From 6074b9d12b70757fe68ab2b4da059ea363c4df04 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 7 Aug 2023 22:34:19 +0000 Subject: [PATCH] Update LKG for 5.2.1 RC. --- lib/lib.es2015.core.d.ts | 4 +- lib/lib.es2020.bigint.d.ts | 8 +- lib/lib.es5.d.ts | 36 +- lib/tsc.js | 879 ++++++++++++--------- lib/tsserver.js | 1489 +++++++++++++++++++++++------------- lib/tsserverlibrary.d.ts | 25 +- lib/tsserverlibrary.js | 1487 ++++++++++++++++++++++------------- lib/typescript.d.ts | 16 +- lib/typescript.js | 1433 ++++++++++++++++++++++------------ lib/typingsInstaller.js | 195 +++-- 10 files changed, 3555 insertions(+), 2017 deletions(-) diff --git a/lib/lib.es2015.core.d.ts b/lib/lib.es2015.core.d.ts index 1ca098d8a4d6d..ecd2e029ef0f8 100644 --- a/lib/lib.es2015.core.d.ts +++ b/lib/lib.es2015.core.d.ts @@ -56,10 +56,10 @@ interface Array { * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. If start is omitted, `0` is used. + * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ - copyWithin(target: number, start?: number, end?: number): this; + copyWithin(target: number, start: number, end?: number): this; } interface ArrayConstructor { diff --git a/lib/lib.es2020.bigint.d.ts b/lib/lib.es2020.bigint.d.ts index f7727a6ac5071..73df22e21ebf7 100644 --- a/lib/lib.es2020.bigint.d.ts +++ b/lib/lib.es2020.bigint.d.ts @@ -165,10 +165,10 @@ interface BigInt64Array { * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. If start is omitted, `0` is used. + * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ - copyWithin(target: number, start?: number, end?: number): this; + copyWithin(target: number, start: number, end?: number): this; /** Yields index, value pairs for every entry in the array. */ entries(): IterableIterator<[number, bigint]>; @@ -437,10 +437,10 @@ interface BigUint64Array { * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. If start is omitted, `0` is used. + * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ - copyWithin(target: number, start?: number, end?: number): this; + copyWithin(target: number, start: number, end?: number): this; /** Yields index, value pairs for every entry in the array. */ entries(): IterableIterator<[number, bigint]>; diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 491c422bdc5c6..a88d3b6a0ddd6 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1889,10 +1889,10 @@ interface Int8Array { * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. If start is omitted, `0` is used. + * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ - copyWithin(target: number, start?: number, end?: number): this; + copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. @@ -2171,10 +2171,10 @@ interface Uint8Array { * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. If start is omitted, `0` is used. + * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ - copyWithin(target: number, start?: number, end?: number): this; + copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. @@ -2453,10 +2453,10 @@ interface Uint8ClampedArray { * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. If start is omitted, `0` is used. + * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ - copyWithin(target: number, start?: number, end?: number): this; + copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. @@ -2734,10 +2734,10 @@ interface Int16Array { * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. If start is omitted, `0` is used. + * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ - copyWithin(target: number, start?: number, end?: number): this; + copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. @@ -3016,10 +3016,10 @@ interface Uint16Array { * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. If start is omitted, `0` is used. + * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ - copyWithin(target: number, start?: number, end?: number): this; + copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. @@ -3298,10 +3298,10 @@ interface Int32Array { * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. If start is omitted, `0` is used. + * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ - copyWithin(target: number, start?: number, end?: number): this; + copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. @@ -3580,10 +3580,10 @@ interface Uint32Array { * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. If start is omitted, `0` is used. + * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ - copyWithin(target: number, start?: number, end?: number): this; + copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. @@ -3861,10 +3861,10 @@ interface Float32Array { * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. If start is omitted, `0` is used. + * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ - copyWithin(target: number, start?: number, end?: number): this; + copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. @@ -4144,10 +4144,10 @@ interface Float64Array { * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. If start is omitted, `0` is used. + * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ - copyWithin(target: number, start?: number, end?: number): this; + copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. diff --git a/lib/tsc.js b/lib/tsc.js index 61b80bb6c91f6..a00b1dc780e04 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -908,7 +908,7 @@ function identity(x) { function toLowerCase(x) { return x.toLowerCase(); } -var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g; +var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_. ]+/g; function toFileNameLowerCase(x) { return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x; } @@ -1145,8 +1145,8 @@ function unorderedRemoveFirstItemWhere(array, predicate) { } return false; } -function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames ? identity : toFileNameLowerCase; +function createGetCanonicalFileName(useCaseSensitiveFileNames2) { + return useCaseSensitiveFileNames2 ? identity : toFileNameLowerCase; } function patternText({ prefix, suffix }) { return `${prefix}*${suffix}`; @@ -1526,7 +1526,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, return func.name; } else { const text = Function.prototype.toString.call(func); - const match = /^function\s+([\w\$]+)\s*\(/.exec(text); + const match = /^function\s+([\w$]+)\s*\(/.exec(text); return match ? match[1] : ""; } } @@ -2309,7 +2309,7 @@ ${lanes.join("\n")} })(Debug || (Debug = {})); // src/compiler/semver.ts -var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; +var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; var prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; @@ -3762,7 +3762,8 @@ var SignatureFlags = /* @__PURE__ */ ((SignatureFlags4) => { SignatureFlags4[SignatureFlags4["IsOuterCallChain"] = 16] = "IsOuterCallChain"; SignatureFlags4[SignatureFlags4["IsUntypedSignatureInJSFile"] = 32] = "IsUntypedSignatureInJSFile"; SignatureFlags4[SignatureFlags4["IsNonInferrable"] = 64] = "IsNonInferrable"; - SignatureFlags4[SignatureFlags4["PropagatingFlags"] = 39] = "PropagatingFlags"; + SignatureFlags4[SignatureFlags4["IsSignatureCandidateForOverloadFailure"] = 128] = "IsSignatureCandidateForOverloadFailure"; + SignatureFlags4[SignatureFlags4["PropagatingFlags"] = 167] = "PropagatingFlags"; SignatureFlags4[SignatureFlags4["CallChainFlags"] = 24] = "CallChainFlags"; return SignatureFlags4; })(SignatureFlags || {}); @@ -4173,10 +4174,10 @@ function createDynamicPriorityPollingWatchFile(host) { pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === 250 /* Low */ ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingInterval === 250 /* Low */ ? "pollLowPollingIntervalQueue" : "pollPollingIntervalQueue", pollingIntervalQueue(pollingInterval)); } } -function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) { +function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2) { const fileWatcherCallbacks = createMultiMap(); const dirWatchers = /* @__PURE__ */ new Map(); - const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames2); return nonPollingWatchFile; function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) { const filePath = toCanonicalName(fileName); @@ -4252,8 +4253,8 @@ function createFixedChunkSizePollingWatchFile(host) { pollScheduled = host.setTimeout(pollQueue, 2e3 /* High */, "pollQueue"); } } -function createSingleWatcherPerName(cache, useCaseSensitiveFileNames, name, callback, createWatcher) { - const toCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); +function createSingleWatcherPerName(cache, useCaseSensitiveFileNames2, name, callback, createWatcher) { + const toCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const path = toCanonicalFileName(name); const existing = cache.get(path); if (existing) { @@ -4305,7 +4306,7 @@ function setSysLog(logger) { } function createDirectoryWatcherSupportingRecursive({ watchDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, getAccessibleSortedChildDirectories, fileSystemEntryExists, @@ -4317,8 +4318,8 @@ function createDirectoryWatcherSupportingRecursive({ const callbackCache = createMultiMap(); const cacheToUpdateChildWatches = /* @__PURE__ */ new Map(); let timerToUpdateChildWatches; - const filePathComparer = getStringComparer(!useCaseSensitiveFileNames); - const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames); + const filePathComparer = getStringComparer(!useCaseSensitiveFileNames2); + const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames2); return (dirName, callback, recursive, options) => recursive ? createDirectoryWatcher(dirName, options, callback) : watchDirectory(dirName, callback, recursive, options); function createDirectoryWatcher(dirName, options, callback) { const dirPath = toCanonicalFilePath(dirName); @@ -4485,12 +4486,12 @@ function createDirectoryWatcherSupportingRecursive({ } } function isIgnoredPath(path, options) { - return some(ignoredPaths, (searchPath) => isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames, getCurrentDirectory); + return some(ignoredPaths, (searchPath) => isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames2, getCurrentDirectory); } function isInPath(path, searchPath) { if (stringContains(path, searchPath)) return true; - if (useCaseSensitiveFileNames) + if (useCaseSensitiveFileNames2) return false; return stringContains(toCanonicalFilePath(path), searchPath); } @@ -4508,14 +4509,14 @@ function createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModi } }; } -function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames, getCurrentDirectory) { - return ((options == null ? void 0 : options.excludeDirectories) || (options == null ? void 0 : options.excludeFiles)) && (matchesExclude(pathToCheck, options == null ? void 0 : options.excludeFiles, useCaseSensitiveFileNames, getCurrentDirectory()) || matchesExclude(pathToCheck, options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames, getCurrentDirectory())); +function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames2, getCurrentDirectory) { + return ((options == null ? void 0 : options.excludeDirectories) || (options == null ? void 0 : options.excludeFiles)) && (matchesExclude(pathToCheck, options == null ? void 0 : options.excludeFiles, useCaseSensitiveFileNames2, getCurrentDirectory()) || matchesExclude(pathToCheck, options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2, getCurrentDirectory())); } -function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory) { +function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory) { return (eventName, relativeFileName) => { if (eventName === "rename") { const fileName = !relativeFileName ? directoryName : normalizePath(combinePaths(directoryName, relativeFileName)); - if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames, getCurrentDirectory)) { + if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames2, getCurrentDirectory)) { callback(fileName); } } @@ -4528,7 +4529,7 @@ function createSystemWatchFunctions({ clearTimeout: clearTimeout2, fsWatchWorker, fileSystemEntryExists, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories, @@ -4600,7 +4601,7 @@ function createSystemWatchFunctions({ ); case 5 /* UseFsEventsOnParentDirectory */: if (!nonPollingWatchFile) { - nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames); + nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2); } return nonPollingWatchFile(fileName, callback, pollingInterval, getFallbackOptions(options)); default: @@ -4649,7 +4650,7 @@ function createSystemWatchFunctions({ return fsWatch( directoryName, 1 /* Directory */, - createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), + createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */, getFallbackOptions(options) @@ -4657,7 +4658,7 @@ function createSystemWatchFunctions({ } if (!hostRecursiveDirectoryWatcher) { hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fileSystemEntryExists, getAccessibleSortedChildDirectories, @@ -4703,7 +4704,7 @@ function createSystemWatchFunctions({ return fsWatch( directoryName, 1 /* Directory */, - createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), + createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */, getFallbackOptions(watchDirectoryOptions) @@ -4731,7 +4732,7 @@ function createSystemWatchFunctions({ function pollingWatchFile(fileName, callback, pollingInterval, options) { return createSingleWatcherPerName( pollingWatches, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, fileName, callback, (cb) => pollingWatchFileWorker(fileName, cb, pollingInterval, options) @@ -4740,7 +4741,7 @@ function createSystemWatchFunctions({ function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { return createSingleWatcherPerName( recursive ? fsWatchesRecursive : fsWatches, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, fileOrDirectory, callback, (cb) => fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, cb, recursive, fallbackPollingInterval, fallbackOptions) @@ -4868,7 +4869,7 @@ var sys = (() => { const Buffer = require("buffer").Buffer; const isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; const platform = _os.platform(); - const useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + const useCaseSensitiveFileNames2 = isFileSystemCaseSensitive(); const fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; const executingFilePath = __filename.endsWith("sys.js") ? _path.join(_path.dirname(__dirname), "__fake__.js") : __filename; const fsSupportsRecursiveFsWatch = process.platform === "win32" || process.platform === "darwin"; @@ -4879,7 +4880,7 @@ var sys = (() => { setTimeout, clearTimeout, fsWatchWorker, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fileSystemEntryExists, // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows @@ -4896,7 +4897,7 @@ var sys = (() => { const nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, write(s) { process.stdout.write(s); }, @@ -5025,12 +5026,12 @@ var sys = (() => { for (const node of profile.nodes) { if (node.callFrame.url) { const url = normalizeSlashes(node.callFrame.url); - if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) { + if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames2)) { node.callFrame.url = getRelativePathToDirectoryOrUrl( fileUrlRoot, url, fileUrlRoot, - createGetCanonicalFileName(useCaseSensitiveFileNames), + createGetCanonicalFileName(useCaseSensitiveFileNames2), /*isAbsolutePathAnUrl*/ true ); @@ -5210,7 +5211,7 @@ var sys = (() => { } } function readDirectory(path, extensions, excludes, includes, depth) { - return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); + return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames2, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path, entryKind) { const originalStackTraceLimit = Error.stackTraceLimit; @@ -5763,6 +5764,7 @@ var Diagnostics = { Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, 1 /* Error */, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, 1 /* Error */, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, 1 /* Error */, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1065, 1 /* Error */, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065", "The return type of an async function or method must be the global Promise type."), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, 1 /* Error */, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, 1 /* Error */, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, 1 /* Error */, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), @@ -7465,6 +7467,7 @@ var Diagnostics = { Parameter_modifiers_can_only_be_used_in_TypeScript_files: diag(8012, 1 /* Error */, "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012", "Parameter modifiers can only be used in TypeScript files."), Non_null_assertions_can_only_be_used_in_TypeScript_files: diag(8013, 1 /* Error */, "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013", "Non-null assertions can only be used in TypeScript files."), Type_assertion_expressions_can_only_be_used_in_TypeScript_files: diag(8016, 1 /* Error */, "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016", "Type assertion expressions can only be used in TypeScript files."), + Signature_declarations_can_only_be_used_in_TypeScript_files: diag(8017, 1 /* Error */, "Signature_declarations_can_only_be_used_in_TypeScript_files_8017", "Signature declarations can only be used in TypeScript files."), Report_errors_in_js_files: diag(8019, 3 /* Message */, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, 1 /* Error */, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, 1 /* Error */, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), @@ -8572,7 +8575,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (withMinus) start2--; error(Diagnostics.Octal_literals_are_not_allowed_Use_the_syntax_0, start2, pos - start2, literal); - return { type: 9 /* NumericLiteral */, value: tokenValue }; + return 9 /* NumericLiteral */; } } else { mainFragment = scanNumberFragment(); @@ -8612,20 +8615,18 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } if (tokenFlags & 8192 /* ContainsLeadingZero */) { error(Diagnostics.Decimals_with_leading_zeros_are_not_allowed, start2, end2 - start2); - return { type: 9 /* NumericLiteral */, value: "" + +result }; + tokenValue = "" + +result; + return 9 /* NumericLiteral */; } if (decimalFragment !== void 0 || tokenFlags & 16 /* Scientific */) { checkForIdentifierStartAfterNumericLiteral(start2, decimalFragment === void 0 && !!(tokenFlags & 16 /* Scientific */)); - return { - type: 9 /* NumericLiteral */, - value: "" + +result - // if value is not an integer, it can be safely coerced to a number - }; + tokenValue = "" + +result; + return 9 /* NumericLiteral */; } else { tokenValue = result; const type = checkBigIntSuffix(); checkForIdentifierStartAfterNumericLiteral(start2); - return { type, value: tokenValue }; + return type; } } function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { @@ -9234,7 +9235,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return token = 41 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber().value; + scanNumber(); return token = 9 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { @@ -9352,8 +9353,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan case 55 /* _7 */: case 56 /* _8 */: case 57 /* _9 */: - ({ type: token, value: tokenValue } = scanNumber()); - return token; + return token = scanNumber(); case 58 /* colon */: pos++; return token = 59 /* ColonToken */; @@ -10108,7 +10108,7 @@ function getNodeFlags(node) { var supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; function validateLocaleAndSetLanguage(locale, sys2, errors) { const lowerCaseLocale = locale.toLowerCase(); - const matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); + const matchResult = /^([a-z]+)([_-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -14644,9 +14644,9 @@ function escapeTemplateSubstitution(str) { function hasInvalidEscape(template) { return template && !!(isNoSubstitutionTemplateLiteral(template) ? template.templateFlags : template.head.templateFlags || some(template.templateSpans, (span) => !!span.literal.templateFlags)); } -var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; -var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; -var backtickQuoteEscapedCharsRegExp = /\r\n|[\\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g; +var doubleQuoteEscapedCharsRegExp = /[\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; +var singleQuoteEscapedCharsRegExp = /[\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; +var backtickQuoteEscapedCharsRegExp = /\r\n|[\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g; var escapedCharsMap = new Map(Object.entries({ " ": "\\t", "\v": "\\v", @@ -14691,8 +14691,8 @@ function escapeNonAsciiString(s, quoteChar) { s = escapeString(s, quoteChar); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, (c) => encodeUtf16EscapeSequence(c.charCodeAt(0))) : s; } -var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g; -var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g; +var jsxDoubleQuoteEscapedCharsRegExp = /["\u0000-\u001f\u2028\u2029\u0085]/g; +var jsxSingleQuoteEscapedCharsRegExp = /['\u0000-\u001f\u2028\u2029\u0085]/g; var jsxEscapedCharsMap = new Map(Object.entries({ '"': """, "'": "'" @@ -15064,6 +15064,12 @@ function parameterIsThisKeyword(parameter) { function isThisIdentifier(node) { return !!node && node.kind === 80 /* Identifier */ && identifierIsThisKeyword(node); } +function isInTypeQuery(node) { + return !!findAncestor( + node, + (n) => n.kind === 186 /* TypeQuery */ ? true : n.kind === 80 /* Identifier */ || n.kind === 166 /* QualifiedName */ ? false : "quit" + ); +} function isThisInTypeQuery(node) { if (!isThisIdentifier(node)) { return false; @@ -15527,7 +15533,7 @@ function isPrototypeAccess(node) { return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype"; } function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return node.parent.kind === 166 /* QualifiedName */ && node.parent.right === node || node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.name === node; + return node.parent.kind === 166 /* QualifiedName */ && node.parent.right === node || node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.name === node || node.parent.kind === 236 /* MetaProperty */ && node.parent.name === node; } function isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(node) { return isQualifiedName(node.parent) && node.parent.right === node || isPropertyAccessExpression(node.parent) && node.parent.name === node || isJSDocMemberName(node.parent) && node.parent.right === node; @@ -16381,6 +16387,9 @@ function getAllowJSCompilerOption(compilerOptions) { function getUseDefineForClassFields(compilerOptions) { return compilerOptions.useDefineForClassFields === void 0 ? getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ : compilerOptions.useDefineForClassFields; } +function getEmitStandardClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields !== false && getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */; +} function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return optionsHaveChanges(oldOptions, newOptions, semanticDiagnosticsOptionDeclarations); } @@ -16478,7 +16487,7 @@ function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { return s !== void 0 && (getCanonicalFileName(s) === "node_modules" || startsWith(s, "@")); } -var reservedCharacterPattern = /[^\w\s\/]/g; +var reservedCharacterPattern = /[^\w\s/]/g; var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; var commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = `(?!(${commonPackageFolders.join("|")})(/|$))`; @@ -16591,7 +16600,7 @@ function getSubPatternFromSpec(spec, basePath, usage, { singleAsteriskRegexFragm function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } -function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { +function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames2, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); const absolutePath = combinePaths(currentDirectory, path); @@ -16600,22 +16609,22 @@ function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNa includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), - basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames2) }; } -function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { - return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); +function getRegexFromPattern(pattern, useCaseSensitiveFileNames2) { + return new RegExp(pattern, useCaseSensitiveFileNames2 ? "" : "i"); } -function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) { +function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames2, currentDirectory, depth, getFileSystemEntries, realpath) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); - const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, useCaseSensitiveFileNames)); - const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); - const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames2, currentDirectory); + const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, useCaseSensitiveFileNames2)); + const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames2); + const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames2); const results = includeFileRegexes ? includeFileRegexes.map(() => []) : [[]]; const visited = /* @__PURE__ */ new Map(); - const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames); + const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames2); for (const basePath of patterns.basePaths) { visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); } @@ -16657,7 +16666,7 @@ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNa } } } -function getBasePaths(path, includes, useCaseSensitiveFileNames) { +function getBasePaths(path, includes, useCaseSensitiveFileNames2) { const basePaths = [path]; if (includes) { const includeBasePaths = []; @@ -16665,9 +16674,9 @@ function getBasePaths(path, includes, useCaseSensitiveFileNames) { const absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); includeBasePaths.push(getIncludeBasePath(absolute)); } - includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames)); + includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames2)); for (const includeBasePath of includeBasePaths) { - if (every(basePaths, (basePath) => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames))) { + if (every(basePaths, (basePath) => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames2))) { basePaths.push(includeBasePath); } } @@ -17405,6 +17414,18 @@ function getTextOfJsxNamespacedName(node) { function intrinsicTagNameToString(node) { return isIdentifier(node) ? idText(node) : getTextOfJsxNamespacedName(node); } +function isTypeUsableAsPropertyName(type) { + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); +} +function getPropertyNameFromType(type) { + if (type.flags & 8192 /* UniqueESSymbol */) { + return type.escapedName; + } + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + return escapeLeadingUnderscores("" + type.value); + } + return Debug.fail(); +} // src/compiler/factory/baseNodeFactory.ts function createBaseNodeFactory() { @@ -23889,7 +23910,7 @@ var addDisposableResourceHelper = { text: ` var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { if (value !== null && value !== void 0) { - if (typeof value !== "object") throw new TypeError("Object expected."); + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); @@ -25531,7 +25552,7 @@ function createAccessorPropertyBackingField(factory2, node, modifiers, initializ initializer ); } -function createAccessorPropertyGetRedirector(factory2, node, modifiers, name) { +function createAccessorPropertyGetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { return factory2.createGetAccessorDeclaration( modifiers, name, @@ -25541,7 +25562,7 @@ function createAccessorPropertyGetRedirector(factory2, node, modifiers, name) { factory2.createBlock([ factory2.createReturnStatement( factory2.createPropertyAccessExpression( - factory2.createThis(), + receiver, factory2.getGeneratedPrivateNameForNode( node.name, /*prefix*/ @@ -25553,7 +25574,7 @@ function createAccessorPropertyGetRedirector(factory2, node, modifiers, name) { ]) ); } -function createAccessorPropertySetRedirector(factory2, node, modifiers, name) { +function createAccessorPropertySetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { return factory2.createSetAccessorDeclaration( modifiers, name, @@ -25568,7 +25589,7 @@ function createAccessorPropertySetRedirector(factory2, node, modifiers, name) { factory2.createExpressionStatement( factory2.createAssignment( factory2.createPropertyAccessExpression( - factory2.createThis(), + receiver, factory2.getGeneratedPrivateNameForNode( node.name, /*prefix*/ @@ -26594,7 +26615,8 @@ var Parser; nextToken(); const statements = parseList(0 /* SourceElements */, parseStatement); Debug.assert(token() === 1 /* EndOfFileToken */); - const endOfFileToken = addJSDocComment(parseTokenNode()); + const endHasJSDoc = hasPrecedingJSDocComment(); + const endOfFileToken = withJSDoc(parseTokenNode(), endHasJSDoc); const sourceFile = createSourceFile2(fileName, languageVersion2, scriptKind2, isDeclarationFile, statements, endOfFileToken, sourceFlags, setExternalModuleIndicator2); processCommentPragmas(sourceFile, sourceText); processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); @@ -26614,11 +26636,11 @@ var Parser; parseDiagnostics.push(createDetachedDiagnostic(fileName, pos, end, diagnostic)); } } - function withJSDoc(node, hasJSDoc) { - return hasJSDoc ? addJSDocComment(node) : node; - } let hasDeprecatedTag = false; - function addJSDocComment(node) { + function withJSDoc(node, hasJSDoc) { + if (!hasJSDoc) { + return node; + } Debug.assert(!node.jsDoc); const jsDoc = mapDefined(getJSDocCommentRanges(node, sourceText), (comment) => JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); if (jsDoc.length) @@ -27412,6 +27434,9 @@ var Parser; case 22 /* HeritageClauses */: return isHeritageClause2(); case 23 /* ImportOrExportSpecifiers */: + if (token() === 161 /* FromKeyword */ && lookAhead(nextTokenIsStringLiteral)) { + return false; + } return tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */; @@ -27770,6 +27795,9 @@ var Parser; case 22 /* HeritageClauses */: return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_expected); case 23 /* ImportOrExportSpecifiers */: + if (token() === 161 /* FromKeyword */) { + return parseErrorAtCurrentToken(Diagnostics._0_expected, "}"); + } return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 13 /* JsxAttributes */: return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); @@ -29127,12 +29155,14 @@ var Parser; return arrowExpression; } const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); if (expr.kind === 80 /* Identifier */ && token() === 39 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression( pos, expr, allowReturnTypeInArrowFunction, + hasJSDoc, /*asyncModifier*/ void 0 ); @@ -29178,7 +29208,7 @@ var Parser; ), pos); } } - function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, asyncModifier) { + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier) { Debug.assert(token() === 39 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); const parameter = factory2.createParameterDeclaration( /*modifiers*/ @@ -29211,7 +29241,7 @@ var Parser; equalsGreaterThanToken, body ); - return addJSDocComment(finishNode(node, pos)); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { const triState = isParenthesizedArrowFunctionExpression(); @@ -29339,9 +29369,10 @@ var Parser; if (token() === 134 /* AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const asyncModifier = parseModifiersForArrowFunction(); const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); - return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier); } } return void 0; @@ -30702,10 +30733,14 @@ var Parser; case 124 /* ProtectedKeyword */: case 125 /* PublicKeyword */: case 148 /* ReadonlyKeyword */: + const previousToken = token(); nextToken(); if (scanner.hasPrecedingLineBreak()) { return false; } + if (previousToken === 138 /* DeclareKeyword */ && token() === 156 /* TypeKeyword */) { + return true; + } continue; case 162 /* GlobalKeyword */: nextToken(); @@ -31015,6 +31050,9 @@ var Parser; return void 0; } } + function nextTokenIsStringLiteral() { + return nextToken() === 11 /* StringLiteral */; + } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); return !scanner.hasPrecedingLineBreak() && (isIdentifier2() || token() === 11 /* StringLiteral */); @@ -31067,14 +31105,14 @@ var Parser; function parseObjectBindingPattern() { const pos = getNodePos(); parseExpected(19 /* OpenBraceToken */); - const elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + const elements = allowInAnd(() => parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement)); parseExpected(20 /* CloseBraceToken */); return finishNode(factory2.createObjectBindingPattern(elements), pos); } function parseArrayBindingPattern() { const pos = getNodePos(); parseExpected(23 /* OpenBracketToken */); - const elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + const elements = allowInAnd(() => parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement)); parseExpected(24 /* CloseBracketToken */); return finishNode(factory2.createArrayBindingPattern(elements), pos); } @@ -31592,6 +31630,9 @@ var Parser; } function parseTypeAliasDeclaration(pos, hasJSDoc, modifiers) { parseExpected(156 /* TypeKeyword */); + if (scanner.hasPrecedingLineBreak()) { + parseErrorAtCurrentToken(Diagnostics.Line_break_not_permitted_here); + } const name = parseIdentifier(); const typeParameters = parseTypeParameters(); parseExpected(64 /* EqualsToken */); @@ -32574,7 +32615,7 @@ var Parser; typeExpression = tryParseTypeExpression(); } const comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText); - const nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent2); + const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target, indent2); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -32860,7 +32901,7 @@ var Parser; case 60 /* AtToken */: if (canParseTag) { const child = tryParseChildTag(target, indent2); - if (child && (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + if (child && (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */) && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } return child; @@ -33493,7 +33534,7 @@ function getNamedArgRegEx(name) { return result; } var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; -var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; +var singleLinePragmaRegEx = /^\/\/\/?\s*@([^\s:]+)(.*)\s*$/im; function extractPragmas(pragmas, range, text) { const tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text); if (tripleSlash) { @@ -34093,6 +34134,7 @@ var commandOptionsWithoutBuild = [ { name: "checkJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: Diagnostics.JavaScript_Support, description: Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files, @@ -34319,7 +34361,7 @@ var commandOptionsWithoutBuild = [ strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, - defaultValueDescription: false + defaultValueDescription: Diagnostics.false_unless_strict_is_set }, { name: "alwaysStrict", @@ -36503,19 +36545,19 @@ function getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, e const wildcardFiles = arrayFrom(wildcardFileMap.values()); return literalFiles.concat(wildcardFiles, arrayFrom(wildCardJsonFileMap.values())); } -function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames, currentDirectory) { +function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames2, currentDirectory) { const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = spec; if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) return false; basePath = normalizePath(basePath); - const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames); + const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames2); if (validatedFilesSpec) { for (const fileName of validatedFilesSpec) { if (keyMapper(getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck) return false; } } - return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath); + return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath); } function invalidDotDotAfterRecursiveWildcard(s) { const wildcardIndex = startsWith(s, "**/") ? 0 : s.indexOf("/**/"); @@ -36525,17 +36567,17 @@ function invalidDotDotAfterRecursiveWildcard(s) { const lastDotIndex = endsWith(s, "/..") ? s.length : s.lastIndexOf("/../"); return lastDotIndex > wildcardIndex; } -function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory) { +function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory) { return matchesExcludeWorker( pathToCheck, filter(excludeSpecs, (spec) => !invalidDotDotAfterRecursiveWildcard(spec)), - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, currentDirectory ); } -function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath) { +function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath) { const excludePattern = getRegularExpressionForWildcard(excludeSpecs, combinePaths(normalizePath(currentDirectory), basePath), "exclude"); - const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames); + const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames2); if (!excludeRegex) return false; if (excludeRegex.test(pathToCheck)) @@ -36565,9 +36607,9 @@ function specToDiagnostic(spec, disallowTrailingRecursion) { return [Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec]; } } -function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }, path, useCaseSensitiveFileNames) { +function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }, path, useCaseSensitiveFileNames2) { const rawExcludeRegex = getRegularExpressionForWildcard(exclude, path, "exclude"); - const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames2 ? "" : "i"); const wildcardDirectories = {}; if (include !== void 0) { const recursiveKeys = []; @@ -36576,7 +36618,7 @@ function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExclu if (excludeRegex && excludeRegex.test(spec)) { continue; } - const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); + const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2); if (match) { const { key, flags } = match; const existingFlags = wildcardDirectories[key]; @@ -36591,7 +36633,7 @@ function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExclu for (const key in wildcardDirectories) { if (hasProperty(wildcardDirectories, key)) { for (const recursiveKey of recursiveKeys) { - if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames2)) { delete wildcardDirectories[key]; } } @@ -36600,20 +36642,20 @@ function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExclu } return wildcardDirectories; } -function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { +function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2) { const match = wildcardDirectoryPattern.exec(spec); if (match) { const questionWildcardIndex = spec.indexOf("?"); const starWildcardIndex = spec.indexOf("*"); const lastDirectorySeperatorIndex = spec.lastIndexOf(directorySeparator); return { - key: useCaseSensitiveFileNames ? match[0] : toFileNameLowerCase(match[0]), + key: useCaseSensitiveFileNames2 ? match[0] : toFileNameLowerCase(match[0]), flags: questionWildcardIndex !== -1 && questionWildcardIndex < lastDirectorySeperatorIndex || starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex ? 1 /* Recursive */ : 0 /* None */ }; } if (isImplicitGlob(spec.substring(spec.lastIndexOf(directorySeparator) + 1))) { return { - key: removeTrailingDirectorySeparator(useCaseSensitiveFileNames ? spec : toFileNameLowerCase(spec)), + key: removeTrailingDirectorySeparator(useCaseSensitiveFileNames2 ? spec : toFileNameLowerCase(spec)), flags: 1 /* Recursive */ }; } @@ -36895,8 +36937,8 @@ function getDefaultTypeRoots(currentDirectory) { } var nodeModulesAtTypes = combinePaths("node_modules", "@types"); function arePathsEqual(path1, path2, host) { - const useCaseSensitiveFileNames = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; - return comparePaths(path1, path2, !useCaseSensitiveFileNames) === 0 /* EqualTo */; + const useCaseSensitiveFileNames2 = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; + return comparePaths(path1, path2, !useCaseSensitiveFileNames2) === 0 /* EqualTo */; } function getOriginalAndResolvedFileName(fileName, host, traceEnabled) { const resolvedFileName = realPath(fileName, host, traceEnabled); @@ -38291,6 +38333,9 @@ function loadModuleFromSelfNameReference(extensions, moduleName, directory, stat } const trailingParts = parts.slice(nameParts.length); const subpath = !length(trailingParts) ? "." : `.${directorySeparator}${trailingParts.join(directorySeparator)}`; + if (getAllowJSCompilerOption(state.compilerOptions) && !pathContainsNodeModules(directory)) { + return loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference); + } const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */); const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */); return loadModuleFromExports(scope, priorityExtensions, subpath, state, cache, redirectedReference) || loadModuleFromExports(scope, secondaryExtensions, subpath, state, cache, redirectedReference); @@ -38638,13 +38683,10 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec function combineDirectoryPath(root, dir) { return ensureTrailingDirectorySeparator(combinePaths(root, dir)); } - function useCaseSensitiveFileNames() { - return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); - } function tryLoadInputFileForPath(finalPath, entry, packagePath, isImports2) { var _a, _b, _c, _d; - if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames()) : true)) { - const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames }); + if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true)) { + const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames: () => useCaseSensitiveFileNames(state) }); const commonSourceDirGuesses = []; if (state.compilerOptions.rootDir || state.compilerOptions.composite && state.compilerOptions.configFilePath) { const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, () => [], ((_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)) || "", getCanonicalFileName)); @@ -38673,7 +38715,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec for (const commonSourceDirGuess of commonSourceDirGuesses) { const candidateDirectories = getOutputDirectoriesForBaseDirectory(commonSourceDirGuess); for (const candidateDir of candidateDirectories) { - if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames())) { + if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames(state))) { const pathFragment = finalPath.slice(candidateDir.length + 1); const possibleInputBase = combinePaths(commonSourceDirGuess, pathFragment); const jsAndDtsExtensions = [".mjs" /* Mjs */, ".cjs" /* Cjs */, ".js" /* Js */, ".json" /* Json */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */, ".d.ts" /* Dts */]; @@ -38683,7 +38725,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec for (const possibleExt of inputExts) { if (!extensionIsOk(extensions, possibleExt)) continue; - const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames()); + const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames(state)); if (state.host.fileExists(possibleInputWithInputExtension)) { return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( extensions, @@ -39100,6 +39142,9 @@ function traceIfEnabled(state, diagnostic, ...args) { trace(state.host, diagnostic, ...args); } } +function useCaseSensitiveFileNames(state) { + return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); +} // src/compiler/binder.ts function getModuleInstanceState(node, visited) { @@ -39207,6 +39252,9 @@ function getModuleInstanceStateForAliasTarget(specifier, visited) { if (found === 1 /* Instantiated */) { return found; } + if (statement.kind === 271 /* ImportEqualsDeclaration */) { + found = 1 /* Instantiated */; + } } } if (found !== void 0) { @@ -42517,7 +42565,9 @@ function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, hos for (const { ending, value } of candidates) { if (value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ ending, value })) { const matchedStar = value.substring(prefix.length, value.length - suffix.length); - return pathIsRelative(matchedStar) ? void 0 : key.replace("*", matchedStar); + if (!pathIsRelative(matchedStar)) { + return key.replace("*", matchedStar); + } } } } else if (some(candidates, (c) => c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, (c) => c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) { @@ -42589,7 +42639,7 @@ function tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, for (const key of getOwnKeys(exports)) { if (key === "default" || conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(conditions, key)) { const subTarget = exports[key]; - const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions); + const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions, mode); if (result) { return result; } @@ -43003,6 +43053,7 @@ function createTypeChecker(host) { var moduleKind = getEmitModuleKind(compilerOptions); var legacyDecorators = !!compilerOptions.experimentalDecorators; var useDefineForClassFields = getUseDefineForClassFields(compilerOptions); + var emitStandardClassFields = getEmitStandardClassFields(compilerOptions); var allowSyntheticDefaultImports = getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -43093,7 +43144,7 @@ function createTypeChecker(host) { return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, - getParameterIdentifierNameAtPosition, + getParameterIdentifierInfoAtPosition, getPromisedTypeOfPromise, getAwaitedType: (type) => getAwaitedType(type), getReturnTypeOfSignature, @@ -43746,7 +43797,7 @@ function createTypeChecker(host) { }; var amalgamatedDuplicates; var reverseMappedCache = /* @__PURE__ */ new Map(); - var inInferTypeForHomomorphicMappedType = false; + var homomorphicMappedTypeInferenceStack = []; var ambientModulesCache; var patternAmbientModules; var patternAmbientModuleAugmentations; @@ -44306,7 +44357,7 @@ function createTypeChecker(host) { return symbol; } if (symbol.flags & 2097152 /* Alias */) { - const targetFlags = getAllSymbolFlags(symbol); + const targetFlags = getSymbolFlags(symbol); if (targetFlags & meaning) { return symbol; } @@ -44357,7 +44408,7 @@ function createTypeChecker(host) { false ); } else if (isParameterPropertyDeclaration(declaration, declaration.parent)) { - return !(getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); + return !(emitStandardClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } @@ -44371,7 +44422,7 @@ function createTypeChecker(host) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { + if (emitStandardClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration( declaration, usage, @@ -44495,7 +44546,7 @@ function createTypeChecker(host) { return requiresScopeChangeWorker(node.name); case 172 /* PropertyDeclaration */: if (hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !useDefineForClassFields; + return !emitStandardClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -44534,7 +44585,7 @@ function createTypeChecker(host) { if (name === "const" && isConstAssertion(location)) { return void 0; } - if (isModuleDeclaration(location) && lastLocation && location.name === lastLocation) { + if (isModuleOrEnumDeclaration(location) && lastLocation && location.name === lastLocation) { lastLocation = location; location = location.parent; } @@ -44766,7 +44817,7 @@ function createTypeChecker(host) { } } function checkAndReportErrorForInvalidInitializer() { - if (propertyWithInvalidInitializer && !(useDefineForClassFields && getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */)) { + if (propertyWithInvalidInitializer && !emitStandardClassFields) { error( errorLocation, errorLocation && propertyWithInvalidInitializer.type && textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) ? Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor : Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, @@ -45066,7 +45117,7 @@ function createTypeChecker(host) { /*isUse*/ false )); - const allFlags = symbol && getAllSymbolFlags(symbol); + const allFlags = symbol && getSymbolFlags(symbol); if (symbol && allFlags !== void 0 && !(allFlags & 111551 /* Value */)) { const rawName = unescapeLeadingUnderscores(name); if (isES2015OrLaterConstructorName(name)) { @@ -45802,11 +45853,23 @@ function createTypeChecker(host) { } return void 0; } - function getAllSymbolFlags(symbol) { - let flags = symbol.flags; + function getSymbolFlags(symbol, excludeTypeOnlyMeanings, excludeLocalMeanings) { + const typeOnlyDeclaration = excludeTypeOnlyMeanings && getTypeOnlyAliasDeclaration(symbol); + const typeOnlyDeclarationIsExportStar = typeOnlyDeclaration && isExportDeclaration(typeOnlyDeclaration); + const typeOnlyResolution = typeOnlyDeclaration && (typeOnlyDeclarationIsExportStar ? resolveExternalModuleName( + typeOnlyDeclaration.moduleSpecifier, + typeOnlyDeclaration.moduleSpecifier, + /*ignoreErrors*/ + true + ) : resolveAlias(typeOnlyDeclaration.symbol)); + const typeOnlyExportStarTargets = typeOnlyDeclarationIsExportStar && typeOnlyResolution ? getExportsOfModule(typeOnlyResolution) : void 0; + let flags = excludeLocalMeanings ? 0 /* None */ : symbol.flags; let seenSymbols; while (symbol.flags & 2097152 /* Alias */) { - const target = resolveAlias(symbol); + const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); + if (!typeOnlyDeclarationIsExportStar && target === typeOnlyResolution || (typeOnlyExportStarTargets == null ? void 0 : typeOnlyExportStarTargets.get(target.escapedName)) === target) { + break; + } if (target === unknownSymbol) { return 67108863 /* All */; } @@ -45864,7 +45927,7 @@ function createTypeChecker(host) { } if (links.typeOnlyDeclaration) { const resolved = links.typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? resolveSymbol(getExportsOfModule(links.typeOnlyDeclaration.symbol.parent).get(links.typeOnlyExportStarName || symbol.escapedName)) : resolveAlias(links.typeOnlyDeclaration.symbol); - return getAllSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0; + return getSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0; } return void 0; } @@ -45875,7 +45938,11 @@ function createTypeChecker(host) { const symbol = getSymbolOfDeclaration(node); const target = resolveAlias(symbol); if (target) { - const markAlias = target === unknownSymbol || getAllSymbolFlags(target) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */); + const markAlias = target === unknownSymbol || getSymbolFlags( + symbol, + /*excludeTypeOnlyMeanings*/ + true + ) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -45890,7 +45957,7 @@ function createTypeChecker(host) { if (!node) return Debug.fail(); if (isInternalModuleImportEqualsDeclaration(node)) { - if (getAllSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { + if (getSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { checkExpressionCached(node.moduleReference); } } @@ -46150,7 +46217,7 @@ function createTypeChecker(host) { return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation) : void 0; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) { - var _a, _b, _c, _d, _e, _f, _g, _h, _i; + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; if (startsWith(moduleReference, "@types/")) { const diag2 = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; const withoutAtTypePrefix = removePrefix(moduleReference, "@types/"); @@ -46185,8 +46252,11 @@ function createTypeChecker(host) { ); } } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) { - const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); - error(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension); + const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); + if (!((importOrExport == null ? void 0 : importOrExport.isTypeOnly) || findAncestor(location, isImportTypeNode))) { + const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); + error(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension); + } } if (sourceFile.symbol) { if (resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) { @@ -46203,7 +46273,7 @@ function createTypeChecker(host) { if (moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */) { const isSyncImport = currentSourceFile.impliedNodeFormat === 1 /* CommonJS */ && !findAncestor(location, isImportCall) || !!findAncestor(location, isImportEqualsDeclaration); const overrideClauseHost = findAncestor(location, (l) => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l)); - const overrideClause = overrideClauseHost && isImportTypeNode(overrideClauseHost) ? (_h = overrideClauseHost.assertions) == null ? void 0 : _h.assertClause : overrideClauseHost == null ? void 0 : overrideClauseHost.assertClause; + const overrideClause = overrideClauseHost && isImportTypeNode(overrideClauseHost) ? (_i = overrideClauseHost.assertions) == null ? void 0 : _i.assertClause : overrideClauseHost == null ? void 0 : overrideClauseHost.assertClause; if (isSyncImport && sourceFile.impliedNodeFormat === 99 /* ESNext */ && !getResolutionModeOverrideForClause(overrideClause)) { if (findAncestor(location, isImportEqualsDeclaration)) { error(errorNode, Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); @@ -46306,7 +46376,7 @@ function createTypeChecker(host) { error(errorNode, Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else if (mode === 99 /* ESNext */ && resolutionIsNode16OrNext && isExtensionlessRelativePathImport) { const absoluteRef = getNormalizedAbsolutePath(moduleReference, getDirectoryPath(currentSourceFile.path)); - const suggestedExt = (_i = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _i[1]; + const suggestedExt = (_j = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _j[1]; if (suggestedExt) { error( errorNode, @@ -46738,7 +46808,7 @@ function createTypeChecker(host) { return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 && symbol.exportSymbol || symbol); } function symbolIsValue(symbol, includeTypeOnlyMembers) { - return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getAllSymbolFlags(symbol) & 111551 /* Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); + return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getSymbolFlags(symbol, !includeTypeOnlyMembers) & 111551 /* Value */); } function findConstructorDeclaration(node) { const members = node.members; @@ -47005,7 +47075,7 @@ function createTypeChecker(host) { } const shouldResolveAlias = symbolFromSymbolTable.flags & 2097152 /* Alias */ && !getDeclarationOfKind(symbolFromSymbolTable, 281 /* ExportSpecifier */); symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - const flags = shouldResolveAlias ? getAllSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; + const flags = shouldResolveAlias ? getSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; if (flags & meaning) { qualify = true; return true; @@ -47742,11 +47812,13 @@ function createTypeChecker(host) { return !!type2.target && isMappedTypeHomomorphic(type2.target) && !isMappedTypeHomomorphic(type2); } function createMappedTypeNodeFromType(type2) { + var _a2; Debug.assert(!!(type2.flags & 524288 /* Object */)); const readonlyToken = type2.declaration.readonlyToken ? factory.createToken(type2.declaration.readonlyToken.kind) : void 0; const questionToken = type2.declaration.questionToken ? factory.createToken(type2.declaration.questionToken.kind) : void 0; let appropriateConstraintTypeNode; let newTypeVariable; + const needsModifierPreservingWrapper = !isMappedTypeWithKeyofConstraintDeclaration(type2) && !(getModifiersTypeFromMappedType(type2).flags & 2 /* Unknown */) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && !(getConstraintTypeFromMappedType(type2).flags & 262144 /* TypeParameter */ && ((_a2 = getConstraintOfTypeParameter(getConstraintTypeFromMappedType(type2))) == null ? void 0 : _a2.flags) & 4194304 /* Index */); if (isMappedTypeWithKeyofConstraintDeclaration(type2)) { if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */) { const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T")); @@ -47754,6 +47826,11 @@ function createTypeChecker(host) { newTypeVariable = factory.createTypeReferenceNode(name); } appropriateConstraintTypeNode = factory.createTypeOperatorNode(143 /* KeyOfKeyword */, newTypeVariable || typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)); + } else if (needsModifierPreservingWrapper) { + const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T")); + const name = typeParameterToName(newParam, context); + newTypeVariable = factory.createTypeReferenceNode(name); + appropriateConstraintTypeNode = newTypeVariable; } else { appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context); } @@ -47784,6 +47861,18 @@ function createTypeChecker(host) { result, factory.createKeywordTypeNode(146 /* NeverKeyword */) ); + } else if (needsModifierPreservingWrapper) { + return factory.createConditionalTypeNode( + typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context), + factory.createInferTypeNode(factory.createTypeParameterDeclaration( + /*modifiers*/ + void 0, + factory.cloneNode(newTypeVariable.typeName), + factory.createTypeOperatorNode(143 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)) + )), + result, + factory.createKeywordTypeNode(146 /* NeverKeyword */) + ); } return result; } @@ -48337,6 +48426,7 @@ function createTypeChecker(host) { ); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { + var _a; const suppressAny = context.flags & 256 /* SuppressAnyReturnType */; if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; @@ -48472,6 +48562,20 @@ function createTypeChecker(host) { if (typeArguments) { node.typeArguments = factory.createNodeArray(typeArguments); } + if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 330 /* JSDocSignature */ && signature.declaration.parent.kind === 346 /* JSDocOverloadTag */) { + const comment = getTextOfNode( + signature.declaration.parent.parent, + /*includeTrivia*/ + true + ).slice(2, -2).split(/\r\n|\n|\r/).map((line) => line.replace(/^\s+/, " ")).join("\n"); + addSyntheticLeadingComment( + node, + 3 /* MultiLineCommentTrivia */, + comment, + /*hasTrailingNewLine*/ + true + ); + } cleanup == null ? void 0 : cleanup(); return node; } @@ -49833,7 +49937,7 @@ function createTypeChecker(host) { return !exports ? [] : filter(arrayFrom(exports.values()), (m) => isNamespaceMember(m) && isIdentifierText(m.escapedName, 99 /* ESNext */)); } function isTypeOnlyNamespace(symbol) { - return every(getNamespaceMembersForSerialization(symbol), (m) => !(getAllSymbolFlags(resolveSymbol(m)) & 111551 /* Value */)); + return every(getNamespaceMembersForSerialization(symbol), (m) => !(getSymbolFlags(resolveSymbol(m)) & 111551 /* Value */)); } function serializeModule(symbol, symbolName2, modifierFlags) { const members = getNamespaceMembersForSerialization(symbol); @@ -51541,7 +51645,7 @@ function createTypeChecker(host) { false, definedInMethod && !definedInConstructor )); - if (symbol.valueDeclaration && filterType(widened, (t) => !!(t.flags & ~98304 /* Nullable */)) === neverType) { + if (symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && filterType(widened, (t) => !!(t.flags & ~98304 /* Nullable */)) === neverType) { reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } @@ -52105,7 +52209,7 @@ function createTypeChecker(host) { true ); const declaredType = firstDefined(exportSymbol == null ? void 0 : exportSymbol.declarations, (d) => isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : void 0); - links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getAllSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; + links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } return links.type; } @@ -52820,9 +52924,6 @@ function createTypeChecker(host) { } return type; } - function isTypeUsableAsPropertyName(type) { - return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); - } function isLateBindableName(node) { if (!isComputedPropertyName(node) && !isElementAccessExpression(node)) { return false; @@ -52843,15 +52944,6 @@ function createTypeChecker(host) { function isNonBindableDynamicName(node) { return isDynamicName(node) && !isLateBindableName(node); } - function getPropertyNameFromType(type) { - if (type.flags & 8192 /* UniqueESSymbol */) { - return type.escapedName; - } - if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { - return escapeLeadingUnderscores("" + type.value); - } - return Debug.fail(); - } function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { Debug.assert(!!(getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol."); symbol.flags |= symbolFlags; @@ -52901,6 +52993,7 @@ function createTypeChecker(host) { return links.resolvedSymbol; } function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var _a, _b, _c; const links = getSymbolLinks(symbol); if (!links[resolutionKind]) { const isStatic2 = resolutionKind === "resolvedExports" /* resolvedExports */; @@ -52919,7 +53012,7 @@ function createTypeChecker(host) { } } } - const assignments = symbol.assignmentDeclarationMembers; + const assignments = (((_a = symbol.valueDeclaration) == null ? void 0 : _a.kind) === 219 /* ArrowFunction */ || ((_b = symbol.valueDeclaration) == null ? void 0 : _b.kind) === 218 /* FunctionExpression */) && ((_c = getSymbolOfNode(symbol.valueDeclaration.parent)) == null ? void 0 : _c.assignmentDeclarationMembers) || symbol.assignmentDeclarationMembers; if (assignments) { const decls = arrayFrom(assignments.values()); for (const member of decls) { @@ -53048,7 +53141,7 @@ function createTypeChecker(host) { /*resolvedTypePredicate*/ void 0, sig.minArgumentCount, - sig.flags & 39 /* PropagatingFlags */ + sig.flags & 167 /* PropagatingFlags */ ); result.target = sig.target; result.mapper = sig.mapper; @@ -53349,7 +53442,7 @@ function createTypeChecker(host) { /*resolvedTypePredicate*/ void 0, minArgCount, - (left.flags | right.flags) & 39 /* PropagatingFlags */ + (left.flags | right.flags) & 167 /* PropagatingFlags */ ); result.compositeKind = 1048576 /* Union */; result.compositeSignatures = concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); @@ -53497,20 +53590,17 @@ function createTypeChecker(host) { setStructuredTypeMembers(type, members2, callSignatures, constructSignatures, indexInfos2); return; } - let members = emptySymbols; + let members = getExportsOfSymbol(symbol); let indexInfos; - if (symbol.exports) { - members = getExportsOfSymbol(symbol); - if (symbol === globalThisSymbol) { - const varsOnly = /* @__PURE__ */ new Map(); - members.forEach((p) => { - var _a; - if (!(p.flags & 418 /* BlockScoped */) && !(p.flags & 512 /* ValueModule */ && ((_a = p.declarations) == null ? void 0 : _a.length) && every(p.declarations, isAmbientModule))) { - varsOnly.set(p.escapedName, p); - } - }); - members = varsOnly; - } + if (symbol === globalThisSymbol) { + const varsOnly = /* @__PURE__ */ new Map(); + members.forEach((p) => { + var _a; + if (!(p.flags & 418 /* BlockScoped */) && !(p.flags & 512 /* ValueModule */ && ((_a = p.declarations) == null ? void 0 : _a.length) && every(p.declarations, isAmbientModule))) { + varsOnly.set(p.escapedName, p); + } + }); + members = varsOnly; } let baseConstructorIndexInfo; setStructuredTypeMembers(type, members, emptyArray, emptyArray, emptyArray); @@ -53559,7 +53649,7 @@ function createTypeChecker(host) { /*resolvedTypePredicate*/ void 0, sig.minArgumentCount, - sig.flags & 39 /* PropagatingFlags */ + sig.flags & 167 /* PropagatingFlags */ ) : void 0 )); } @@ -54951,7 +55041,7 @@ function createTypeChecker(host) { return getReturnTypeOfTypeTag(declaration); } function isResolvingReturnTypeOfSignature(signature) { - return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; + return signature.compositeSignatures && some(signature.compositeSignatures, isResolvingReturnTypeOfSignature) || !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; } function getRestTypeOfSignature(signature) { return tryGetRestTypeOfSignature(signature) || anyType; @@ -56299,6 +56389,9 @@ function createTypeChecker(host) { function getEndElementCount(type, flags) { return type.elementFlags.length - findLastIndex(type.elementFlags, (f) => !(f & flags)) - 1; } + function getTotalFixedElementCount(type) { + return type.fixedLength + getEndElementCount(type, 3 /* Fixed */); + } function getElementTypes(type) { const typeArguments = getTypeArguments(type); const arity = getTypeReferenceArity(type); @@ -57204,10 +57297,7 @@ function createTypeChecker(host) { } if (index >= 0) { errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); - return mapType(objectType, (t) => { - const restType = getRestTypeOfTupleType(t) || undefinedType; - return accessFlags & 1 /* IncludeUndefined */ ? getUnionType([restType, missingType]) : restType; - }); + return getTupleElementTypeOutOfStartCount(objectType, index, accessFlags & 1 /* IncludeUndefined */ ? missingType : void 0); } } } @@ -57492,7 +57582,7 @@ function createTypeChecker(host) { } if (compilerOptions.noUncheckedIndexedAccess && accessFlags & 32 /* ExpressionPosition */) accessFlags |= 1 /* IncludeUndefined */; - if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 199 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)) || isGenericReducibleType(objectType))) { + if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 199 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target)) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target))) || isGenericReducibleType(objectType))) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } @@ -58342,7 +58432,7 @@ function createTypeChecker(host) { /*resolvedTypePredicate*/ void 0, signature.minArgumentCount, - signature.flags & 39 /* PropagatingFlags */ + signature.flags & 167 /* PropagatingFlags */ ); result.target = signature; result.mapper = mapper; @@ -59729,6 +59819,7 @@ function createTypeChecker(host) { let errorInfo; let relatedInfo; let maybeKeys; + let maybeKeysSet; let sourceStack; let targetStack; let maybeCount = 0; @@ -60598,9 +60689,13 @@ function createTypeChecker(host) { } if (!maybeKeys) { maybeKeys = []; + maybeKeysSet = /* @__PURE__ */ new Set(); sourceStack = []; targetStack = []; } else { + if (maybeKeysSet.has(id)) { + return 3 /* Maybe */; + } const broadestEquivalentId = id.startsWith("*") ? getRelationKey( source2, target2, @@ -60609,10 +60704,8 @@ function createTypeChecker(host) { /*ignoreConstraints*/ true ) : void 0; - for (let i = 0; i < maybeCount; i++) { - if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) { - return 3 /* Maybe */; - } + if (broadestEquivalentId && maybeKeysSet.has(broadestEquivalentId)) { + return 3 /* Maybe */; } if (sourceDepth === 100 || targetDepth === 100) { overflow = true; @@ -60621,6 +60714,7 @@ function createTypeChecker(host) { } const maybeStart = maybeCount; maybeKeys[maybeCount] = id; + maybeKeysSet.add(id); maybeCount++; const saveExpandingFlags = expandingFlags; if (recursionFlags & 1 /* Source */) { @@ -60673,17 +60767,34 @@ function createTypeChecker(host) { if (result2) { if (result2 === -1 /* True */ || sourceDepth === 0 && targetDepth === 0) { if (result2 === -1 /* True */ || result2 === 3 /* Maybe */) { - for (let i = maybeStart; i < maybeCount; i++) { - relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags); - } + resetMaybeStack( + /*markAllAsSucceeded*/ + true + ); + } else { + resetMaybeStack( + /*markAllAsSucceeded*/ + false + ); } - maybeCount = maybeStart; } } else { relation.set(id, (reportErrors2 ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags); - maybeCount = maybeStart; + resetMaybeStack( + /*markAllAsSucceeded*/ + false + ); } return result2; + function resetMaybeStack(markAllAsSucceeded) { + for (let i = maybeStart; i < maybeCount; i++) { + maybeKeysSet.delete(maybeKeys[i]); + if (markAllAsSucceeded) { + relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags); + } + } + maybeCount = maybeStart; + } } function structuredTypeRelatedTo(source2, target2, reportErrors2, intersectionState) { const saveErrorInfo = captureErrorCalculationState(); @@ -61095,26 +61206,6 @@ function createTypeChecker(host) { )) { return result2; } - if (sourceFlags & 8388608 /* IndexedAccess */) { - const indexType = source2.indexType; - if (indexType.flags & 4194304 /* Index */) { - const unresolvedIndexConstraint = getBaseConstraintOfType(indexType.type); - const indexConstraint = unresolvedIndexConstraint && unresolvedIndexConstraint !== noConstraintType ? getIndexType(unresolvedIndexConstraint) : keyofConstraintType; - const constraint2 = getIndexedAccessType(source2.objectType, indexConstraint); - if (result2 = isRelatedTo( - constraint2, - target2, - 1 /* Source */, - /*reportErrors*/ - false, - /*headMessage*/ - void 0, - intersectionState - )) { - return result2; - } - } - } if (isMappedTypeGenericIndexedAccess(source2)) { const indexConstraint = getConstraintOfType(source2.indexType); if (indexConstraint) { @@ -62511,7 +62602,8 @@ function createTypeChecker(host) { return !!elementType && isEmptyLiteralType(elementType); } function isTupleLikeType(type) { - return isTupleType(type) || !!getPropertyOfType(type, "0"); + let lengthType; + return isTupleType(type) || !!getPropertyOfType(type, "0") || isArrayLikeType(type) && !!(lengthType = getTypeOfPropertyOfType(type, "length")) && everyType(lengthType, (t) => !!(t.flags & 256 /* NumberLiteral */)); } function isArrayOrTupleLikeType(type) { return isArrayLikeType(type) || isTupleLikeType(type); @@ -62522,17 +62614,7 @@ function createTypeChecker(host) { return propType; } if (everyType(type, isTupleType)) { - return mapType(type, (t) => { - const tupleType = t; - const restType = getRestTypeOfTupleType(tupleType); - if (!restType) { - return undefinedType; - } - if (compilerOptions.noUncheckedIndexedAccess && index >= tupleType.target.fixedLength + getEndElementCount(tupleType.target, 3 /* Fixed */)) { - return getUnionType([restType, undefinedType]); - } - return restType; - }); + return getTupleElementTypeOutOfStartCount(type, index, compilerOptions.noUncheckedIndexedAccess ? undefinedType : void 0); } return void 0; } @@ -62600,6 +62682,19 @@ function createTypeChecker(host) { function getRestTypeOfTupleType(type) { return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength); } + function getTupleElementTypeOutOfStartCount(type, index, undefinedOrMissingType2) { + return mapType(type, (t) => { + const tupleType = t; + const restType = getRestTypeOfTupleType(tupleType); + if (!restType) { + return undefinedType; + } + if (undefinedOrMissingType2 && index >= getTotalFixedElementCount(tupleType.target)) { + return getUnionType([restType, undefinedOrMissingType2]); + } + return restType; + }); + } function getRestArrayTypeOfTupleType(type) { const restType = getRestTypeOfTupleType(type); return restType && createArrayType(restType); @@ -63134,17 +63229,18 @@ function createTypeChecker(host) { ); } function inferTypeForHomomorphicMappedType(source, target, constraint) { - if (inInferTypeForHomomorphicMappedType) { - return void 0; + const cacheKey = source.id + "," + target.id + "," + constraint.id; + if (reverseMappedCache.has(cacheKey)) { + return reverseMappedCache.get(cacheKey); } - const key = source.id + "," + target.id + "," + constraint.id; - if (reverseMappedCache.has(key)) { - return reverseMappedCache.get(key); + const recursionKey = source.id + "," + (target.target || target).id; + if (contains(homomorphicMappedTypeInferenceStack, recursionKey)) { + return void 0; } - inInferTypeForHomomorphicMappedType = true; + homomorphicMappedTypeInferenceStack.push(recursionKey); const type = createReverseMappedType(source, target, constraint); - inInferTypeForHomomorphicMappedType = false; - reverseMappedCache.set(key, type); + homomorphicMappedTypeInferenceStack.pop(); + reverseMappedCache.set(cacheKey, type); return type; } function isPartiallyInferableType(type) { @@ -64098,12 +64194,6 @@ function createTypeChecker(host) { } return links.resolvedSymbol; } - function isInTypeQuery(node) { - return !!findAncestor( - node, - (n) => n.kind === 186 /* TypeQuery */ ? true : n.kind === 80 /* Identifier */ || n.kind === 166 /* QualifiedName */ ? false : "quit" - ); - } function isInAmbientOrTypeNode(node) { return !!(node.flags & 33554432 /* Ambient */ || findAncestor(node, (n) => isInterfaceDeclaration(n) || isTypeAliasDeclaration(n) || isTypeLiteralNode(n))); } @@ -65601,12 +65691,15 @@ function createTypeChecker(host) { return narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue); } const target = getReferenceCandidate(expr.right); - const leftType = getTypeOfExpression(expr.left); - if (leftType.flags & 8576 /* StringOrNumberLiteralOrUnique */) { - if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target) && getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) { + if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target)) { + const leftType = getTypeOfExpression(expr.left); + if (isTypeUsableAsPropertyName(leftType) && getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) { return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */); } - if (isMatchingReference(reference, target)) { + } + if (isMatchingReference(reference, target)) { + const leftType = getTypeOfExpression(expr.left); + if (isTypeUsableAsPropertyName(leftType)) { return narrowTypeByInKeyword(type, leftType, assumeTrue); } } @@ -66054,8 +66147,8 @@ function createTypeChecker(host) { } const parent = getRootDeclaration(symbol.valueDeclaration).parent; const links = getNodeLinks(parent); - if (!(links.flags & 524288 /* AssignmentsMarked */)) { - links.flags |= 524288 /* AssignmentsMarked */; + if (!(links.flags & 131072 /* AssignmentsMarked */)) { + links.flags |= 131072 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(parent)) { markNodeAssignments(parent); } @@ -66063,7 +66156,7 @@ function createTypeChecker(host) { return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!findAncestor(node.parent, (node2) => (isFunctionLike(node2) || isCatchClause(node2)) && !!(getNodeLinks(node2).flags & 524288 /* AssignmentsMarked */)); + return !!findAncestor(node.parent, (node2) => (isFunctionLike(node2) || isCatchClause(node2)) && !!(getNodeLinks(node2).flags & 131072 /* AssignmentsMarked */)); } function markNodeAssignments(node) { if (node.kind === 80 /* Identifier */) { @@ -66145,9 +66238,13 @@ function createTypeChecker(host) { symbol, /*excludes*/ 111551 /* Value */ - ) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */)) { + ) && !isInTypeQuery(location)) { const target = resolveAlias(symbol); - if (getAllSymbolFlags(target) & (111551 /* Value */ | 1048576 /* ExportValue */)) { + if (getSymbolFlags( + symbol, + /*excludeTypeOnlyMeanings*/ + true + ) & (111551 /* Value */ | 1048576 /* ExportValue */)) { if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); } else { @@ -66165,11 +66262,11 @@ function createTypeChecker(host) { const parent = declaration.parent.parent; if (parent.kind === 260 /* VariableDeclaration */ && getCombinedNodeFlagsCached(declaration) & 6 /* Constant */ || parent.kind === 169 /* Parameter */) { const links = getNodeLinks(parent); - if (!(links.flags & 16777216 /* InCheckIdentifier */)) { - links.flags |= 16777216 /* InCheckIdentifier */; + if (!(links.flags & 4194304 /* InCheckIdentifier */)) { + links.flags |= 4194304 /* InCheckIdentifier */; const parentType = getTypeForBindingElementParent(parent, 0 /* Normal */); const parentTypeConstraint = parentType && mapType(parentType, getBaseConstraintOrType); - links.flags &= ~16777216 /* InCheckIdentifier */; + links.flags &= ~4194304 /* InCheckIdentifier */; if (parentTypeConstraint && parentTypeConstraint.flags & 1048576 /* Union */ && !(parent.kind === 169 /* Parameter */ && isSymbolAssigned(symbol))) { const pattern = declaration.parent; const narrowedType = getFlowTypeOfReference( @@ -66246,17 +66343,7 @@ function createTypeChecker(host) { } let declaration = localOrExportSymbol.valueDeclaration; if (declaration && localOrExportSymbol.flags & 32 /* Class */) { - if (declaration.kind === 263 /* ClassDeclaration */ && nodeIsDecorated(legacyDecorators, declaration)) { - let container = getContainingClass(node); - while (container !== void 0) { - if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 1048576 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 2097152 /* ConstructorReferenceInClass */; - break; - } - container = getContainingClass(container); - } - } else if (declaration.kind === 231 /* ClassExpression */) { + if (isClassLike(declaration) && declaration.name !== node) { let container = getThisContainer( node, /*includeArrowFunctions*/ @@ -66264,14 +66351,7 @@ function createTypeChecker(host) { /*includeClassComputedPropertyName*/ false ); - while (container.kind !== 312 /* SourceFile */) { - if (container.parent === declaration) { - if (isPropertyDeclaration(container) && isStatic(container) || isClassStaticBlockDeclaration(container)) { - getNodeLinks(declaration).flags |= 1048576 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 2097152 /* ConstructorReferenceInClass */; - } - break; - } + while (container.kind !== 312 /* SourceFile */ && container.parent !== declaration) { container = getThisContainer( container, /*includeArrowFunctions*/ @@ -66280,6 +66360,11 @@ function createTypeChecker(host) { false ); } + if (container.kind !== 312 /* SourceFile */) { + getNodeLinks(declaration).flags |= 262144 /* ContainsConstructorReference */; + getNodeLinks(container).flags |= 262144 /* ContainsConstructorReference */; + getNodeLinks(node).flags |= 536870912 /* ConstructorReference */; + } } } checkNestedBlockScopedBinding(node, symbol); @@ -66410,7 +66495,7 @@ function createTypeChecker(host) { if (isForStatement(container)) { const varDeclList = getAncestor(symbol.valueDeclaration, 261 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 65536 /* NeedsLoopOutParameter */; } } getNodeLinks(symbol.valueDeclaration).flags |= 32768 /* BlockScopedBindingInLoop */; @@ -66688,7 +66773,7 @@ function createTypeChecker(host) { if (!isCallExpression2 && languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */ && (isPropertyDeclaration(container) || isClassStaticBlockDeclaration(container))) { forEachEnclosingBlockScopeContainer(node.parent, (current) => { if (!isSourceFile(current) || isExternalOrCommonJsModule(current)) { - getNodeLinks(current).flags |= 8388608 /* ContainsSuperPropertyInStaticInitializer */; + getNodeLinks(current).flags |= 2097152 /* ContainsSuperPropertyInStaticInitializer */; } }); } @@ -67789,7 +67874,7 @@ function createTypeChecker(host) { /*resolvedTypePredicate*/ void 0, minArgCount, - (left.flags | right.flags) & 39 /* PropagatingFlags */ + (left.flags | right.flags) & 167 /* PropagatingFlags */ ); result.compositeKind = 2097152 /* Intersection */; result.compositeSignatures = concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); @@ -67873,6 +67958,10 @@ function createTypeChecker(host) { function hasDefaultValue(node) { return node.kind === 208 /* BindingElement */ && !!node.initializer || node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */; } + function isSpreadIntoCallOrNew(node) { + const parent = walkUpParenthesizedExpressions(node.parent); + return isSpreadElement(parent) && isCallOrNewExpression(parent.parent); + } function checkArrayLiteral(node, checkMode, forceTuple) { const elements = node.elements; const elementCount = elements.length; @@ -67880,14 +67969,13 @@ function createTypeChecker(host) { const elementFlags = []; pushCachedContextualType(node); const inDestructuringPattern = isAssignmentTarget(node); - const isSpreadIntoCallOrNew = isSpreadElement(node.parent) && isCallOrNewExpression(node.parent.parent); - const inConstContext = isSpreadIntoCallOrNew || isConstContext(node); + const inConstContext = isConstContext(node); const contextualType = getApparentTypeOfContextualType( node, /*contextFlags*/ void 0 ); - const inTupleContext = isSpreadIntoCallOrNew || !!contextualType && someType(contextualType, isTupleLikeType); + const inTupleContext = isSpreadIntoCallOrNew(node) || !!contextualType && someType(contextualType, isTupleLikeType); let hasOmittedExpression = false; for (let i = 0; i < elementCount; i++) { const e = elements[i]; @@ -69320,7 +69408,7 @@ function createTypeChecker(host) { } let diagnosticMessage; const declarationName = idText(right); - if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & 32 /* Static */) && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { + if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & 32 /* Static */) && (useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { diagnosticMessage = error(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } else if (valueDeclaration.kind === 263 /* ClassDeclaration */ && node.parent.kind !== 183 /* TypeReference */ && !(valueDeclaration.flags & 33554432 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -70227,7 +70315,7 @@ function createTypeChecker(host) { } } function getThisArgumentOfCall(node) { - const expression = node.kind === 213 /* CallExpression */ ? node.expression : node.kind === 215 /* TaggedTemplateExpression */ ? node.tag : void 0; + const expression = node.kind === 213 /* CallExpression */ ? node.expression : node.kind === 215 /* TaggedTemplateExpression */ ? node.tag : node.kind === 170 /* Decorator */ && !legacyDecorators ? node.expression : void 0; if (expression) { const callee = skipOuterExpressions(expression); if (isAccessExpression(callee)) { @@ -70815,7 +70903,7 @@ function createTypeChecker(host) { parameters.push(createCombinedSymbolFromTypes(symbols, mapDefined(candidates, (candidate) => tryGetTypeAtPosition(candidate, i)))); } const restParameterSymbols = mapDefined(candidates, (c) => signatureHasRestParameter(c) ? last(c.parameters) : void 0); - let flags = 0 /* None */; + let flags = 128 /* IsSignatureCandidateForOverloadFailure */; if (restParameterSymbols.length !== 0) { const type = createArrayType(getUnionType(mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); @@ -71539,6 +71627,8 @@ function createTypeChecker(host) { return returnType; } function checkDeprecatedSignature(signature, node) { + if (signature.flags & 128 /* IsSignatureCandidateForOverloadFailure */) + return; if (signature.declaration && signature.declaration.flags & 536870912 /* Deprecated */) { const suggestionNode = getDeprecatedSuggestionNode(node); const name = tryGetPropertyAccessOrIdentifierToString(getInvokedExpression(node)); @@ -72012,7 +72102,7 @@ function createTypeChecker(host) { } return restParameter.escapedName; } - function getParameterIdentifierNameAtPosition(signature, pos) { + function getParameterIdentifierInfoAtPosition(signature, pos) { var _a; if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 324 /* JSDocFunctionType */) { return void 0; @@ -72020,10 +72110,16 @@ function createTypeChecker(host) { const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { const param = signature.parameters[pos]; - return isParameterDeclarationWithIdentifierName(param) ? [param.escapedName, false] : void 0; + const paramIdent = getParameterDeclarationIdentifier(param); + return paramIdent ? { + parameter: paramIdent, + parameterName: param.escapedName, + isRestParameter: false + } : void 0; } const restParameter = signature.parameters[paramCount] || unknownSymbol; - if (!isParameterDeclarationWithIdentifierName(restParameter)) { + const restIdent = getParameterDeclarationIdentifier(restParameter); + if (!restIdent) { return void 0; } const restType = getTypeOfSymbol(restParameter); @@ -72032,18 +72128,19 @@ function createTypeChecker(host) { const index = pos - paramCount; const associatedName = associatedNames == null ? void 0 : associatedNames[index]; const isRestTupleElement = !!(associatedName == null ? void 0 : associatedName.dotDotDotToken); - return associatedName ? [ - getTupleElementLabel(associatedName), - isRestTupleElement - ] : void 0; + if (associatedName) { + Debug.assert(isIdentifier(associatedName.name)); + return { parameter: associatedName.name, parameterName: associatedName.name.escapedText, isRestParameter: isRestTupleElement }; + } + return void 0; } if (pos === paramCount) { - return [restParameter.escapedName, true]; + return { parameter: restIdent, parameterName: restParameter.escapedName, isRestParameter: true }; } return void 0; } - function isParameterDeclarationWithIdentifierName(symbol) { - return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name); + function getParameterDeclarationIdentifier(symbol) { + return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name) && symbol.valueDeclaration.name; } function isValidDeclarationForTupleLabel(d) { return d.kind === 202 /* NamedTupleMember */ || isParameter(d) && d.name && isIdentifier(d.name); @@ -74906,7 +75003,18 @@ function createTypeChecker(host) { addLazyDiagnostic(checkSignatureDeclarationDiagnostics); function checkSignatureDeclarationDiagnostics() { checkCollisionWithArgumentsInGeneratedCode(node); - const returnTypeNode = getEffectiveReturnTypeNode(node); + let returnTypeNode = getEffectiveReturnTypeNode(node); + let returnTypeErrorLocation = returnTypeNode; + if (isInJSFile(node)) { + const typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && isTypeReferenceNode(typeTag.typeExpression.type)) { + const signature = getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + if (signature && signature.declaration) { + returnTypeNode = getEffectiveReturnTypeNode(signature.declaration); + returnTypeErrorLocation = typeTag.typeExpression.type; + } + } + } if (noImplicitAny && !returnTypeNode) { switch (node.kind) { case 180 /* ConstructSignature */: @@ -74917,21 +75025,21 @@ function createTypeChecker(host) { break; } } - if (returnTypeNode) { + if (returnTypeNode && returnTypeErrorLocation) { const functionFlags2 = getFunctionFlags(node); if ((functionFlags2 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { const returnType = getTypeFromTypeNode(returnTypeNode); if (returnType === voidType) { - error(returnTypeNode, Diagnostics.A_generator_cannot_have_a_void_type_annotation); + error(returnTypeErrorLocation, Diagnostics.A_generator_cannot_have_a_void_type_annotation); } else { const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags2 & 2 /* Async */) !== 0) || anyType; const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags2 & 2 /* Async */) !== 0) || generatorYieldType; const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags2 & 2 /* Async */) !== 0) || unknownType; const generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags2 & 2 /* Async */)); - checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode); + checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeErrorLocation); } } else if ((functionFlags2 & 3 /* AsyncGenerator */) === 2 /* Async */) { - checkAsyncFunctionReturnType(node, returnTypeNode); + checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation); } } if (node.kind !== 181 /* IndexSignature */ && node.kind !== 324 /* JSDocFunctionType */) { @@ -75012,7 +75120,7 @@ function createTypeChecker(host) { case "length": case "caller": case "arguments": - if (compilerOptions.useDefineForClassFields) { + if (useDefineForClassFields) { break; } case "prototype": @@ -75114,7 +75222,7 @@ function createTypeChecker(host) { function setNodeLinksForPrivateIdentifierScope(node) { if (isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { for (let lexicalScope = getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = getEnclosingBlockScopeContainer(lexicalScope)) { - getNodeLinks(lexicalScope).flags |= 4194304 /* ContainsClassWithPrivateIdentifiers */; + getNodeLinks(lexicalScope).flags |= 1048576 /* ContainsClassWithPrivateIdentifiers */; } if (isClassExpression(node.parent)) { const enclosingIterationStatement = getEnclosingIterationStatement(node.parent); @@ -75160,7 +75268,7 @@ function createTypeChecker(host) { if (classExtendsNull) { error(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - const superCallShouldBeRootLevel = (getEmitScriptTarget(compilerOptions) !== 99 /* ESNext */ || !useDefineForClassFields) && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p) => hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */))); + const superCallShouldBeRootLevel = !emitStandardClassFields && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p) => hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */))); if (superCallShouldBeRootLevel) { if (!superCallIsRootLevelInConstructor(superCall, node.body)) { error(superCall, Diagnostics.A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers); @@ -76013,7 +76121,7 @@ function createTypeChecker(host) { } return typeAsAwaitable.awaitedTypeOfType = type; } - function checkAsyncFunctionReturnType(node, returnTypeNode) { + function checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation) { const returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { if (isErrorType(returnType)) { @@ -76024,7 +76132,7 @@ function createTypeChecker(host) { true ); if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { - error(returnTypeNode, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedTypeNoAlias(returnType) || voidType)); + reportErrorForInvalidReturnType(Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, returnTypeNode, returnTypeErrorLocation, typeToString(getAwaitedTypeNoAlias(returnType) || voidType)); return; } } else { @@ -76034,7 +76142,7 @@ function createTypeChecker(host) { } const promiseConstructorName = getEntityNameFromTypeNode(returnTypeNode); if (promiseConstructorName === void 0) { - error(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, typeToString(returnType)); return; } const promiseConstructorSymbol = resolveEntityName( @@ -76049,9 +76157,9 @@ function createTypeChecker(host) { /*reportErrors*/ false )) { - error(returnTypeNode, Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + error(returnTypeErrorLocation, Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { - error(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, entityNameToString(promiseConstructorName)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); } return; } @@ -76060,15 +76168,16 @@ function createTypeChecker(host) { true ); if (globalPromiseConstructorLikeType === emptyObjectType) { - error(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, entityNameToString(promiseConstructorName)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); return; } - if (!checkTypeAssignableTo( - promiseConstructorType, - globalPromiseConstructorLikeType, - returnTypeNode, - Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value - )) { + const headMessage = Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value; + const errorInfo = () => returnTypeNode === returnTypeErrorLocation ? void 0 : chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type + ); + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeErrorLocation, headMessage, errorInfo)) { return; } const rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); @@ -76090,6 +76199,14 @@ function createTypeChecker(host) { node, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member ); + function reportErrorForInvalidReturnType(message, returnTypeNode2, returnTypeErrorLocation2, typeName) { + if (returnTypeNode2 === returnTypeErrorLocation2) { + error(returnTypeErrorLocation2, message, typeName); + } else { + const diag2 = error(returnTypeErrorLocation2, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + addRelatedInfo(diag2, createDiagnosticForNode(returnTypeNode2, message, typeName)); + } + } } function checkDecorator(node) { const signature = getResolvedSignature(node); @@ -76316,6 +76433,7 @@ function createTypeChecker(host) { for (const parameter of containingSignature.parameters) { markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(containingSignature)); break; } } @@ -76857,7 +76975,7 @@ function createTypeChecker(host) { } function checkWeakMapSetCollision(node) { const enclosingBlockScope = getEnclosingBlockScopeContainer(node); - if (getNodeCheckFlags(enclosingBlockScope) & 4194304 /* ContainsClassWithPrivateIdentifiers */) { + if (getNodeCheckFlags(enclosingBlockScope) & 1048576 /* ContainsClassWithPrivateIdentifiers */) { Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier"); errorSkippedOn("noEmit", node, Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText); } @@ -76871,18 +76989,18 @@ function createTypeChecker(host) { let hasCollision = false; if (isClassExpression(node)) { for (const member of node.members) { - if (getNodeCheckFlags(member) & 8388608 /* ContainsSuperPropertyInStaticInitializer */) { + if (getNodeCheckFlags(member) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { hasCollision = true; break; } } } else if (isFunctionExpression(node)) { - if (getNodeCheckFlags(node) & 8388608 /* ContainsSuperPropertyInStaticInitializer */) { + if (getNodeCheckFlags(node) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { hasCollision = true; } } else { const container = getEnclosingBlockScopeContainer(node); - if (container && getNodeCheckFlags(container) & 8388608 /* ContainsSuperPropertyInStaticInitializer */) { + if (container && getNodeCheckFlags(container) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { hasCollision = true; } } @@ -76917,9 +77035,6 @@ function createTypeChecker(host) { if ((getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */) !== 0 || isParameterDeclaration(node)) { return; } - if (node.kind === 260 /* VariableDeclaration */ && !node.initializer) { - return; - } const symbol = getSymbolOfDeclaration(node); if (symbol.flags & 1 /* FunctionScopedVariable */) { if (!isIdentifier(node.name)) @@ -78429,7 +78544,7 @@ function createTypeChecker(host) { node ); const willTransformPrivateElementsOrClassStaticBlocks = languageVersion <= 9 /* ES2022 */; - const willTransformInitializers = !useDefineForClassFields || languageVersion < 9 /* ES2022 */; + const willTransformInitializers = !emitStandardClassFields; if (willTransformStaticElementsOfDecoratedClass || willTransformPrivateElementsOrClassStaticBlocks) { for (const member of node.members) { if (willTransformStaticElementsOfDecoratedClass && classElementOrClassElementParameterIsDecorated( @@ -79187,10 +79302,22 @@ function createTypeChecker(host) { return +expr.text; case 217 /* ParenthesizedExpression */: return evaluate(expr.expression, location); - case 80 /* Identifier */: - if (isInfinityOrNaNString(expr.escapedText)) { - return +expr.escapedText; + case 80 /* Identifier */: { + const identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText) && resolveEntityName( + identifier, + 111551 /* Value */, + /*ignoreErrors*/ + true + ) === getGlobalSymbol( + identifier.escapedText, + 111551 /* Value */, + /*diagnostic*/ + void 0 + )) { + return +identifier.escapedText; } + } case 211 /* PropertyAccessExpression */: if (isEntityNameExpression(expr)) { const symbol = resolveEntityName( @@ -79529,7 +79656,7 @@ function createTypeChecker(host) { } return; } - const targetFlags = getAllSymbolFlags(target); + const targetFlags = getSymbolFlags(target); const excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) | (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (targetFlags & excludedMeanings) { const message = node.kind === 281 /* ExportSpecifier */ ? Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; @@ -79687,7 +79814,7 @@ function createTypeChecker(host) { if (node.moduleReference.kind !== 283 /* ExternalModuleReference */) { const target = resolveAlias(getSymbolOfDeclaration(node)); if (target !== unknownSymbol) { - const targetFlags = getAllSymbolFlags(target); + const targetFlags = getSymbolFlags(target); if (targetFlags & 111551 /* Value */) { const moduleName = getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { @@ -79827,7 +79954,7 @@ function createTypeChecker(host) { markExportAsReferenced(node); } const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol); - if (!target || getAllSymbolFlags(target) & 111551 /* Value */) { + if (!target || getSymbolFlags(target) & 111551 /* Value */) { checkExpressionCached(node.propertyName || node.name); } } @@ -79872,7 +79999,7 @@ function createTypeChecker(host) { )); if (sym) { markAliasReferenced(sym, id); - if (getAllSymbolFlags(sym) & 111551 /* Value */) { + if (getSymbolFlags(sym) & 111551 /* Value */) { checkExpressionCached(id); if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && getTypeOnlyAliasDeclaration(sym, 111551 /* Value */)) { error( @@ -80493,7 +80620,7 @@ function createTypeChecker(host) { function copyLocallyVisibleExportSymbols(source, meaning2) { if (meaning2) { source.forEach((symbol) => { - if (!getDeclarationOfKind(symbol, 281 /* ExportSpecifier */) && !getDeclarationOfKind(symbol, 280 /* NamespaceExport */)) { + if (!getDeclarationOfKind(symbol, 281 /* ExportSpecifier */) && !getDeclarationOfKind(symbol, 280 /* NamespaceExport */) && symbol.escapedName !== "default" /* Default */) { copySymbol(symbol, meaning2); } }); @@ -81119,7 +81246,7 @@ function createTypeChecker(host) { return symbolLinks2.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(getAllSymbolFlags(s) & 111551 /* Value */); + return s && !!(getSymbolFlags(s) & 111551 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -81249,7 +81376,11 @@ function createTypeChecker(host) { case 276 /* ImportSpecifier */: case 281 /* ExportSpecifier */: const symbol = getSymbolOfDeclaration(node); - return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */); + return !!symbol && isAliasResolvedToValue( + symbol, + /*excludeTypeOnlyValues*/ + true + ); case 278 /* ExportDeclaration */: const exportClause = node.exportClause; return !!exportClause && (isNamespaceExport(exportClause) || some(exportClause.elements, isValueAliasDeclaration)); @@ -81266,7 +81397,7 @@ function createTypeChecker(host) { const isValue = isAliasResolvedToValue(getSymbolOfDeclaration(node)); return isValue && node.moduleReference && !nodeIsMissing(node.moduleReference); } - function isAliasResolvedToValue(symbol) { + function isAliasResolvedToValue(symbol, excludeTypeOnlyValues) { if (!symbol) { return false; } @@ -81274,7 +81405,12 @@ function createTypeChecker(host) { if (target === unknownSymbol) { return true; } - return !!((getAllSymbolFlags(target) ?? -1) & 111551 /* Value */) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); + return !!(getSymbolFlags( + symbol, + excludeTypeOnlyValues, + /*excludeLocalMeanings*/ + true + ) & 111551 /* Value */) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -81288,7 +81424,7 @@ function createTypeChecker(host) { return true; } const target = getSymbolLinks(symbol).aliasTarget; - if (target && getEffectiveModifierFlags(node) & 1 /* Export */ && getAllSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { + if (target && getEffectiveModifierFlags(node) & 1 /* Export */ && getSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { return true; } } @@ -88558,7 +88694,7 @@ function transformTypeScript(context) { const constantValue = tryGetConstEnumValue(node); if (constantValue !== void 0) { setConstantValue(node, constantValue); - const substitute = typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : factory2.createNumericLiteral(constantValue); + const substitute = typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : constantValue < 0 ? factory2.createPrefixUnaryExpression(41 /* MinusToken */, factory2.createNumericLiteral(Math.abs(constantValue))) : factory2.createNumericLiteral(constantValue); if (!compilerOptions.removeComments) { const originalNode = getOriginalNode(node, isAccessExpression); addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, ` ${safeMultiLineComment(getTextOfNode(originalNode))} `); @@ -88983,6 +89119,11 @@ function transformClassFields(context) { } } } + function getClassThis() { + const lex = getClassLexicalEnvironment(); + const classThis = lex.classThis ?? lex.classConstructor ?? (currentClassContainer == null ? void 0 : currentClassContainer.name); + return Debug.checkDefined(classThis); + } function transformAutoAccessor(node) { const commentRange = getCommentRange(node); const sourceMapRange = getSourceMapRange(node); @@ -89009,11 +89150,13 @@ function transformClassFields(context) { setOriginalNode(backingField, node); setEmitFlags(backingField, 3072 /* NoComments */); setSourceMapRange(backingField, sourceMapRange); - const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName); + const receiver = isStatic(node) ? getClassThis() : factory2.createThis(); + const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName, receiver); setOriginalNode(getter, node); setCommentRange(getter, commentRange); setSourceMapRange(getter, sourceMapRange); - const setter = createAccessorPropertySetRedirector(factory2, node, modifiers, setterName); + const setterModifiers = factory2.createModifiersFromModifierFlags(modifiersToFlags(modifiers)); + const setter = createAccessorPropertySetRedirector(factory2, node, setterModifiers, setterName, receiver); setOriginalNode(setter, node); setEmitFlags(setter, 3072 /* NoComments */); setSourceMapRange(setter, sourceMapRange); @@ -89570,6 +89713,7 @@ function transformClassFields(context) { return filter(node.members, isNonStaticMethodOrAccessorWithPrivateName); } function getClassFacts(node) { + var _a; let facts = 0 /* None */; const original = getOriginalNode(node); if (isClassDeclaration(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) { @@ -89586,6 +89730,8 @@ function transformClassFields(context) { if (isStatic(member)) { if (member.name && (isPrivateIdentifier(member.name) || isAutoAccessorPropertyDeclaration(member)) && shouldTransformPrivateElementsOrClassStaticBlocks) { facts |= 2 /* NeedsClassConstructorReference */; + } else if (isAutoAccessorPropertyDeclaration(member) && shouldTransformAutoAccessors === -1 /* True */ && !node.name && !((_a = node.emitNode) == null ? void 0 : _a.classThis)) { + facts |= 2 /* NeedsClassConstructorReference */; } if (isPropertyDeclaration(member) || isClassStaticBlockDeclaration(member)) { if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* ContainsLexicalThis */) { @@ -89606,6 +89752,9 @@ function transformClassFields(context) { containsInstancePrivateElements || (containsInstancePrivateElements = isPrivateIdentifierClassElementDeclaration(member)); } else if (isPrivateIdentifierClassElementDeclaration(member)) { containsInstancePrivateElements = true; + if (resolver.getNodeCheckFlags(member) & 262144 /* ContainsConstructorReference */) { + facts |= 2 /* NeedsClassConstructorReference */; + } } else if (isPropertyDeclaration(member)) { containsPublicInstanceFields = true; containsInitializedPublicInstanceFields || (containsInitializedPublicInstanceFields = !!member.initializer); @@ -89706,10 +89855,11 @@ function transformClassFields(context) { getClassLexicalEnvironment().classConstructor = factory2.cloneNode(temp); pendingClassReferenceAssignment = factory2.createAssignment(temp, factory2.getInternalName(node)); } - if ((_b = node.emitNode) == null ? void 0 : _b.classThis) { - getClassLexicalEnvironment().classThis = node.emitNode.classThis; - } } + if ((_b = node.emitNode) == null ? void 0 : _b.classThis) { + getClassLexicalEnvironment().classThis = node.emitNode.classThis; + } + const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */; const isExport = hasSyntacticModifier(node, 1 /* Export */); const isDefault = hasSyntacticModifier(node, 1024 /* Default */); let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); @@ -89744,6 +89894,11 @@ function transformClassFields(context) { ) )); } + const alias = getClassLexicalEnvironment().classConstructor; + if (isClassWithConstructorReference && alias) { + enableSubstitutionForClassAliases(); + classAliases[getOriginalNodeId(node)] = alias; + } const classDecl = factory2.updateClassDeclaration( node, modifiers, @@ -89766,14 +89921,14 @@ function transformClassFields(context) { var _a, _b, _c; const isDecoratedClassDeclaration = !!(facts & 1 /* ClassWasDecorated */); const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); - const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 1048576 /* ClassWithConstructorReference */; + const classCheckFlags = resolver.getNodeCheckFlags(node); + const isClassWithConstructorReference = classCheckFlags & 262144 /* ContainsConstructorReference */; let temp; function createClassTempVar() { var _a2; if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a2 = node.emitNode) == null ? void 0 : _a2.classThis)) { return getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; } - const classCheckFlags = resolver.getNodeCheckFlags(node); const requiresBlockScopedVar = classCheckFlags & 32768 /* BlockScopedBindingInLoop */; const temp2 = factory2.createTempVariable( requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, @@ -90740,7 +90895,7 @@ function transformClassFields(context) { } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 2097152 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -91594,7 +91749,7 @@ function transformLegacyDecorators(context) { } } function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 1048576 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */) { enableSubstitutionForClassAliases(); const classAlias = factory2.createUniqueName(node.name && !isGeneratedIdentifier(node.name) ? idText(node.name) : "default"); classAliases[getOriginalNodeId(node)] = classAlias; @@ -91627,7 +91782,7 @@ function transformLegacyDecorators(context) { } function trySubstituteClassAlias(node) { if (classAliases) { - if (resolver.getNodeCheckFlags(node) & 2097152 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -91653,6 +91808,7 @@ function transformESDecorators(context) { endLexicalEnvironment, hoistVariableDeclaration } = context; + const languageVersion = getEmitScriptTarget(context.getCompilerOptions()); let top; let classInfo; let classThis; @@ -93154,6 +93310,17 @@ function transformESDecorators(context) { function transformDecorator(decorator) { const expression = visitNode(decorator.expression, visitor, isExpression); setEmitFlags(expression, 3072 /* NoComments */); + const innerExpression = skipOuterExpressions(expression); + if (isAccessExpression(innerExpression)) { + const { target, thisArg } = factory2.createCallBinding( + expression, + hoistVariableDeclaration, + languageVersion, + /*cacheIdentifiers*/ + true + ); + return factory2.restoreOuterExpressions(expression, factory2.createFunctionBindCall(target, thisArg, [])); + } return expression; } function createDescriptorMethod(original, name, modifiers, asteriskToken, kind, parameters, body) { @@ -96744,10 +96911,10 @@ function transformJsx(context) { for (const prop of attr.expression.properties) { if (isSpreadAssignment(prop)) { finishObjectLiteralIfNeeded(); - expressions.push(prop.expression); + expressions.push(Debug.checkDefined(visitNode(prop.expression, visitor, isExpression))); continue; } - properties.push(prop); + properties.push(Debug.checkDefined(visitNode(prop, visitor))); } continue; } @@ -99797,10 +99964,10 @@ function transformES2015(context) { name )); const checkFlags = resolver.getNodeCheckFlags(decl); - if (checkFlags & 262144 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { + if (checkFlags & 65536 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { const outParamName = factory2.createUniqueName("out_" + idText(name)); let flags = 0 /* None */; - if (checkFlags & 262144 /* NeedsLoopOutParameter */) { + if (checkFlags & 65536 /* NeedsLoopOutParameter */) { flags |= 1 /* Body */; } if (isForStatement(container)) { @@ -110833,7 +111000,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return !(expression.numericLiteralFlags & 448 /* WithSpecifier */) && !stringContains(text, tokenToString(25 /* DotToken */)) && !stringContains(text, String.fromCharCode(69 /* E */)) && !stringContains(text, String.fromCharCode(101 /* e */)); } else if (isAccessExpression(expression)) { const constantValue = getConstantValue(expression); - return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue; + return typeof constantValue === "number" && isFinite(constantValue) && constantValue >= 0 && Math.floor(constantValue) === constantValue; } } function emitElementAccessExpression(node) { @@ -113970,14 +114137,14 @@ function getEmitListItem(emit, parenthesizerRule) { } // src/compiler/watchUtilities.ts -function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { +function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames2) { if (!host.getDirectories || !host.readDirectory) { return void 0; } const cachedReadDirectoryResult = /* @__PURE__ */ new Map(); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); return { - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, fileExists, readFile: (path, encoding) => host.readFile(path, encoding), directoryExists: host.directoryExists && directoryExists, @@ -114099,7 +114266,7 @@ function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensi const rootResult = tryReadDirectory(rootDir, rootDirPath); let rootSymLinkResult; if (rootResult !== void 0) { - return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); + return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames2, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { @@ -114283,7 +114450,7 @@ function isIgnoredFileFromWildCardWatching({ program, extraFileExtensions, currentDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 }) { @@ -114299,7 +114466,7 @@ function isIgnoredFileFromWildCardWatching({ writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); return true; } - if (isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) { + if (isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames2, currentDirectory)) { writeLog(`Project: ${configFileName} Detected excluded file: ${fileOrDirectory}`); return true; } @@ -114356,7 +114523,7 @@ function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo) { function createExcludeHandlingAddWatch(key) { return (file, cb, flags, options, detailInfo1, detailInfo2) => { var _a; - return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call( + return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call( /*thisArgs*/ void 0, file, @@ -114368,7 +114535,7 @@ function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo) { ) : excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2); }; } - function useCaseSensitiveFileNames() { + function useCaseSensitiveFileNames2() { return typeof host.useCaseSensitiveFileNames === "boolean" ? host.useCaseSensitiveFileNames : host.useCaseSensitiveFileNames(); } function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) { @@ -116460,6 +116627,14 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config case 265 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); return "skip"; + case 176 /* Constructor */: + case 174 /* MethodDeclaration */: + case 262 /* FunctionDeclaration */: + if (!node.body) { + diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Signature_declarations_can_only_be_used_in_TypeScript_files)); + return "skip"; + } + return; case 266 /* EnumDeclaration */: const enumKeyword = Debug.checkDefined(tokenToString(94 /* EnumKeyword */)); diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); @@ -118375,6 +118550,9 @@ function parseConfigHostFromCompilerHostLike(host, directoryStructureHost = host return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); }, readFile: (f) => directoryStructureHost.readFile(f), + directoryExists: maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: maybeBind(directoryStructureHost, directoryStructureHost.realpath), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: () => host.getCurrentDirectory(), onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || returnUndefined, @@ -121379,12 +121557,12 @@ function getMatchedIncludeSpec(program, fileName) { return true; const isJsonFile = fileExtensionIs(fileName, ".json" /* Json */); const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); - const useCaseSensitiveFileNames = program.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = program.useCaseSensitiveFileNames(); return find((_b = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs, (includeSpec) => { if (isJsonFile && !endsWith(includeSpec, ".json" /* Json */)) return false; const pattern = getPatternFromSpec(includeSpec, basePath, "files"); - return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames).test(fileName); + return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames2).test(fileName); }); } function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) { @@ -121613,7 +121791,7 @@ function createWatchFactory(host, options) { return result; } function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost = host) { - const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); const compilerHost = { getSourceFile: createGetSourceFile( (fileName, encoding) => !encoding ? compilerHost.readFile(fileName) : host.readFile(fileName, encoding), @@ -121629,8 +121807,8 @@ function createCompilerHostFromProgramHost(host, getCompilerOptions, directorySt (path) => host.directoryExists(path) ), getCurrentDirectory: memoize(() => host.getCurrentDirectory()), - useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, - getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames), + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2, + getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames2), getNewLine: () => getNewLineCharacter(getCompilerOptions()), fileExists: (f) => host.fileExists(f), readFile: (f) => host.readFile(f), @@ -121845,7 +122023,7 @@ function createWatchProgram(host) { const sourceFilesCache = /* @__PURE__ */ new Map(); let missingFilePathsRequestedForRelease; let hasChangedCompilerOptions = false; - const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); const currentDirectory = host.getCurrentDirectory(); const { configFileName, optionsToExtend: optionsToExtendForConfigFile = {}, watchOptionsToExtend, extraFileExtensions, createProgram: createProgram2 } = host; let { rootFiles: rootFileNames, options: compilerOptions, watchOptions, projectReferences } = host; @@ -121853,7 +122031,7 @@ function createWatchProgram(host) { let configFileParsingDiagnostics; let canConfigFileJsonReportNoInputFiles = false; let hasChangedConfigFileParsingErrors = false; - const cachedDirectoryStructureHost = configFileName === void 0 ? void 0 : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + const cachedDirectoryStructureHost = configFileName === void 0 ? void 0 : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames2); const directoryStructureHost = cachedDirectoryStructureHost || host; const parseConfigFileHost = parseConfigHostFromCompilerHostLike(host, directoryStructureHost); let newLine = updateNewLine(); @@ -121871,8 +122049,8 @@ function createWatchProgram(host) { Debug.assert(compilerOptions); Debug.assert(rootFileNames); const { watchFile: watchFile2, watchDirectory, writeLog } = createWatchFactory(host, compilerOptions); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); - writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames}`); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); + writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames2}`); let configFileWatcher; if (configFileName) { configFileWatcher = watchFile2(configFileName, scheduleProgramReload, 2e3 /* High */, watchOptions, WatchType.ConfigFile); @@ -121981,7 +122159,6 @@ function createWatchProgram(host) { if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { - debugger; resolutionCache.onChangesAffectModuleResolution(); } } @@ -122378,7 +122555,7 @@ function createWatchProgram(host) { options: compilerOptions, program: getCurrentBuilderProgram() || rootFileNames, currentDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 })) @@ -122468,7 +122645,7 @@ function createWatchProgram(host) { options: config.parsedCommandLine.options, program: config.parsedCommandLine.fileNames, currentDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 })) diff --git a/lib/tsserver.js b/lib/tsserver.js index 9ef8d4444b4c7..c3ec359c2dec7 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -751,6 +751,7 @@ __export(server_exports, { getEmitModuleKind: () => getEmitModuleKind, getEmitModuleResolutionKind: () => getEmitModuleResolutionKind, getEmitScriptTarget: () => getEmitScriptTarget, + getEmitStandardClassFields: () => getEmitStandardClassFields, getEnclosingBlockScopeContainer: () => getEnclosingBlockScopeContainer, getEnclosingContainer: () => getEnclosingContainer, getEncodedSemanticClassifications: () => getEncodedSemanticClassifications, @@ -970,6 +971,7 @@ __export(server_exports, { getPropertyAssignmentAliasLikeExpression: () => getPropertyAssignmentAliasLikeExpression, getPropertyNameForPropertyNameNode: () => getPropertyNameForPropertyNameNode, getPropertyNameForUniqueESSymbol: () => getPropertyNameForUniqueESSymbol, + getPropertyNameFromType: () => getPropertyNameFromType, getPropertyNameOfBindingOrAssignmentElement: () => getPropertyNameOfBindingOrAssignmentElement, getPropertySymbolFromBindingElement: () => getPropertySymbolFromBindingElement, getPropertySymbolsFromContextualType: () => getPropertySymbolsFromContextualType, @@ -1425,6 +1427,7 @@ __export(server_exports, { isInString: () => isInString, isInTemplateString: () => isInTemplateString, isInTopLevelContext: () => isInTopLevelContext, + isInTypeQuery: () => isInTypeQuery, isIncrementalCompilation: () => isIncrementalCompilation, isIndexSignatureDeclaration: () => isIndexSignatureDeclaration, isIndexedAccessTypeNode: () => isIndexedAccessTypeNode, @@ -1802,6 +1805,7 @@ __export(server_exports, { isTypeQueryNode: () => isTypeQueryNode, isTypeReferenceNode: () => isTypeReferenceNode, isTypeReferenceType: () => isTypeReferenceType, + isTypeUsableAsPropertyName: () => isTypeUsableAsPropertyName, isUMDExportSymbol: () => isUMDExportSymbol, isUnaryExpression: () => isUnaryExpression, isUnaryExpressionWithWrite: () => isUnaryExpressionWithWrite, @@ -3496,7 +3500,7 @@ function identity(x) { function toLowerCase(x) { return x.toLowerCase(); } -var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g; +var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_. ]+/g; function toFileNameLowerCase(x) { return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x; } @@ -3839,8 +3843,8 @@ function unorderedRemoveFirstItemWhere(array, predicate) { } return false; } -function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames ? identity : toFileNameLowerCase; +function createGetCanonicalFileName(useCaseSensitiveFileNames2) { + return useCaseSensitiveFileNames2 ? identity : toFileNameLowerCase; } function patternText({ prefix, suffix }) { return `${prefix}*${suffix}`; @@ -4231,7 +4235,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, return func.name; } else { const text = Function.prototype.toString.call(func); - const match = /^function\s+([\w\$]+)\s*\(/.exec(text); + const match = /^function\s+([\w$]+)\s*\(/.exec(text); return match ? match[1] : ""; } } @@ -5014,7 +5018,7 @@ ${lanes.join("\n")} })(Debug || (Debug = {})); // src/compiler/semver.ts -var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; +var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; var prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; @@ -6621,15 +6625,13 @@ var NodeCheckFlags = /* @__PURE__ */ ((NodeCheckFlags2) => { NodeCheckFlags2[NodeCheckFlags2["ContainsCapturedBlockScopeBinding"] = 8192] = "ContainsCapturedBlockScopeBinding"; NodeCheckFlags2[NodeCheckFlags2["CapturedBlockScopedBinding"] = 16384] = "CapturedBlockScopedBinding"; NodeCheckFlags2[NodeCheckFlags2["BlockScopedBindingInLoop"] = 32768] = "BlockScopedBindingInLoop"; - NodeCheckFlags2[NodeCheckFlags2["ClassWithBodyScopedClassBinding"] = 65536] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags2[NodeCheckFlags2["BodyScopedClassBinding"] = 131072] = "BodyScopedClassBinding"; - NodeCheckFlags2[NodeCheckFlags2["NeedsLoopOutParameter"] = 262144] = "NeedsLoopOutParameter"; - NodeCheckFlags2[NodeCheckFlags2["AssignmentsMarked"] = 524288] = "AssignmentsMarked"; - NodeCheckFlags2[NodeCheckFlags2["ClassWithConstructorReference"] = 1048576] = "ClassWithConstructorReference"; - NodeCheckFlags2[NodeCheckFlags2["ConstructorReferenceInClass"] = 2097152] = "ConstructorReferenceInClass"; - NodeCheckFlags2[NodeCheckFlags2["ContainsClassWithPrivateIdentifiers"] = 4194304] = "ContainsClassWithPrivateIdentifiers"; - NodeCheckFlags2[NodeCheckFlags2["ContainsSuperPropertyInStaticInitializer"] = 8388608] = "ContainsSuperPropertyInStaticInitializer"; - NodeCheckFlags2[NodeCheckFlags2["InCheckIdentifier"] = 16777216] = "InCheckIdentifier"; + NodeCheckFlags2[NodeCheckFlags2["NeedsLoopOutParameter"] = 65536] = "NeedsLoopOutParameter"; + NodeCheckFlags2[NodeCheckFlags2["AssignmentsMarked"] = 131072] = "AssignmentsMarked"; + NodeCheckFlags2[NodeCheckFlags2["ContainsConstructorReference"] = 262144] = "ContainsConstructorReference"; + NodeCheckFlags2[NodeCheckFlags2["ConstructorReference"] = 536870912] = "ConstructorReference"; + NodeCheckFlags2[NodeCheckFlags2["ContainsClassWithPrivateIdentifiers"] = 1048576] = "ContainsClassWithPrivateIdentifiers"; + NodeCheckFlags2[NodeCheckFlags2["ContainsSuperPropertyInStaticInitializer"] = 2097152] = "ContainsSuperPropertyInStaticInitializer"; + NodeCheckFlags2[NodeCheckFlags2["InCheckIdentifier"] = 4194304] = "InCheckIdentifier"; return NodeCheckFlags2; })(NodeCheckFlags || {}); var TypeFlags = /* @__PURE__ */ ((TypeFlags2) => { @@ -6810,7 +6812,8 @@ var SignatureFlags = /* @__PURE__ */ ((SignatureFlags5) => { SignatureFlags5[SignatureFlags5["IsOuterCallChain"] = 16] = "IsOuterCallChain"; SignatureFlags5[SignatureFlags5["IsUntypedSignatureInJSFile"] = 32] = "IsUntypedSignatureInJSFile"; SignatureFlags5[SignatureFlags5["IsNonInferrable"] = 64] = "IsNonInferrable"; - SignatureFlags5[SignatureFlags5["PropagatingFlags"] = 39] = "PropagatingFlags"; + SignatureFlags5[SignatureFlags5["IsSignatureCandidateForOverloadFailure"] = 128] = "IsSignatureCandidateForOverloadFailure"; + SignatureFlags5[SignatureFlags5["PropagatingFlags"] = 167] = "PropagatingFlags"; SignatureFlags5[SignatureFlags5["CallChainFlags"] = 24] = "CallChainFlags"; return SignatureFlags5; })(SignatureFlags || {}); @@ -7677,10 +7680,10 @@ function createDynamicPriorityPollingWatchFile(host) { pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === 250 /* Low */ ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingInterval === 250 /* Low */ ? "pollLowPollingIntervalQueue" : "pollPollingIntervalQueue", pollingIntervalQueue(pollingInterval)); } } -function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) { +function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2) { const fileWatcherCallbacks = createMultiMap(); const dirWatchers = /* @__PURE__ */ new Map(); - const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames2); return nonPollingWatchFile; function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) { const filePath = toCanonicalName(fileName); @@ -7756,8 +7759,8 @@ function createFixedChunkSizePollingWatchFile(host) { pollScheduled = host.setTimeout(pollQueue, 2e3 /* High */, "pollQueue"); } } -function createSingleWatcherPerName(cache, useCaseSensitiveFileNames, name, callback, createWatcher) { - const toCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); +function createSingleWatcherPerName(cache, useCaseSensitiveFileNames2, name, callback, createWatcher) { + const toCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const path = toCanonicalFileName(name); const existing = cache.get(path); if (existing) { @@ -7809,7 +7812,7 @@ function setSysLog(logger) { } function createDirectoryWatcherSupportingRecursive({ watchDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, getAccessibleSortedChildDirectories, fileSystemEntryExists, @@ -7821,8 +7824,8 @@ function createDirectoryWatcherSupportingRecursive({ const callbackCache = createMultiMap(); const cacheToUpdateChildWatches = /* @__PURE__ */ new Map(); let timerToUpdateChildWatches; - const filePathComparer = getStringComparer(!useCaseSensitiveFileNames); - const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames); + const filePathComparer = getStringComparer(!useCaseSensitiveFileNames2); + const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames2); return (dirName, callback, recursive, options) => recursive ? createDirectoryWatcher(dirName, options, callback) : watchDirectory(dirName, callback, recursive, options); function createDirectoryWatcher(dirName, options, callback) { const dirPath = toCanonicalFilePath(dirName); @@ -7989,12 +7992,12 @@ function createDirectoryWatcherSupportingRecursive({ } } function isIgnoredPath(path, options) { - return some(ignoredPaths, (searchPath) => isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames, getCurrentDirectory); + return some(ignoredPaths, (searchPath) => isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames2, getCurrentDirectory); } function isInPath(path, searchPath) { if (stringContains(path, searchPath)) return true; - if (useCaseSensitiveFileNames) + if (useCaseSensitiveFileNames2) return false; return stringContains(toCanonicalFilePath(path), searchPath); } @@ -8017,14 +8020,14 @@ function createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModi } }; } -function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames, getCurrentDirectory) { - return ((options == null ? void 0 : options.excludeDirectories) || (options == null ? void 0 : options.excludeFiles)) && (matchesExclude(pathToCheck, options == null ? void 0 : options.excludeFiles, useCaseSensitiveFileNames, getCurrentDirectory()) || matchesExclude(pathToCheck, options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames, getCurrentDirectory())); +function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames2, getCurrentDirectory) { + return ((options == null ? void 0 : options.excludeDirectories) || (options == null ? void 0 : options.excludeFiles)) && (matchesExclude(pathToCheck, options == null ? void 0 : options.excludeFiles, useCaseSensitiveFileNames2, getCurrentDirectory()) || matchesExclude(pathToCheck, options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2, getCurrentDirectory())); } -function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory) { +function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory) { return (eventName, relativeFileName) => { if (eventName === "rename") { const fileName = !relativeFileName ? directoryName : normalizePath(combinePaths(directoryName, relativeFileName)); - if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames, getCurrentDirectory)) { + if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames2, getCurrentDirectory)) { callback(fileName); } } @@ -8037,7 +8040,7 @@ function createSystemWatchFunctions({ clearTimeout: clearTimeout2, fsWatchWorker, fileSystemEntryExists, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories, @@ -8109,7 +8112,7 @@ function createSystemWatchFunctions({ ); case 5 /* UseFsEventsOnParentDirectory */: if (!nonPollingWatchFile) { - nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames); + nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2); } return nonPollingWatchFile(fileName, callback, pollingInterval, getFallbackOptions(options)); default: @@ -8158,7 +8161,7 @@ function createSystemWatchFunctions({ return fsWatch( directoryName, 1 /* Directory */, - createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), + createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */, getFallbackOptions(options) @@ -8166,7 +8169,7 @@ function createSystemWatchFunctions({ } if (!hostRecursiveDirectoryWatcher) { hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fileSystemEntryExists, getAccessibleSortedChildDirectories, @@ -8212,7 +8215,7 @@ function createSystemWatchFunctions({ return fsWatch( directoryName, 1 /* Directory */, - createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), + createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */, getFallbackOptions(watchDirectoryOptions) @@ -8240,7 +8243,7 @@ function createSystemWatchFunctions({ function pollingWatchFile(fileName, callback, pollingInterval, options) { return createSingleWatcherPerName( pollingWatches, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, fileName, callback, (cb) => pollingWatchFileWorker(fileName, cb, pollingInterval, options) @@ -8249,7 +8252,7 @@ function createSystemWatchFunctions({ function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { return createSingleWatcherPerName( recursive ? fsWatchesRecursive : fsWatches, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, fileOrDirectory, callback, (cb) => fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, cb, recursive, fallbackPollingInterval, fallbackOptions) @@ -8377,7 +8380,7 @@ var sys = (() => { const Buffer2 = require("buffer").Buffer; const isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; const platform = _os.platform(); - const useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + const useCaseSensitiveFileNames2 = isFileSystemCaseSensitive(); const fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; const executingFilePath = __filename.endsWith("sys.js") ? _path.join(_path.dirname(__dirname), "__fake__.js") : __filename; const fsSupportsRecursiveFsWatch = process.platform === "win32" || process.platform === "darwin"; @@ -8388,7 +8391,7 @@ var sys = (() => { setTimeout, clearTimeout, fsWatchWorker, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fileSystemEntryExists, // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows @@ -8405,7 +8408,7 @@ var sys = (() => { const nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, write(s) { process.stdout.write(s); }, @@ -8534,12 +8537,12 @@ var sys = (() => { for (const node of profile.nodes) { if (node.callFrame.url) { const url = normalizeSlashes(node.callFrame.url); - if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) { + if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames2)) { node.callFrame.url = getRelativePathToDirectoryOrUrl( fileUrlRoot, url, fileUrlRoot, - createGetCanonicalFileName(useCaseSensitiveFileNames), + createGetCanonicalFileName(useCaseSensitiveFileNames2), /*isAbsolutePathAnUrl*/ true ); @@ -8719,7 +8722,7 @@ var sys = (() => { } } function readDirectory(path, extensions, excludes, includes, depth) { - return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); + return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames2, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path, entryKind) { const originalStackTraceLimit = Error.stackTraceLimit; @@ -9284,6 +9287,7 @@ var Diagnostics = { Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, 1 /* Error */, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, 1 /* Error */, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, 1 /* Error */, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1065, 1 /* Error */, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065", "The return type of an async function or method must be the global Promise type."), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, 1 /* Error */, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, 1 /* Error */, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, 1 /* Error */, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), @@ -10986,6 +10990,7 @@ var Diagnostics = { Parameter_modifiers_can_only_be_used_in_TypeScript_files: diag(8012, 1 /* Error */, "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012", "Parameter modifiers can only be used in TypeScript files."), Non_null_assertions_can_only_be_used_in_TypeScript_files: diag(8013, 1 /* Error */, "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013", "Non-null assertions can only be used in TypeScript files."), Type_assertion_expressions_can_only_be_used_in_TypeScript_files: diag(8016, 1 /* Error */, "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016", "Type assertion expressions can only be used in TypeScript files."), + Signature_declarations_can_only_be_used_in_TypeScript_files: diag(8017, 1 /* Error */, "Signature_declarations_can_only_be_used_in_TypeScript_files_8017", "Signature declarations can only be used in TypeScript files."), Report_errors_in_js_files: diag(8019, 3 /* Message */, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, 1 /* Error */, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, 1 /* Error */, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), @@ -12114,7 +12119,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (withMinus) start3--; error2(Diagnostics.Octal_literals_are_not_allowed_Use_the_syntax_0, start3, pos - start3, literal); - return { type: 9 /* NumericLiteral */, value: tokenValue }; + return 9 /* NumericLiteral */; } } else { mainFragment = scanNumberFragment(); @@ -12154,20 +12159,18 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } if (tokenFlags & 8192 /* ContainsLeadingZero */) { error2(Diagnostics.Decimals_with_leading_zeros_are_not_allowed, start3, end2 - start3); - return { type: 9 /* NumericLiteral */, value: "" + +result }; + tokenValue = "" + +result; + return 9 /* NumericLiteral */; } if (decimalFragment !== void 0 || tokenFlags & 16 /* Scientific */) { checkForIdentifierStartAfterNumericLiteral(start3, decimalFragment === void 0 && !!(tokenFlags & 16 /* Scientific */)); - return { - type: 9 /* NumericLiteral */, - value: "" + +result - // if value is not an integer, it can be safely coerced to a number - }; + tokenValue = "" + +result; + return 9 /* NumericLiteral */; } else { tokenValue = result; const type = checkBigIntSuffix(); checkForIdentifierStartAfterNumericLiteral(start3); - return { type, value: tokenValue }; + return type; } } function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { @@ -12776,7 +12779,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return token = 41 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber().value; + scanNumber(); return token = 9 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { @@ -12894,8 +12897,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan case 55 /* _7 */: case 56 /* _8 */: case 57 /* _9 */: - ({ type: token, value: tokenValue } = scanNumber()); - return token; + return token = scanNumber(); case 58 /* colon */: pos++; return token = 59 /* ColonToken */; @@ -13732,7 +13734,7 @@ function getNodeFlags(node) { var supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; function validateLocaleAndSetLanguage(locale, sys2, errors) { const lowerCaseLocale = locale.toLowerCase(); - const matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); + const matchResult = /^([a-z]+)([_-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -18613,9 +18615,9 @@ function escapeTemplateSubstitution(str) { function hasInvalidEscape(template) { return template && !!(isNoSubstitutionTemplateLiteral(template) ? template.templateFlags : template.head.templateFlags || some(template.templateSpans, (span) => !!span.literal.templateFlags)); } -var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; -var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; -var backtickQuoteEscapedCharsRegExp = /\r\n|[\\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g; +var doubleQuoteEscapedCharsRegExp = /[\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; +var singleQuoteEscapedCharsRegExp = /[\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; +var backtickQuoteEscapedCharsRegExp = /\r\n|[\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g; var escapedCharsMap = new Map(Object.entries({ " ": "\\t", "\v": "\\v", @@ -18660,8 +18662,8 @@ function escapeNonAsciiString(s, quoteChar) { s = escapeString(s, quoteChar); return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, (c) => encodeUtf16EscapeSequence(c.charCodeAt(0))) : s; } -var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g; -var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g; +var jsxDoubleQuoteEscapedCharsRegExp = /["\u0000-\u001f\u2028\u2029\u0085]/g; +var jsxSingleQuoteEscapedCharsRegExp = /['\u0000-\u001f\u2028\u2029\u0085]/g; var jsxEscapedCharsMap = new Map(Object.entries({ '"': """, "'": "'" @@ -19037,6 +19039,12 @@ function parameterIsThisKeyword(parameter) { function isThisIdentifier(node) { return !!node && node.kind === 80 /* Identifier */ && identifierIsThisKeyword(node); } +function isInTypeQuery(node) { + return !!findAncestor( + node, + (n) => n.kind === 186 /* TypeQuery */ ? true : n.kind === 80 /* Identifier */ || n.kind === 166 /* QualifiedName */ ? false : "quit" + ); +} function isThisInTypeQuery(node) { if (!isThisIdentifier(node)) { return false; @@ -19515,7 +19523,7 @@ function isPrototypeAccess(node) { return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype"; } function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return node.parent.kind === 166 /* QualifiedName */ && node.parent.right === node || node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.name === node; + return node.parent.kind === 166 /* QualifiedName */ && node.parent.right === node || node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.name === node || node.parent.kind === 236 /* MetaProperty */ && node.parent.name === node; } function isRightSideOfAccessExpression(node) { return isPropertyAccessExpression(node.parent) && node.parent.name === node || isElementAccessExpression(node.parent) && node.parent.argumentExpression === node; @@ -20534,6 +20542,9 @@ function getAllowJSCompilerOption(compilerOptions) { function getUseDefineForClassFields(compilerOptions) { return compilerOptions.useDefineForClassFields === void 0 ? getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ : compilerOptions.useDefineForClassFields; } +function getEmitStandardClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields !== false && getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */; +} function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return optionsHaveChanges(oldOptions, newOptions, semanticDiagnosticsOptionDeclarations); } @@ -20638,7 +20649,7 @@ function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { const withoutPrefix = tryRemovePrefix(path, dirPath, getCanonicalFileName); return withoutPrefix === void 0 ? void 0 : stripLeadingDirectorySeparator(withoutPrefix); } -var reservedCharacterPattern = /[^\w\s\/]/g; +var reservedCharacterPattern = /[^\w\s/]/g; function regExpEscape(text) { return text.replace(reservedCharacterPattern, escapeRegExpCharacter); } @@ -20757,7 +20768,7 @@ function getSubPatternFromSpec(spec, basePath, usage, { singleAsteriskRegexFragm function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } -function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { +function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames2, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); const absolutePath = combinePaths(currentDirectory, path); @@ -20766,22 +20777,22 @@ function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNa includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), - basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames2) }; } -function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { - return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); +function getRegexFromPattern(pattern, useCaseSensitiveFileNames2) { + return new RegExp(pattern, useCaseSensitiveFileNames2 ? "" : "i"); } -function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) { +function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames2, currentDirectory, depth, getFileSystemEntries, realpath) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); - const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, useCaseSensitiveFileNames)); - const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); - const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames2, currentDirectory); + const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, useCaseSensitiveFileNames2)); + const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames2); + const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames2); const results = includeFileRegexes ? includeFileRegexes.map(() => []) : [[]]; const visited = /* @__PURE__ */ new Map(); - const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames); + const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames2); for (const basePath of patterns.basePaths) { visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); } @@ -20823,7 +20834,7 @@ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNa } } } -function getBasePaths(path, includes, useCaseSensitiveFileNames) { +function getBasePaths(path, includes, useCaseSensitiveFileNames2) { const basePaths = [path]; if (includes) { const includeBasePaths = []; @@ -20831,9 +20842,9 @@ function getBasePaths(path, includes, useCaseSensitiveFileNames) { const absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); includeBasePaths.push(getIncludeBasePath(absolute)); } - includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames)); + includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames2)); for (const includeBasePath of includeBasePaths) { - if (every(basePaths, (basePath) => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames))) { + if (every(basePaths, (basePath) => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames2))) { basePaths.push(includeBasePath); } } @@ -21602,6 +21613,18 @@ function getTextOfJsxNamespacedName(node) { function intrinsicTagNameToString(node) { return isIdentifier(node) ? idText(node) : getTextOfJsxNamespacedName(node); } +function isTypeUsableAsPropertyName(type) { + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); +} +function getPropertyNameFromType(type) { + if (type.flags & 8192 /* UniqueESSymbol */) { + return type.escapedName; + } + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + return escapeLeadingUnderscores("" + type.value); + } + return Debug.fail(); +} // src/compiler/factory/baseNodeFactory.ts function createBaseNodeFactory() { @@ -28153,7 +28176,7 @@ var addDisposableResourceHelper = { text: ` var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { if (value !== null && value !== void 0) { - if (typeof value !== "object") throw new TypeError("Object expected."); + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); @@ -29914,7 +29937,7 @@ function createAccessorPropertyBackingField(factory2, node, modifiers, initializ initializer ); } -function createAccessorPropertyGetRedirector(factory2, node, modifiers, name) { +function createAccessorPropertyGetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { return factory2.createGetAccessorDeclaration( modifiers, name, @@ -29924,7 +29947,7 @@ function createAccessorPropertyGetRedirector(factory2, node, modifiers, name) { factory2.createBlock([ factory2.createReturnStatement( factory2.createPropertyAccessExpression( - factory2.createThis(), + receiver, factory2.getGeneratedPrivateNameForNode( node.name, /*prefix*/ @@ -29936,7 +29959,7 @@ function createAccessorPropertyGetRedirector(factory2, node, modifiers, name) { ]) ); } -function createAccessorPropertySetRedirector(factory2, node, modifiers, name) { +function createAccessorPropertySetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { return factory2.createSetAccessorDeclaration( modifiers, name, @@ -29951,7 +29974,7 @@ function createAccessorPropertySetRedirector(factory2, node, modifiers, name) { factory2.createExpressionStatement( factory2.createAssignment( factory2.createPropertyAccessExpression( - factory2.createThis(), + receiver, factory2.getGeneratedPrivateNameForNode( node.name, /*prefix*/ @@ -30992,7 +31015,8 @@ var Parser; nextToken(); const statements = parseList(0 /* SourceElements */, parseStatement); Debug.assert(token() === 1 /* EndOfFileToken */); - const endOfFileToken = addJSDocComment(parseTokenNode()); + const endHasJSDoc = hasPrecedingJSDocComment(); + const endOfFileToken = withJSDoc(parseTokenNode(), endHasJSDoc); const sourceFile = createSourceFile2(fileName, languageVersion2, scriptKind2, isDeclarationFile, statements, endOfFileToken, sourceFlags, setExternalModuleIndicator2); processCommentPragmas(sourceFile, sourceText); processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); @@ -31012,11 +31036,11 @@ var Parser; parseDiagnostics.push(createDetachedDiagnostic(fileName, pos, end, diagnostic)); } } - function withJSDoc(node, hasJSDoc) { - return hasJSDoc ? addJSDocComment(node) : node; - } let hasDeprecatedTag = false; - function addJSDocComment(node) { + function withJSDoc(node, hasJSDoc) { + if (!hasJSDoc) { + return node; + } Debug.assert(!node.jsDoc); const jsDoc = mapDefined(getJSDocCommentRanges(node, sourceText), (comment) => JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); if (jsDoc.length) @@ -31810,6 +31834,9 @@ var Parser; case 22 /* HeritageClauses */: return isHeritageClause2(); case 23 /* ImportOrExportSpecifiers */: + if (token() === 161 /* FromKeyword */ && lookAhead(nextTokenIsStringLiteral)) { + return false; + } return tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */; @@ -32168,6 +32195,9 @@ var Parser; case 22 /* HeritageClauses */: return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_expected); case 23 /* ImportOrExportSpecifiers */: + if (token() === 161 /* FromKeyword */) { + return parseErrorAtCurrentToken(Diagnostics._0_expected, "}"); + } return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 13 /* JsxAttributes */: return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); @@ -33525,12 +33555,14 @@ var Parser; return arrowExpression; } const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); if (expr.kind === 80 /* Identifier */ && token() === 39 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression( pos, expr, allowReturnTypeInArrowFunction, + hasJSDoc, /*asyncModifier*/ void 0 ); @@ -33576,7 +33608,7 @@ var Parser; ), pos); } } - function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, asyncModifier) { + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier) { Debug.assert(token() === 39 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); const parameter = factory2.createParameterDeclaration( /*modifiers*/ @@ -33609,7 +33641,7 @@ var Parser; equalsGreaterThanToken, body ); - return addJSDocComment(finishNode(node, pos)); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { const triState = isParenthesizedArrowFunctionExpression(); @@ -33737,9 +33769,10 @@ var Parser; if (token() === 134 /* AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const asyncModifier = parseModifiersForArrowFunction(); const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); - return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier); } } return void 0; @@ -35100,10 +35133,14 @@ var Parser; case 124 /* ProtectedKeyword */: case 125 /* PublicKeyword */: case 148 /* ReadonlyKeyword */: + const previousToken = token(); nextToken(); if (scanner2.hasPrecedingLineBreak()) { return false; } + if (previousToken === 138 /* DeclareKeyword */ && token() === 156 /* TypeKeyword */) { + return true; + } continue; case 162 /* GlobalKeyword */: nextToken(); @@ -35413,6 +35450,9 @@ var Parser; return void 0; } } + function nextTokenIsStringLiteral() { + return nextToken() === 11 /* StringLiteral */; + } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); return !scanner2.hasPrecedingLineBreak() && (isIdentifier2() || token() === 11 /* StringLiteral */); @@ -35465,14 +35505,14 @@ var Parser; function parseObjectBindingPattern() { const pos = getNodePos(); parseExpected(19 /* OpenBraceToken */); - const elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + const elements = allowInAnd(() => parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement)); parseExpected(20 /* CloseBraceToken */); return finishNode(factory2.createObjectBindingPattern(elements), pos); } function parseArrayBindingPattern() { const pos = getNodePos(); parseExpected(23 /* OpenBracketToken */); - const elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + const elements = allowInAnd(() => parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement)); parseExpected(24 /* CloseBracketToken */); return finishNode(factory2.createArrayBindingPattern(elements), pos); } @@ -35990,6 +36030,9 @@ var Parser; } function parseTypeAliasDeclaration(pos, hasJSDoc, modifiers) { parseExpected(156 /* TypeKeyword */); + if (scanner2.hasPrecedingLineBreak()) { + parseErrorAtCurrentToken(Diagnostics.Line_break_not_permitted_here); + } const name = parseIdentifier(); const typeParameters = parseTypeParameters(); parseExpected(64 /* EqualsToken */); @@ -36972,7 +37015,7 @@ var Parser; typeExpression = tryParseTypeExpression(); } const comment = parseTrailingTagComments(start3, getNodePos(), indent3, indentText); - const nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent3); + const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target, indent3); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -37258,7 +37301,7 @@ var Parser; case 60 /* AtToken */: if (canParseTag) { const child = tryParseChildTag(target, indent3); - if (child && (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + if (child && (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */) && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } return child; @@ -37891,7 +37934,7 @@ function getNamedArgRegEx(name) { return result; } var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; -var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; +var singleLinePragmaRegEx = /^\/\/\/?\s*@([^\s:]+)(.*)\s*$/im; function extractPragmas(pragmas, range, text) { const tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text); if (tripleSlash) { @@ -38491,6 +38534,7 @@ var commandOptionsWithoutBuild = [ { name: "checkJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: Diagnostics.JavaScript_Support, description: Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files, @@ -38717,7 +38761,7 @@ var commandOptionsWithoutBuild = [ strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, - defaultValueDescription: false + defaultValueDescription: Diagnostics.false_unless_strict_is_set }, { name: "alwaysStrict", @@ -40936,19 +40980,19 @@ function getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, e const wildcardFiles = arrayFrom(wildcardFileMap.values()); return literalFiles.concat(wildcardFiles, arrayFrom(wildCardJsonFileMap.values())); } -function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames, currentDirectory) { +function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames2, currentDirectory) { const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = spec; if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) return false; basePath = normalizePath(basePath); - const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames); + const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames2); if (validatedFilesSpec) { for (const fileName of validatedFilesSpec) { if (keyMapper(getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck) return false; } } - return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath); + return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath); } function invalidDotDotAfterRecursiveWildcard(s) { const wildcardIndex = startsWith(s, "**/") ? 0 : s.indexOf("/**/"); @@ -40958,17 +41002,17 @@ function invalidDotDotAfterRecursiveWildcard(s) { const lastDotIndex = endsWith(s, "/..") ? s.length : s.lastIndexOf("/../"); return lastDotIndex > wildcardIndex; } -function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory) { +function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory) { return matchesExcludeWorker( pathToCheck, filter(excludeSpecs, (spec) => !invalidDotDotAfterRecursiveWildcard(spec)), - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, currentDirectory ); } -function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath) { +function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath) { const excludePattern = getRegularExpressionForWildcard(excludeSpecs, combinePaths(normalizePath(currentDirectory), basePath), "exclude"); - const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames); + const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames2); if (!excludeRegex) return false; if (excludeRegex.test(pathToCheck)) @@ -40998,9 +41042,9 @@ function specToDiagnostic(spec, disallowTrailingRecursion) { return [Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec]; } } -function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }, path, useCaseSensitiveFileNames) { +function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }, path, useCaseSensitiveFileNames2) { const rawExcludeRegex = getRegularExpressionForWildcard(exclude, path, "exclude"); - const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames2 ? "" : "i"); const wildcardDirectories = {}; if (include !== void 0) { const recursiveKeys = []; @@ -41009,7 +41053,7 @@ function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExclu if (excludeRegex && excludeRegex.test(spec)) { continue; } - const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); + const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2); if (match) { const { key, flags } = match; const existingFlags = wildcardDirectories[key]; @@ -41024,7 +41068,7 @@ function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExclu for (const key in wildcardDirectories) { if (hasProperty(wildcardDirectories, key)) { for (const recursiveKey of recursiveKeys) { - if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames2)) { delete wildcardDirectories[key]; } } @@ -41033,20 +41077,20 @@ function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExclu } return wildcardDirectories; } -function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { +function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2) { const match = wildcardDirectoryPattern.exec(spec); if (match) { const questionWildcardIndex = spec.indexOf("?"); const starWildcardIndex = spec.indexOf("*"); const lastDirectorySeperatorIndex = spec.lastIndexOf(directorySeparator); return { - key: useCaseSensitiveFileNames ? match[0] : toFileNameLowerCase(match[0]), + key: useCaseSensitiveFileNames2 ? match[0] : toFileNameLowerCase(match[0]), flags: questionWildcardIndex !== -1 && questionWildcardIndex < lastDirectorySeperatorIndex || starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex ? 1 /* Recursive */ : 0 /* None */ }; } if (isImplicitGlob(spec.substring(spec.lastIndexOf(directorySeparator) + 1))) { return { - key: removeTrailingDirectorySeparator(useCaseSensitiveFileNames ? spec : toFileNameLowerCase(spec)), + key: removeTrailingDirectorySeparator(useCaseSensitiveFileNames2 ? spec : toFileNameLowerCase(spec)), flags: 1 /* Recursive */ }; } @@ -41192,6 +41236,18 @@ function formatExtensions(extensions) { result.push("JSON"); return result.join(", "); } +function extensionsToExtensionsArray(extensions) { + const result = []; + if (extensions & 1 /* TypeScript */) + result.push(...supportedTSImplementationExtensions); + if (extensions & 2 /* JavaScript */) + result.push(...supportedJSExtensionsFlat); + if (extensions & 4 /* Declaration */) + result.push(...supportedDeclarationExtensions); + if (extensions & 8 /* Json */) + result.push(".json" /* Json */); + return result; +} function resolvedTypeScriptOnly(resolved) { if (!resolved) { return void 0; @@ -41366,8 +41422,8 @@ function getDefaultTypeRoots(currentDirectory) { } var nodeModulesAtTypes = combinePaths("node_modules", "@types"); function arePathsEqual(path1, path2, host) { - const useCaseSensitiveFileNames = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; - return comparePaths(path1, path2, !useCaseSensitiveFileNames) === 0 /* EqualTo */; + const useCaseSensitiveFileNames2 = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; + return comparePaths(path1, path2, !useCaseSensitiveFileNames2) === 0 /* EqualTo */; } function getOriginalAndResolvedFileName(fileName, host, traceEnabled) { const resolvedFileName = realPath(fileName, host, traceEnabled); @@ -42644,7 +42700,7 @@ function getEntrypointsFromPackageJsonInfo(packageJsonInfo, options, host, cache arrayIsEqualTo ); for (const conditions of conditionSets) { - const loadPackageJsonExportsState = { ...loadPackageJsonMainState, failedLookupLocations: [], conditions }; + const loadPackageJsonExportsState = { ...loadPackageJsonMainState, failedLookupLocations: [], conditions, host }; const exportResolutions = loadEntrypointsFromExportMap( packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, @@ -42676,23 +42732,42 @@ function loadEntrypointsFromExportMap(scope, exports, state, extensions) { return entrypoints; function loadEntrypointsFromTargetExports(target) { var _a, _b; - if (typeof target === "string" && startsWith(target, "./") && target.indexOf("*") === -1) { - const partsAfterFirst = getPathComponents(target).slice(2); - if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) { - return false; - } - const resolvedTarget = combinePaths(scope.packageDirectory, target); - const finalPath = getNormalizedAbsolutePath(resolvedTarget, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); - const result = loadFileNameFromPackageJsonField( - extensions, - finalPath, - /*onlyRecordFailures*/ - false, - state - ); - if (result) { - entrypoints = appendIfUnique(entrypoints, result, (a, b) => a.path === b.path); - return true; + if (typeof target === "string" && startsWith(target, "./")) { + if (target.indexOf("*") >= 0 && state.host.readDirectory) { + if (target.indexOf("*") !== target.lastIndexOf("*")) { + return false; + } + state.host.readDirectory( + scope.packageDirectory, + extensionsToExtensionsArray(extensions), + /*excludes*/ + void 0, + [changeAnyExtension(target.replace("*", "**/*"), getDeclarationEmitExtensionForPath(target))] + ).forEach((entry) => { + entrypoints = appendIfUnique(entrypoints, { + path: entry, + ext: getAnyExtensionFromPath(entry), + resolvedUsingTsExtension: void 0 + }); + }); + } else { + const partsAfterFirst = getPathComponents(target).slice(2); + if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) { + return false; + } + const resolvedTarget = combinePaths(scope.packageDirectory, target); + const finalPath = getNormalizedAbsolutePath(resolvedTarget, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); + const result = loadFileNameFromPackageJsonField( + extensions, + finalPath, + /*onlyRecordFailures*/ + false, + state + ); + if (result) { + entrypoints = appendIfUnique(entrypoints, result, (a, b) => a.path === b.path); + return true; + } } } else if (Array.isArray(target)) { for (const t of target) { @@ -42901,6 +42976,9 @@ function loadModuleFromSelfNameReference(extensions, moduleName, directory, stat } const trailingParts = parts.slice(nameParts.length); const subpath = !length(trailingParts) ? "." : `.${directorySeparator}${trailingParts.join(directorySeparator)}`; + if (getAllowJSCompilerOption(state.compilerOptions) && !pathContainsNodeModules(directory)) { + return loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference); + } const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */); const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */); return loadModuleFromExports(scope, priorityExtensions, subpath, state, cache, redirectedReference) || loadModuleFromExports(scope, secondaryExtensions, subpath, state, cache, redirectedReference); @@ -43248,13 +43326,10 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec function combineDirectoryPath(root, dir) { return ensureTrailingDirectorySeparator(combinePaths(root, dir)); } - function useCaseSensitiveFileNames() { - return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); - } function tryLoadInputFileForPath(finalPath, entry, packagePath, isImports2) { var _a, _b, _c, _d; - if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames()) : true)) { - const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames }); + if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true)) { + const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames: () => useCaseSensitiveFileNames(state) }); const commonSourceDirGuesses = []; if (state.compilerOptions.rootDir || state.compilerOptions.composite && state.compilerOptions.configFilePath) { const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, () => [], ((_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)) || "", getCanonicalFileName)); @@ -43283,7 +43358,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec for (const commonSourceDirGuess of commonSourceDirGuesses) { const candidateDirectories = getOutputDirectoriesForBaseDirectory(commonSourceDirGuess); for (const candidateDir of candidateDirectories) { - if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames())) { + if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames(state))) { const pathFragment = finalPath.slice(candidateDir.length + 1); const possibleInputBase = combinePaths(commonSourceDirGuess, pathFragment); const jsAndDtsExtensions = [".mjs" /* Mjs */, ".cjs" /* Cjs */, ".js" /* Js */, ".json" /* Json */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */, ".d.ts" /* Dts */]; @@ -43293,7 +43368,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec for (const possibleExt of inputExts) { if (!extensionIsOk(extensions, possibleExt)) continue; - const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames()); + const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames(state)); if (state.host.fileExists(possibleInputWithInputExtension)) { return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( extensions, @@ -43710,6 +43785,9 @@ function traceIfEnabled(state, diagnostic, ...args) { trace(state.host, diagnostic, ...args); } } +function useCaseSensitiveFileNames(state) { + return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); +} // src/compiler/binder.ts var ModuleInstanceState = /* @__PURE__ */ ((ModuleInstanceState2) => { @@ -43823,6 +43901,9 @@ function getModuleInstanceStateForAliasTarget(specifier, visited) { if (found === 1 /* Instantiated */) { return found; } + if (statement.kind === 271 /* ImportEqualsDeclaration */) { + found = 1 /* Instantiated */; + } } } if (found !== void 0) { @@ -47193,7 +47274,9 @@ function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, hos for (const { ending, value } of candidates) { if (value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ ending, value })) { const matchedStar = value.substring(prefix.length, value.length - suffix.length); - return pathIsRelative(matchedStar) ? void 0 : key.replace("*", matchedStar); + if (!pathIsRelative(matchedStar)) { + return key.replace("*", matchedStar); + } } } } else if (some(candidates, (c) => c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, (c) => c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) { @@ -47265,7 +47348,7 @@ function tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, for (const key of getOwnKeys(exports)) { if (key === "default" || conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(conditions, key)) { const subTarget = exports[key]; - const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions); + const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions, mode); if (result) { return result; } @@ -47679,6 +47762,7 @@ function createTypeChecker(host) { var moduleKind = getEmitModuleKind(compilerOptions); var legacyDecorators = !!compilerOptions.experimentalDecorators; var useDefineForClassFields = getUseDefineForClassFields(compilerOptions); + var emitStandardClassFields = getEmitStandardClassFields(compilerOptions); var allowSyntheticDefaultImports = getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -47769,7 +47853,7 @@ function createTypeChecker(host) { return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, - getParameterIdentifierNameAtPosition, + getParameterIdentifierInfoAtPosition, getPromisedTypeOfPromise, getAwaitedType: (type) => getAwaitedType(type), getReturnTypeOfSignature, @@ -48422,7 +48506,7 @@ function createTypeChecker(host) { }; var amalgamatedDuplicates; var reverseMappedCache = /* @__PURE__ */ new Map(); - var inInferTypeForHomomorphicMappedType = false; + var homomorphicMappedTypeInferenceStack = []; var ambientModulesCache; var patternAmbientModules; var patternAmbientModuleAugmentations; @@ -48982,7 +49066,7 @@ function createTypeChecker(host) { return symbol; } if (symbol.flags & 2097152 /* Alias */) { - const targetFlags = getAllSymbolFlags(symbol); + const targetFlags = getSymbolFlags(symbol); if (targetFlags & meaning) { return symbol; } @@ -49033,7 +49117,7 @@ function createTypeChecker(host) { false ); } else if (isParameterPropertyDeclaration(declaration, declaration.parent)) { - return !(getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); + return !(emitStandardClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } @@ -49047,7 +49131,7 @@ function createTypeChecker(host) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { + if (emitStandardClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration( declaration, usage, @@ -49171,7 +49255,7 @@ function createTypeChecker(host) { return requiresScopeChangeWorker(node.name); case 172 /* PropertyDeclaration */: if (hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !useDefineForClassFields; + return !emitStandardClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -49210,7 +49294,7 @@ function createTypeChecker(host) { if (name === "const" && isConstAssertion(location)) { return void 0; } - if (isModuleDeclaration(location) && lastLocation && location.name === lastLocation) { + if (isModuleOrEnumDeclaration(location) && lastLocation && location.name === lastLocation) { lastLocation = location; location = location.parent; } @@ -49442,7 +49526,7 @@ function createTypeChecker(host) { } } function checkAndReportErrorForInvalidInitializer() { - if (propertyWithInvalidInitializer && !(useDefineForClassFields && getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */)) { + if (propertyWithInvalidInitializer && !emitStandardClassFields) { error2( errorLocation, errorLocation && propertyWithInvalidInitializer.type && textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) ? Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor : Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, @@ -49742,7 +49826,7 @@ function createTypeChecker(host) { /*isUse*/ false )); - const allFlags = symbol && getAllSymbolFlags(symbol); + const allFlags = symbol && getSymbolFlags(symbol); if (symbol && allFlags !== void 0 && !(allFlags & 111551 /* Value */)) { const rawName = unescapeLeadingUnderscores(name); if (isES2015OrLaterConstructorName(name)) { @@ -50478,11 +50562,23 @@ function createTypeChecker(host) { } return void 0; } - function getAllSymbolFlags(symbol) { - let flags = symbol.flags; + function getSymbolFlags(symbol, excludeTypeOnlyMeanings, excludeLocalMeanings) { + const typeOnlyDeclaration = excludeTypeOnlyMeanings && getTypeOnlyAliasDeclaration(symbol); + const typeOnlyDeclarationIsExportStar = typeOnlyDeclaration && isExportDeclaration(typeOnlyDeclaration); + const typeOnlyResolution = typeOnlyDeclaration && (typeOnlyDeclarationIsExportStar ? resolveExternalModuleName( + typeOnlyDeclaration.moduleSpecifier, + typeOnlyDeclaration.moduleSpecifier, + /*ignoreErrors*/ + true + ) : resolveAlias(typeOnlyDeclaration.symbol)); + const typeOnlyExportStarTargets = typeOnlyDeclarationIsExportStar && typeOnlyResolution ? getExportsOfModule(typeOnlyResolution) : void 0; + let flags = excludeLocalMeanings ? 0 /* None */ : symbol.flags; let seenSymbols; while (symbol.flags & 2097152 /* Alias */) { - const target = resolveAlias(symbol); + const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); + if (!typeOnlyDeclarationIsExportStar && target === typeOnlyResolution || (typeOnlyExportStarTargets == null ? void 0 : typeOnlyExportStarTargets.get(target.escapedName)) === target) { + break; + } if (target === unknownSymbol) { return 67108863 /* All */; } @@ -50540,7 +50636,7 @@ function createTypeChecker(host) { } if (links.typeOnlyDeclaration) { const resolved = links.typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? resolveSymbol(getExportsOfModule(links.typeOnlyDeclaration.symbol.parent).get(links.typeOnlyExportStarName || symbol.escapedName)) : resolveAlias(links.typeOnlyDeclaration.symbol); - return getAllSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0; + return getSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0; } return void 0; } @@ -50551,7 +50647,11 @@ function createTypeChecker(host) { const symbol = getSymbolOfDeclaration(node); const target = resolveAlias(symbol); if (target) { - const markAlias = target === unknownSymbol || getAllSymbolFlags(target) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */); + const markAlias = target === unknownSymbol || getSymbolFlags( + symbol, + /*excludeTypeOnlyMeanings*/ + true + ) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -50566,7 +50666,7 @@ function createTypeChecker(host) { if (!node) return Debug.fail(); if (isInternalModuleImportEqualsDeclaration(node)) { - if (getAllSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { + if (getSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { checkExpressionCached(node.moduleReference); } } @@ -50826,7 +50926,7 @@ function createTypeChecker(host) { return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation) : void 0; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) { - var _a, _b, _c, _d, _e, _f, _g, _h, _i; + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; if (startsWith(moduleReference, "@types/")) { const diag2 = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; const withoutAtTypePrefix = removePrefix(moduleReference, "@types/"); @@ -50861,8 +50961,11 @@ function createTypeChecker(host) { ); } } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) { - const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); - error2(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension); + const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); + if (!((importOrExport == null ? void 0 : importOrExport.isTypeOnly) || findAncestor(location, isImportTypeNode))) { + const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); + error2(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension); + } } if (sourceFile.symbol) { if (resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) { @@ -50879,7 +50982,7 @@ function createTypeChecker(host) { if (moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */) { const isSyncImport = currentSourceFile.impliedNodeFormat === 1 /* CommonJS */ && !findAncestor(location, isImportCall) || !!findAncestor(location, isImportEqualsDeclaration); const overrideClauseHost = findAncestor(location, (l) => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l)); - const overrideClause = overrideClauseHost && isImportTypeNode(overrideClauseHost) ? (_h = overrideClauseHost.assertions) == null ? void 0 : _h.assertClause : overrideClauseHost == null ? void 0 : overrideClauseHost.assertClause; + const overrideClause = overrideClauseHost && isImportTypeNode(overrideClauseHost) ? (_i = overrideClauseHost.assertions) == null ? void 0 : _i.assertClause : overrideClauseHost == null ? void 0 : overrideClauseHost.assertClause; if (isSyncImport && sourceFile.impliedNodeFormat === 99 /* ESNext */ && !getResolutionModeOverrideForClause(overrideClause)) { if (findAncestor(location, isImportEqualsDeclaration)) { error2(errorNode, Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); @@ -50982,7 +51085,7 @@ function createTypeChecker(host) { error2(errorNode, Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else if (mode === 99 /* ESNext */ && resolutionIsNode16OrNext && isExtensionlessRelativePathImport) { const absoluteRef = getNormalizedAbsolutePath(moduleReference, getDirectoryPath(currentSourceFile.path)); - const suggestedExt = (_i = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _i[1]; + const suggestedExt = (_j = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _j[1]; if (suggestedExt) { error2( errorNode, @@ -51414,7 +51517,7 @@ function createTypeChecker(host) { return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 && symbol.exportSymbol || symbol); } function symbolIsValue(symbol, includeTypeOnlyMembers) { - return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getAllSymbolFlags(symbol) & 111551 /* Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); + return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getSymbolFlags(symbol, !includeTypeOnlyMembers) & 111551 /* Value */); } function findConstructorDeclaration(node) { const members = node.members; @@ -51681,7 +51784,7 @@ function createTypeChecker(host) { } const shouldResolveAlias = symbolFromSymbolTable.flags & 2097152 /* Alias */ && !getDeclarationOfKind(symbolFromSymbolTable, 281 /* ExportSpecifier */); symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - const flags = shouldResolveAlias ? getAllSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; + const flags = shouldResolveAlias ? getSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; if (flags & meaning) { qualify = true; return true; @@ -52418,11 +52521,13 @@ function createTypeChecker(host) { return !!type2.target && isMappedTypeHomomorphic(type2.target) && !isMappedTypeHomomorphic(type2); } function createMappedTypeNodeFromType(type2) { + var _a2; Debug.assert(!!(type2.flags & 524288 /* Object */)); const readonlyToken = type2.declaration.readonlyToken ? factory.createToken(type2.declaration.readonlyToken.kind) : void 0; const questionToken = type2.declaration.questionToken ? factory.createToken(type2.declaration.questionToken.kind) : void 0; let appropriateConstraintTypeNode; let newTypeVariable; + const needsModifierPreservingWrapper = !isMappedTypeWithKeyofConstraintDeclaration(type2) && !(getModifiersTypeFromMappedType(type2).flags & 2 /* Unknown */) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && !(getConstraintTypeFromMappedType(type2).flags & 262144 /* TypeParameter */ && ((_a2 = getConstraintOfTypeParameter(getConstraintTypeFromMappedType(type2))) == null ? void 0 : _a2.flags) & 4194304 /* Index */); if (isMappedTypeWithKeyofConstraintDeclaration(type2)) { if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */) { const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T")); @@ -52430,6 +52535,11 @@ function createTypeChecker(host) { newTypeVariable = factory.createTypeReferenceNode(name); } appropriateConstraintTypeNode = factory.createTypeOperatorNode(143 /* KeyOfKeyword */, newTypeVariable || typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)); + } else if (needsModifierPreservingWrapper) { + const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T")); + const name = typeParameterToName(newParam, context); + newTypeVariable = factory.createTypeReferenceNode(name); + appropriateConstraintTypeNode = newTypeVariable; } else { appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context); } @@ -52460,6 +52570,18 @@ function createTypeChecker(host) { result, factory.createKeywordTypeNode(146 /* NeverKeyword */) ); + } else if (needsModifierPreservingWrapper) { + return factory.createConditionalTypeNode( + typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context), + factory.createInferTypeNode(factory.createTypeParameterDeclaration( + /*modifiers*/ + void 0, + factory.cloneNode(newTypeVariable.typeName), + factory.createTypeOperatorNode(143 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)) + )), + result, + factory.createKeywordTypeNode(146 /* NeverKeyword */) + ); } return result; } @@ -53013,6 +53135,7 @@ function createTypeChecker(host) { ); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { + var _a; const suppressAny = context.flags & 256 /* SuppressAnyReturnType */; if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; @@ -53148,6 +53271,20 @@ function createTypeChecker(host) { if (typeArguments) { node.typeArguments = factory.createNodeArray(typeArguments); } + if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 330 /* JSDocSignature */ && signature.declaration.parent.kind === 346 /* JSDocOverloadTag */) { + const comment = getTextOfNode( + signature.declaration.parent.parent, + /*includeTrivia*/ + true + ).slice(2, -2).split(/\r\n|\n|\r/).map((line) => line.replace(/^\s+/, " ")).join("\n"); + addSyntheticLeadingComment( + node, + 3 /* MultiLineCommentTrivia */, + comment, + /*hasTrailingNewLine*/ + true + ); + } cleanup == null ? void 0 : cleanup(); return node; } @@ -54509,7 +54646,7 @@ function createTypeChecker(host) { return !exports ? [] : filter(arrayFrom(exports.values()), (m) => isNamespaceMember(m) && isIdentifierText(m.escapedName, 99 /* ESNext */)); } function isTypeOnlyNamespace(symbol) { - return every(getNamespaceMembersForSerialization(symbol), (m) => !(getAllSymbolFlags(resolveSymbol(m)) & 111551 /* Value */)); + return every(getNamespaceMembersForSerialization(symbol), (m) => !(getSymbolFlags(resolveSymbol(m)) & 111551 /* Value */)); } function serializeModule(symbol, symbolName2, modifierFlags) { const members = getNamespaceMembersForSerialization(symbol); @@ -56217,7 +56354,7 @@ function createTypeChecker(host) { false, definedInMethod && !definedInConstructor )); - if (symbol.valueDeclaration && filterType(widened, (t) => !!(t.flags & ~98304 /* Nullable */)) === neverType) { + if (symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && filterType(widened, (t) => !!(t.flags & ~98304 /* Nullable */)) === neverType) { reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } @@ -56781,7 +56918,7 @@ function createTypeChecker(host) { true ); const declaredType = firstDefined(exportSymbol == null ? void 0 : exportSymbol.declarations, (d) => isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : void 0); - links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getAllSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; + links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } return links.type; } @@ -57496,9 +57633,6 @@ function createTypeChecker(host) { } return type; } - function isTypeUsableAsPropertyName(type) { - return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); - } function isLateBindableName(node) { if (!isComputedPropertyName(node) && !isElementAccessExpression(node)) { return false; @@ -57519,15 +57653,6 @@ function createTypeChecker(host) { function isNonBindableDynamicName(node) { return isDynamicName(node) && !isLateBindableName(node); } - function getPropertyNameFromType(type) { - if (type.flags & 8192 /* UniqueESSymbol */) { - return type.escapedName; - } - if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { - return escapeLeadingUnderscores("" + type.value); - } - return Debug.fail(); - } function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { Debug.assert(!!(getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol."); symbol.flags |= symbolFlags; @@ -57577,6 +57702,7 @@ function createTypeChecker(host) { return links.resolvedSymbol; } function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var _a, _b, _c; const links = getSymbolLinks(symbol); if (!links[resolutionKind]) { const isStatic2 = resolutionKind === "resolvedExports" /* resolvedExports */; @@ -57595,7 +57721,7 @@ function createTypeChecker(host) { } } } - const assignments = symbol.assignmentDeclarationMembers; + const assignments = (((_a = symbol.valueDeclaration) == null ? void 0 : _a.kind) === 219 /* ArrowFunction */ || ((_b = symbol.valueDeclaration) == null ? void 0 : _b.kind) === 218 /* FunctionExpression */) && ((_c = getSymbolOfNode(symbol.valueDeclaration.parent)) == null ? void 0 : _c.assignmentDeclarationMembers) || symbol.assignmentDeclarationMembers; if (assignments) { const decls = arrayFrom(assignments.values()); for (const member of decls) { @@ -57724,7 +57850,7 @@ function createTypeChecker(host) { /*resolvedTypePredicate*/ void 0, sig.minArgumentCount, - sig.flags & 39 /* PropagatingFlags */ + sig.flags & 167 /* PropagatingFlags */ ); result.target = sig.target; result.mapper = sig.mapper; @@ -58025,7 +58151,7 @@ function createTypeChecker(host) { /*resolvedTypePredicate*/ void 0, minArgCount, - (left.flags | right.flags) & 39 /* PropagatingFlags */ + (left.flags | right.flags) & 167 /* PropagatingFlags */ ); result.compositeKind = 1048576 /* Union */; result.compositeSignatures = concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); @@ -58173,20 +58299,17 @@ function createTypeChecker(host) { setStructuredTypeMembers(type, members2, callSignatures, constructSignatures, indexInfos2); return; } - let members = emptySymbols; + let members = getExportsOfSymbol(symbol); let indexInfos; - if (symbol.exports) { - members = getExportsOfSymbol(symbol); - if (symbol === globalThisSymbol) { - const varsOnly = /* @__PURE__ */ new Map(); - members.forEach((p) => { - var _a; - if (!(p.flags & 418 /* BlockScoped */) && !(p.flags & 512 /* ValueModule */ && ((_a = p.declarations) == null ? void 0 : _a.length) && every(p.declarations, isAmbientModule))) { - varsOnly.set(p.escapedName, p); - } - }); - members = varsOnly; - } + if (symbol === globalThisSymbol) { + const varsOnly = /* @__PURE__ */ new Map(); + members.forEach((p) => { + var _a; + if (!(p.flags & 418 /* BlockScoped */) && !(p.flags & 512 /* ValueModule */ && ((_a = p.declarations) == null ? void 0 : _a.length) && every(p.declarations, isAmbientModule))) { + varsOnly.set(p.escapedName, p); + } + }); + members = varsOnly; } let baseConstructorIndexInfo; setStructuredTypeMembers(type, members, emptyArray, emptyArray, emptyArray); @@ -58235,7 +58358,7 @@ function createTypeChecker(host) { /*resolvedTypePredicate*/ void 0, sig.minArgumentCount, - sig.flags & 39 /* PropagatingFlags */ + sig.flags & 167 /* PropagatingFlags */ ) : void 0 )); } @@ -59627,7 +59750,7 @@ function createTypeChecker(host) { return getReturnTypeOfTypeTag(declaration); } function isResolvingReturnTypeOfSignature(signature) { - return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; + return signature.compositeSignatures && some(signature.compositeSignatures, isResolvingReturnTypeOfSignature) || !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; } function getRestTypeOfSignature(signature) { return tryGetRestTypeOfSignature(signature) || anyType; @@ -60975,6 +61098,9 @@ function createTypeChecker(host) { function getEndElementCount(type, flags) { return type.elementFlags.length - findLastIndex(type.elementFlags, (f) => !(f & flags)) - 1; } + function getTotalFixedElementCount(type) { + return type.fixedLength + getEndElementCount(type, 3 /* Fixed */); + } function getElementTypes(type) { const typeArguments = getTypeArguments(type); const arity = getTypeReferenceArity(type); @@ -61880,10 +62006,7 @@ function createTypeChecker(host) { } if (index >= 0) { errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); - return mapType(objectType, (t) => { - const restType = getRestTypeOfTupleType(t) || undefinedType; - return accessFlags & 1 /* IncludeUndefined */ ? getUnionType([restType, missingType]) : restType; - }); + return getTupleElementTypeOutOfStartCount(objectType, index, accessFlags & 1 /* IncludeUndefined */ ? missingType : void 0); } } } @@ -62168,7 +62291,7 @@ function createTypeChecker(host) { } if (compilerOptions.noUncheckedIndexedAccess && accessFlags & 32 /* ExpressionPosition */) accessFlags |= 1 /* IncludeUndefined */; - if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 199 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)) || isGenericReducibleType(objectType))) { + if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 199 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target)) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target))) || isGenericReducibleType(objectType))) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } @@ -63018,7 +63141,7 @@ function createTypeChecker(host) { /*resolvedTypePredicate*/ void 0, signature.minArgumentCount, - signature.flags & 39 /* PropagatingFlags */ + signature.flags & 167 /* PropagatingFlags */ ); result.target = signature; result.mapper = mapper; @@ -64405,6 +64528,7 @@ function createTypeChecker(host) { let errorInfo; let relatedInfo; let maybeKeys; + let maybeKeysSet; let sourceStack; let targetStack; let maybeCount = 0; @@ -65274,9 +65398,13 @@ function createTypeChecker(host) { } if (!maybeKeys) { maybeKeys = []; + maybeKeysSet = /* @__PURE__ */ new Set(); sourceStack = []; targetStack = []; } else { + if (maybeKeysSet.has(id)) { + return 3 /* Maybe */; + } const broadestEquivalentId = id.startsWith("*") ? getRelationKey( source2, target2, @@ -65285,10 +65413,8 @@ function createTypeChecker(host) { /*ignoreConstraints*/ true ) : void 0; - for (let i = 0; i < maybeCount; i++) { - if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) { - return 3 /* Maybe */; - } + if (broadestEquivalentId && maybeKeysSet.has(broadestEquivalentId)) { + return 3 /* Maybe */; } if (sourceDepth === 100 || targetDepth === 100) { overflow = true; @@ -65297,6 +65423,7 @@ function createTypeChecker(host) { } const maybeStart = maybeCount; maybeKeys[maybeCount] = id; + maybeKeysSet.add(id); maybeCount++; const saveExpandingFlags = expandingFlags; if (recursionFlags & 1 /* Source */) { @@ -65349,17 +65476,34 @@ function createTypeChecker(host) { if (result2) { if (result2 === -1 /* True */ || sourceDepth === 0 && targetDepth === 0) { if (result2 === -1 /* True */ || result2 === 3 /* Maybe */) { - for (let i = maybeStart; i < maybeCount; i++) { - relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags); - } + resetMaybeStack( + /*markAllAsSucceeded*/ + true + ); + } else { + resetMaybeStack( + /*markAllAsSucceeded*/ + false + ); } - maybeCount = maybeStart; } } else { relation.set(id, (reportErrors2 ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags); - maybeCount = maybeStart; + resetMaybeStack( + /*markAllAsSucceeded*/ + false + ); } return result2; + function resetMaybeStack(markAllAsSucceeded) { + for (let i = maybeStart; i < maybeCount; i++) { + maybeKeysSet.delete(maybeKeys[i]); + if (markAllAsSucceeded) { + relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags); + } + } + maybeCount = maybeStart; + } } function structuredTypeRelatedTo(source2, target2, reportErrors2, intersectionState) { const saveErrorInfo = captureErrorCalculationState(); @@ -65771,26 +65915,6 @@ function createTypeChecker(host) { )) { return result2; } - if (sourceFlags & 8388608 /* IndexedAccess */) { - const indexType = source2.indexType; - if (indexType.flags & 4194304 /* Index */) { - const unresolvedIndexConstraint = getBaseConstraintOfType(indexType.type); - const indexConstraint = unresolvedIndexConstraint && unresolvedIndexConstraint !== noConstraintType ? getIndexType(unresolvedIndexConstraint) : keyofConstraintType; - const constraint2 = getIndexedAccessType(source2.objectType, indexConstraint); - if (result2 = isRelatedTo( - constraint2, - target2, - 1 /* Source */, - /*reportErrors*/ - false, - /*headMessage*/ - void 0, - intersectionState - )) { - return result2; - } - } - } if (isMappedTypeGenericIndexedAccess(source2)) { const indexConstraint = getConstraintOfType(source2.indexType); if (indexConstraint) { @@ -67187,7 +67311,8 @@ function createTypeChecker(host) { return !!elementType && isEmptyLiteralType(elementType); } function isTupleLikeType(type) { - return isTupleType(type) || !!getPropertyOfType(type, "0"); + let lengthType; + return isTupleType(type) || !!getPropertyOfType(type, "0") || isArrayLikeType(type) && !!(lengthType = getTypeOfPropertyOfType(type, "length")) && everyType(lengthType, (t) => !!(t.flags & 256 /* NumberLiteral */)); } function isArrayOrTupleLikeType(type) { return isArrayLikeType(type) || isTupleLikeType(type); @@ -67198,17 +67323,7 @@ function createTypeChecker(host) { return propType; } if (everyType(type, isTupleType)) { - return mapType(type, (t) => { - const tupleType = t; - const restType = getRestTypeOfTupleType(tupleType); - if (!restType) { - return undefinedType; - } - if (compilerOptions.noUncheckedIndexedAccess && index >= tupleType.target.fixedLength + getEndElementCount(tupleType.target, 3 /* Fixed */)) { - return getUnionType([restType, undefinedType]); - } - return restType; - }); + return getTupleElementTypeOutOfStartCount(type, index, compilerOptions.noUncheckedIndexedAccess ? undefinedType : void 0); } return void 0; } @@ -67276,6 +67391,19 @@ function createTypeChecker(host) { function getRestTypeOfTupleType(type) { return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength); } + function getTupleElementTypeOutOfStartCount(type, index, undefinedOrMissingType2) { + return mapType(type, (t) => { + const tupleType = t; + const restType = getRestTypeOfTupleType(tupleType); + if (!restType) { + return undefinedType; + } + if (undefinedOrMissingType2 && index >= getTotalFixedElementCount(tupleType.target)) { + return getUnionType([restType, undefinedOrMissingType2]); + } + return restType; + }); + } function getRestArrayTypeOfTupleType(type) { const restType = getRestTypeOfTupleType(type); return restType && createArrayType(restType); @@ -67810,17 +67938,18 @@ function createTypeChecker(host) { ); } function inferTypeForHomomorphicMappedType(source, target, constraint) { - if (inInferTypeForHomomorphicMappedType) { - return void 0; + const cacheKey = source.id + "," + target.id + "," + constraint.id; + if (reverseMappedCache.has(cacheKey)) { + return reverseMappedCache.get(cacheKey); } - const key = source.id + "," + target.id + "," + constraint.id; - if (reverseMappedCache.has(key)) { - return reverseMappedCache.get(key); + const recursionKey = source.id + "," + (target.target || target).id; + if (contains(homomorphicMappedTypeInferenceStack, recursionKey)) { + return void 0; } - inInferTypeForHomomorphicMappedType = true; + homomorphicMappedTypeInferenceStack.push(recursionKey); const type = createReverseMappedType(source, target, constraint); - inInferTypeForHomomorphicMappedType = false; - reverseMappedCache.set(key, type); + homomorphicMappedTypeInferenceStack.pop(); + reverseMappedCache.set(cacheKey, type); return type; } function isPartiallyInferableType(type) { @@ -68774,12 +68903,6 @@ function createTypeChecker(host) { } return links.resolvedSymbol; } - function isInTypeQuery(node) { - return !!findAncestor( - node, - (n) => n.kind === 186 /* TypeQuery */ ? true : n.kind === 80 /* Identifier */ || n.kind === 166 /* QualifiedName */ ? false : "quit" - ); - } function isInAmbientOrTypeNode(node) { return !!(node.flags & 33554432 /* Ambient */ || findAncestor(node, (n) => isInterfaceDeclaration(n) || isTypeAliasDeclaration(n) || isTypeLiteralNode(n))); } @@ -70277,12 +70400,15 @@ function createTypeChecker(host) { return narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue); } const target = getReferenceCandidate(expr.right); - const leftType = getTypeOfExpression(expr.left); - if (leftType.flags & 8576 /* StringOrNumberLiteralOrUnique */) { - if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target) && getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) { + if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target)) { + const leftType = getTypeOfExpression(expr.left); + if (isTypeUsableAsPropertyName(leftType) && getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) { return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */); } - if (isMatchingReference(reference, target)) { + } + if (isMatchingReference(reference, target)) { + const leftType = getTypeOfExpression(expr.left); + if (isTypeUsableAsPropertyName(leftType)) { return narrowTypeByInKeyword(type, leftType, assumeTrue); } } @@ -70730,8 +70856,8 @@ function createTypeChecker(host) { } const parent2 = getRootDeclaration(symbol.valueDeclaration).parent; const links = getNodeLinks(parent2); - if (!(links.flags & 524288 /* AssignmentsMarked */)) { - links.flags |= 524288 /* AssignmentsMarked */; + if (!(links.flags & 131072 /* AssignmentsMarked */)) { + links.flags |= 131072 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(parent2)) { markNodeAssignments(parent2); } @@ -70739,7 +70865,7 @@ function createTypeChecker(host) { return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!findAncestor(node.parent, (node2) => (isFunctionLike(node2) || isCatchClause(node2)) && !!(getNodeLinks(node2).flags & 524288 /* AssignmentsMarked */)); + return !!findAncestor(node.parent, (node2) => (isFunctionLike(node2) || isCatchClause(node2)) && !!(getNodeLinks(node2).flags & 131072 /* AssignmentsMarked */)); } function markNodeAssignments(node) { if (node.kind === 80 /* Identifier */) { @@ -70821,9 +70947,13 @@ function createTypeChecker(host) { symbol, /*excludes*/ 111551 /* Value */ - ) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */)) { + ) && !isInTypeQuery(location)) { const target = resolveAlias(symbol); - if (getAllSymbolFlags(target) & (111551 /* Value */ | 1048576 /* ExportValue */)) { + if (getSymbolFlags( + symbol, + /*excludeTypeOnlyMeanings*/ + true + ) & (111551 /* Value */ | 1048576 /* ExportValue */)) { if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); } else { @@ -70841,11 +70971,11 @@ function createTypeChecker(host) { const parent2 = declaration.parent.parent; if (parent2.kind === 260 /* VariableDeclaration */ && getCombinedNodeFlagsCached(declaration) & 6 /* Constant */ || parent2.kind === 169 /* Parameter */) { const links = getNodeLinks(parent2); - if (!(links.flags & 16777216 /* InCheckIdentifier */)) { - links.flags |= 16777216 /* InCheckIdentifier */; + if (!(links.flags & 4194304 /* InCheckIdentifier */)) { + links.flags |= 4194304 /* InCheckIdentifier */; const parentType = getTypeForBindingElementParent(parent2, 0 /* Normal */); const parentTypeConstraint = parentType && mapType(parentType, getBaseConstraintOrType); - links.flags &= ~16777216 /* InCheckIdentifier */; + links.flags &= ~4194304 /* InCheckIdentifier */; if (parentTypeConstraint && parentTypeConstraint.flags & 1048576 /* Union */ && !(parent2.kind === 169 /* Parameter */ && isSymbolAssigned(symbol))) { const pattern = declaration.parent; const narrowedType = getFlowTypeOfReference( @@ -70922,17 +71052,7 @@ function createTypeChecker(host) { } let declaration = localOrExportSymbol.valueDeclaration; if (declaration && localOrExportSymbol.flags & 32 /* Class */) { - if (declaration.kind === 263 /* ClassDeclaration */ && nodeIsDecorated(legacyDecorators, declaration)) { - let container = getContainingClass(node); - while (container !== void 0) { - if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 1048576 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 2097152 /* ConstructorReferenceInClass */; - break; - } - container = getContainingClass(container); - } - } else if (declaration.kind === 231 /* ClassExpression */) { + if (isClassLike(declaration) && declaration.name !== node) { let container = getThisContainer( node, /*includeArrowFunctions*/ @@ -70940,14 +71060,7 @@ function createTypeChecker(host) { /*includeClassComputedPropertyName*/ false ); - while (container.kind !== 312 /* SourceFile */) { - if (container.parent === declaration) { - if (isPropertyDeclaration(container) && isStatic(container) || isClassStaticBlockDeclaration(container)) { - getNodeLinks(declaration).flags |= 1048576 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 2097152 /* ConstructorReferenceInClass */; - } - break; - } + while (container.kind !== 312 /* SourceFile */ && container.parent !== declaration) { container = getThisContainer( container, /*includeArrowFunctions*/ @@ -70956,6 +71069,11 @@ function createTypeChecker(host) { false ); } + if (container.kind !== 312 /* SourceFile */) { + getNodeLinks(declaration).flags |= 262144 /* ContainsConstructorReference */; + getNodeLinks(container).flags |= 262144 /* ContainsConstructorReference */; + getNodeLinks(node).flags |= 536870912 /* ConstructorReference */; + } } } checkNestedBlockScopedBinding(node, symbol); @@ -71086,7 +71204,7 @@ function createTypeChecker(host) { if (isForStatement(container)) { const varDeclList = getAncestor(symbol.valueDeclaration, 261 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 65536 /* NeedsLoopOutParameter */; } } getNodeLinks(symbol.valueDeclaration).flags |= 32768 /* BlockScopedBindingInLoop */; @@ -71364,7 +71482,7 @@ function createTypeChecker(host) { if (!isCallExpression2 && languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */ && (isPropertyDeclaration(container) || isClassStaticBlockDeclaration(container))) { forEachEnclosingBlockScopeContainer(node.parent, (current) => { if (!isSourceFile(current) || isExternalOrCommonJsModule(current)) { - getNodeLinks(current).flags |= 8388608 /* ContainsSuperPropertyInStaticInitializer */; + getNodeLinks(current).flags |= 2097152 /* ContainsSuperPropertyInStaticInitializer */; } }); } @@ -72465,7 +72583,7 @@ function createTypeChecker(host) { /*resolvedTypePredicate*/ void 0, minArgCount, - (left.flags | right.flags) & 39 /* PropagatingFlags */ + (left.flags | right.flags) & 167 /* PropagatingFlags */ ); result.compositeKind = 2097152 /* Intersection */; result.compositeSignatures = concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); @@ -72549,6 +72667,10 @@ function createTypeChecker(host) { function hasDefaultValue(node) { return node.kind === 208 /* BindingElement */ && !!node.initializer || node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */; } + function isSpreadIntoCallOrNew(node) { + const parent2 = walkUpParenthesizedExpressions(node.parent); + return isSpreadElement(parent2) && isCallOrNewExpression(parent2.parent); + } function checkArrayLiteral(node, checkMode, forceTuple) { const elements = node.elements; const elementCount = elements.length; @@ -72556,14 +72678,13 @@ function createTypeChecker(host) { const elementFlags = []; pushCachedContextualType(node); const inDestructuringPattern = isAssignmentTarget(node); - const isSpreadIntoCallOrNew = isSpreadElement(node.parent) && isCallOrNewExpression(node.parent.parent); - const inConstContext = isSpreadIntoCallOrNew || isConstContext(node); + const inConstContext = isConstContext(node); const contextualType = getApparentTypeOfContextualType( node, /*contextFlags*/ void 0 ); - const inTupleContext = isSpreadIntoCallOrNew || !!contextualType && someType(contextualType, isTupleLikeType); + const inTupleContext = isSpreadIntoCallOrNew(node) || !!contextualType && someType(contextualType, isTupleLikeType); let hasOmittedExpression = false; for (let i = 0; i < elementCount; i++) { const e = elements[i]; @@ -73996,7 +74117,7 @@ function createTypeChecker(host) { } let diagnosticMessage; const declarationName = idText(right); - if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & 32 /* Static */) && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { + if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & 32 /* Static */) && (useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { diagnosticMessage = error2(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } else if (valueDeclaration.kind === 263 /* ClassDeclaration */ && node.parent.kind !== 183 /* TypeReference */ && !(valueDeclaration.flags & 33554432 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error2(right, Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -74903,7 +75024,7 @@ function createTypeChecker(host) { } } function getThisArgumentOfCall(node) { - const expression = node.kind === 213 /* CallExpression */ ? node.expression : node.kind === 215 /* TaggedTemplateExpression */ ? node.tag : void 0; + const expression = node.kind === 213 /* CallExpression */ ? node.expression : node.kind === 215 /* TaggedTemplateExpression */ ? node.tag : node.kind === 170 /* Decorator */ && !legacyDecorators ? node.expression : void 0; if (expression) { const callee = skipOuterExpressions(expression); if (isAccessExpression(callee)) { @@ -75491,7 +75612,7 @@ function createTypeChecker(host) { parameters.push(createCombinedSymbolFromTypes(symbols, mapDefined(candidates, (candidate) => tryGetTypeAtPosition(candidate, i)))); } const restParameterSymbols = mapDefined(candidates, (c) => signatureHasRestParameter(c) ? last(c.parameters) : void 0); - let flags = 0 /* None */; + let flags = 128 /* IsSignatureCandidateForOverloadFailure */; if (restParameterSymbols.length !== 0) { const type = createArrayType(getUnionType(mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); @@ -76215,6 +76336,8 @@ function createTypeChecker(host) { return returnType; } function checkDeprecatedSignature(signature, node) { + if (signature.flags & 128 /* IsSignatureCandidateForOverloadFailure */) + return; if (signature.declaration && signature.declaration.flags & 536870912 /* Deprecated */) { const suggestionNode = getDeprecatedSuggestionNode(node); const name = tryGetPropertyAccessOrIdentifierToString(getInvokedExpression(node)); @@ -76688,7 +76811,7 @@ function createTypeChecker(host) { } return restParameter.escapedName; } - function getParameterIdentifierNameAtPosition(signature, pos) { + function getParameterIdentifierInfoAtPosition(signature, pos) { var _a; if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 324 /* JSDocFunctionType */) { return void 0; @@ -76696,10 +76819,16 @@ function createTypeChecker(host) { const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { const param = signature.parameters[pos]; - return isParameterDeclarationWithIdentifierName(param) ? [param.escapedName, false] : void 0; + const paramIdent = getParameterDeclarationIdentifier(param); + return paramIdent ? { + parameter: paramIdent, + parameterName: param.escapedName, + isRestParameter: false + } : void 0; } const restParameter = signature.parameters[paramCount] || unknownSymbol; - if (!isParameterDeclarationWithIdentifierName(restParameter)) { + const restIdent = getParameterDeclarationIdentifier(restParameter); + if (!restIdent) { return void 0; } const restType = getTypeOfSymbol(restParameter); @@ -76708,18 +76837,19 @@ function createTypeChecker(host) { const index = pos - paramCount; const associatedName = associatedNames == null ? void 0 : associatedNames[index]; const isRestTupleElement = !!(associatedName == null ? void 0 : associatedName.dotDotDotToken); - return associatedName ? [ - getTupleElementLabel(associatedName), - isRestTupleElement - ] : void 0; + if (associatedName) { + Debug.assert(isIdentifier(associatedName.name)); + return { parameter: associatedName.name, parameterName: associatedName.name.escapedText, isRestParameter: isRestTupleElement }; + } + return void 0; } if (pos === paramCount) { - return [restParameter.escapedName, true]; + return { parameter: restIdent, parameterName: restParameter.escapedName, isRestParameter: true }; } return void 0; } - function isParameterDeclarationWithIdentifierName(symbol) { - return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name); + function getParameterDeclarationIdentifier(symbol) { + return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name) && symbol.valueDeclaration.name; } function isValidDeclarationForTupleLabel(d) { return d.kind === 202 /* NamedTupleMember */ || isParameter(d) && d.name && isIdentifier(d.name); @@ -79582,7 +79712,18 @@ function createTypeChecker(host) { addLazyDiagnostic(checkSignatureDeclarationDiagnostics); function checkSignatureDeclarationDiagnostics() { checkCollisionWithArgumentsInGeneratedCode(node); - const returnTypeNode = getEffectiveReturnTypeNode(node); + let returnTypeNode = getEffectiveReturnTypeNode(node); + let returnTypeErrorLocation = returnTypeNode; + if (isInJSFile(node)) { + const typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && isTypeReferenceNode(typeTag.typeExpression.type)) { + const signature = getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + if (signature && signature.declaration) { + returnTypeNode = getEffectiveReturnTypeNode(signature.declaration); + returnTypeErrorLocation = typeTag.typeExpression.type; + } + } + } if (noImplicitAny && !returnTypeNode) { switch (node.kind) { case 180 /* ConstructSignature */: @@ -79593,21 +79734,21 @@ function createTypeChecker(host) { break; } } - if (returnTypeNode) { + if (returnTypeNode && returnTypeErrorLocation) { const functionFlags2 = getFunctionFlags(node); if ((functionFlags2 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { const returnType = getTypeFromTypeNode(returnTypeNode); if (returnType === voidType) { - error2(returnTypeNode, Diagnostics.A_generator_cannot_have_a_void_type_annotation); + error2(returnTypeErrorLocation, Diagnostics.A_generator_cannot_have_a_void_type_annotation); } else { const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags2 & 2 /* Async */) !== 0) || anyType; const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags2 & 2 /* Async */) !== 0) || generatorYieldType; const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags2 & 2 /* Async */) !== 0) || unknownType; const generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags2 & 2 /* Async */)); - checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode); + checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeErrorLocation); } } else if ((functionFlags2 & 3 /* AsyncGenerator */) === 2 /* Async */) { - checkAsyncFunctionReturnType(node, returnTypeNode); + checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation); } } if (node.kind !== 181 /* IndexSignature */ && node.kind !== 324 /* JSDocFunctionType */) { @@ -79688,7 +79829,7 @@ function createTypeChecker(host) { case "length": case "caller": case "arguments": - if (compilerOptions.useDefineForClassFields) { + if (useDefineForClassFields) { break; } case "prototype": @@ -79790,7 +79931,7 @@ function createTypeChecker(host) { function setNodeLinksForPrivateIdentifierScope(node) { if (isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { for (let lexicalScope = getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = getEnclosingBlockScopeContainer(lexicalScope)) { - getNodeLinks(lexicalScope).flags |= 4194304 /* ContainsClassWithPrivateIdentifiers */; + getNodeLinks(lexicalScope).flags |= 1048576 /* ContainsClassWithPrivateIdentifiers */; } if (isClassExpression(node.parent)) { const enclosingIterationStatement = getEnclosingIterationStatement(node.parent); @@ -79836,7 +79977,7 @@ function createTypeChecker(host) { if (classExtendsNull) { error2(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - const superCallShouldBeRootLevel = (getEmitScriptTarget(compilerOptions) !== 99 /* ESNext */ || !useDefineForClassFields) && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p) => hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */))); + const superCallShouldBeRootLevel = !emitStandardClassFields && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p) => hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */))); if (superCallShouldBeRootLevel) { if (!superCallIsRootLevelInConstructor(superCall, node.body)) { error2(superCall, Diagnostics.A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers); @@ -80689,7 +80830,7 @@ function createTypeChecker(host) { } return typeAsAwaitable.awaitedTypeOfType = type; } - function checkAsyncFunctionReturnType(node, returnTypeNode) { + function checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation) { const returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { if (isErrorType(returnType)) { @@ -80700,7 +80841,7 @@ function createTypeChecker(host) { true ); if (globalPromiseType !== emptyGenericType && !isReferenceToType2(returnType, globalPromiseType)) { - error2(returnTypeNode, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedTypeNoAlias(returnType) || voidType)); + reportErrorForInvalidReturnType(Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, returnTypeNode, returnTypeErrorLocation, typeToString(getAwaitedTypeNoAlias(returnType) || voidType)); return; } } else { @@ -80710,7 +80851,7 @@ function createTypeChecker(host) { } const promiseConstructorName = getEntityNameFromTypeNode(returnTypeNode); if (promiseConstructorName === void 0) { - error2(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, typeToString(returnType)); return; } const promiseConstructorSymbol = resolveEntityName( @@ -80725,9 +80866,9 @@ function createTypeChecker(host) { /*reportErrors*/ false )) { - error2(returnTypeNode, Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + error2(returnTypeErrorLocation, Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { - error2(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, entityNameToString(promiseConstructorName)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); } return; } @@ -80736,15 +80877,16 @@ function createTypeChecker(host) { true ); if (globalPromiseConstructorLikeType === emptyObjectType) { - error2(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, entityNameToString(promiseConstructorName)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); return; } - if (!checkTypeAssignableTo( - promiseConstructorType, - globalPromiseConstructorLikeType, - returnTypeNode, - Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value - )) { + const headMessage = Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value; + const errorInfo = () => returnTypeNode === returnTypeErrorLocation ? void 0 : chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type + ); + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeErrorLocation, headMessage, errorInfo)) { return; } const rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); @@ -80766,6 +80908,14 @@ function createTypeChecker(host) { node, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member ); + function reportErrorForInvalidReturnType(message, returnTypeNode2, returnTypeErrorLocation2, typeName) { + if (returnTypeNode2 === returnTypeErrorLocation2) { + error2(returnTypeErrorLocation2, message, typeName); + } else { + const diag2 = error2(returnTypeErrorLocation2, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + addRelatedInfo(diag2, createDiagnosticForNode(returnTypeNode2, message, typeName)); + } + } } function checkDecorator(node) { const signature = getResolvedSignature(node); @@ -80992,6 +81142,7 @@ function createTypeChecker(host) { for (const parameter of containingSignature.parameters) { markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(containingSignature)); break; } } @@ -81533,7 +81684,7 @@ function createTypeChecker(host) { } function checkWeakMapSetCollision(node) { const enclosingBlockScope = getEnclosingBlockScopeContainer(node); - if (getNodeCheckFlags(enclosingBlockScope) & 4194304 /* ContainsClassWithPrivateIdentifiers */) { + if (getNodeCheckFlags(enclosingBlockScope) & 1048576 /* ContainsClassWithPrivateIdentifiers */) { Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier"); errorSkippedOn("noEmit", node, Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText); } @@ -81547,18 +81698,18 @@ function createTypeChecker(host) { let hasCollision = false; if (isClassExpression(node)) { for (const member of node.members) { - if (getNodeCheckFlags(member) & 8388608 /* ContainsSuperPropertyInStaticInitializer */) { + if (getNodeCheckFlags(member) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { hasCollision = true; break; } } } else if (isFunctionExpression(node)) { - if (getNodeCheckFlags(node) & 8388608 /* ContainsSuperPropertyInStaticInitializer */) { + if (getNodeCheckFlags(node) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { hasCollision = true; } } else { const container = getEnclosingBlockScopeContainer(node); - if (container && getNodeCheckFlags(container) & 8388608 /* ContainsSuperPropertyInStaticInitializer */) { + if (container && getNodeCheckFlags(container) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { hasCollision = true; } } @@ -81593,9 +81744,6 @@ function createTypeChecker(host) { if ((getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */) !== 0 || isParameterDeclaration(node)) { return; } - if (node.kind === 260 /* VariableDeclaration */ && !node.initializer) { - return; - } const symbol = getSymbolOfDeclaration(node); if (symbol.flags & 1 /* FunctionScopedVariable */) { if (!isIdentifier(node.name)) @@ -83105,7 +83253,7 @@ function createTypeChecker(host) { node ); const willTransformPrivateElementsOrClassStaticBlocks = languageVersion <= 9 /* ES2022 */; - const willTransformInitializers = !useDefineForClassFields || languageVersion < 9 /* ES2022 */; + const willTransformInitializers = !emitStandardClassFields; if (willTransformStaticElementsOfDecoratedClass || willTransformPrivateElementsOrClassStaticBlocks) { for (const member of node.members) { if (willTransformStaticElementsOfDecoratedClass && classElementOrClassElementParameterIsDecorated( @@ -83863,10 +84011,22 @@ function createTypeChecker(host) { return +expr.text; case 217 /* ParenthesizedExpression */: return evaluate(expr.expression, location); - case 80 /* Identifier */: - if (isInfinityOrNaNString(expr.escapedText)) { - return +expr.escapedText; + case 80 /* Identifier */: { + const identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText) && resolveEntityName( + identifier, + 111551 /* Value */, + /*ignoreErrors*/ + true + ) === getGlobalSymbol( + identifier.escapedText, + 111551 /* Value */, + /*diagnostic*/ + void 0 + )) { + return +identifier.escapedText; } + } case 211 /* PropertyAccessExpression */: if (isEntityNameExpression(expr)) { const symbol = resolveEntityName( @@ -84205,7 +84365,7 @@ function createTypeChecker(host) { } return; } - const targetFlags = getAllSymbolFlags(target); + const targetFlags = getSymbolFlags(target); const excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) | (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (targetFlags & excludedMeanings) { const message = node.kind === 281 /* ExportSpecifier */ ? Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; @@ -84363,7 +84523,7 @@ function createTypeChecker(host) { if (node.moduleReference.kind !== 283 /* ExternalModuleReference */) { const target = resolveAlias(getSymbolOfDeclaration(node)); if (target !== unknownSymbol) { - const targetFlags = getAllSymbolFlags(target); + const targetFlags = getSymbolFlags(target); if (targetFlags & 111551 /* Value */) { const moduleName = getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { @@ -84503,7 +84663,7 @@ function createTypeChecker(host) { markExportAsReferenced(node); } const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol); - if (!target || getAllSymbolFlags(target) & 111551 /* Value */) { + if (!target || getSymbolFlags(target) & 111551 /* Value */) { checkExpressionCached(node.propertyName || node.name); } } @@ -84548,7 +84708,7 @@ function createTypeChecker(host) { )); if (sym) { markAliasReferenced(sym, id); - if (getAllSymbolFlags(sym) & 111551 /* Value */) { + if (getSymbolFlags(sym) & 111551 /* Value */) { checkExpressionCached(id); if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && getTypeOnlyAliasDeclaration(sym, 111551 /* Value */)) { error2( @@ -85169,7 +85329,7 @@ function createTypeChecker(host) { function copyLocallyVisibleExportSymbols(source, meaning2) { if (meaning2) { source.forEach((symbol) => { - if (!getDeclarationOfKind(symbol, 281 /* ExportSpecifier */) && !getDeclarationOfKind(symbol, 280 /* NamespaceExport */)) { + if (!getDeclarationOfKind(symbol, 281 /* ExportSpecifier */) && !getDeclarationOfKind(symbol, 280 /* NamespaceExport */) && symbol.escapedName !== "default" /* Default */) { copySymbol(symbol, meaning2); } }); @@ -85795,7 +85955,7 @@ function createTypeChecker(host) { return symbolLinks2.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(getAllSymbolFlags(s) & 111551 /* Value */); + return s && !!(getSymbolFlags(s) & 111551 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -85925,7 +86085,11 @@ function createTypeChecker(host) { case 276 /* ImportSpecifier */: case 281 /* ExportSpecifier */: const symbol = getSymbolOfDeclaration(node); - return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */); + return !!symbol && isAliasResolvedToValue( + symbol, + /*excludeTypeOnlyValues*/ + true + ); case 278 /* ExportDeclaration */: const exportClause = node.exportClause; return !!exportClause && (isNamespaceExport(exportClause) || some(exportClause.elements, isValueAliasDeclaration)); @@ -85942,7 +86106,7 @@ function createTypeChecker(host) { const isValue = isAliasResolvedToValue(getSymbolOfDeclaration(node)); return isValue && node.moduleReference && !nodeIsMissing(node.moduleReference); } - function isAliasResolvedToValue(symbol) { + function isAliasResolvedToValue(symbol, excludeTypeOnlyValues) { if (!symbol) { return false; } @@ -85950,7 +86114,12 @@ function createTypeChecker(host) { if (target === unknownSymbol) { return true; } - return !!((getAllSymbolFlags(target) ?? -1) & 111551 /* Value */) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); + return !!(getSymbolFlags( + symbol, + excludeTypeOnlyValues, + /*excludeLocalMeanings*/ + true + ) & 111551 /* Value */) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -85964,7 +86133,7 @@ function createTypeChecker(host) { return true; } const target = getSymbolLinks(symbol).aliasTarget; - if (target && getEffectiveModifierFlags(node) & 1 /* Export */ && getAllSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { + if (target && getEffectiveModifierFlags(node) & 1 /* Export */ && getSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { return true; } } @@ -93405,7 +93574,7 @@ function transformTypeScript(context) { const constantValue = tryGetConstEnumValue(node); if (constantValue !== void 0) { setConstantValue(node, constantValue); - const substitute = typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : factory2.createNumericLiteral(constantValue); + const substitute = typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : constantValue < 0 ? factory2.createPrefixUnaryExpression(41 /* MinusToken */, factory2.createNumericLiteral(Math.abs(constantValue))) : factory2.createNumericLiteral(constantValue); if (!compilerOptions.removeComments) { const originalNode = getOriginalNode(node, isAccessExpression); addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, ` ${safeMultiLineComment(getTextOfNode(originalNode))} `); @@ -93830,6 +93999,11 @@ function transformClassFields(context) { } } } + function getClassThis() { + const lex = getClassLexicalEnvironment(); + const classThis = lex.classThis ?? lex.classConstructor ?? (currentClassContainer == null ? void 0 : currentClassContainer.name); + return Debug.checkDefined(classThis); + } function transformAutoAccessor(node) { const commentRange = getCommentRange(node); const sourceMapRange = getSourceMapRange(node); @@ -93856,11 +94030,13 @@ function transformClassFields(context) { setOriginalNode(backingField, node); setEmitFlags(backingField, 3072 /* NoComments */); setSourceMapRange(backingField, sourceMapRange); - const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName); + const receiver = isStatic(node) ? getClassThis() : factory2.createThis(); + const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName, receiver); setOriginalNode(getter, node); setCommentRange(getter, commentRange); setSourceMapRange(getter, sourceMapRange); - const setter = createAccessorPropertySetRedirector(factory2, node, modifiers, setterName); + const setterModifiers = factory2.createModifiersFromModifierFlags(modifiersToFlags(modifiers)); + const setter = createAccessorPropertySetRedirector(factory2, node, setterModifiers, setterName, receiver); setOriginalNode(setter, node); setEmitFlags(setter, 3072 /* NoComments */); setSourceMapRange(setter, sourceMapRange); @@ -94417,6 +94593,7 @@ function transformClassFields(context) { return filter(node.members, isNonStaticMethodOrAccessorWithPrivateName); } function getClassFacts(node) { + var _a; let facts = 0 /* None */; const original = getOriginalNode(node); if (isClassDeclaration(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) { @@ -94433,6 +94610,8 @@ function transformClassFields(context) { if (isStatic(member)) { if (member.name && (isPrivateIdentifier(member.name) || isAutoAccessorPropertyDeclaration(member)) && shouldTransformPrivateElementsOrClassStaticBlocks) { facts |= 2 /* NeedsClassConstructorReference */; + } else if (isAutoAccessorPropertyDeclaration(member) && shouldTransformAutoAccessors === -1 /* True */ && !node.name && !((_a = node.emitNode) == null ? void 0 : _a.classThis)) { + facts |= 2 /* NeedsClassConstructorReference */; } if (isPropertyDeclaration(member) || isClassStaticBlockDeclaration(member)) { if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* ContainsLexicalThis */) { @@ -94453,6 +94632,9 @@ function transformClassFields(context) { containsInstancePrivateElements || (containsInstancePrivateElements = isPrivateIdentifierClassElementDeclaration(member)); } else if (isPrivateIdentifierClassElementDeclaration(member)) { containsInstancePrivateElements = true; + if (resolver.getNodeCheckFlags(member) & 262144 /* ContainsConstructorReference */) { + facts |= 2 /* NeedsClassConstructorReference */; + } } else if (isPropertyDeclaration(member)) { containsPublicInstanceFields = true; containsInitializedPublicInstanceFields || (containsInitializedPublicInstanceFields = !!member.initializer); @@ -94553,10 +94735,11 @@ function transformClassFields(context) { getClassLexicalEnvironment().classConstructor = factory2.cloneNode(temp); pendingClassReferenceAssignment = factory2.createAssignment(temp, factory2.getInternalName(node)); } - if ((_b = node.emitNode) == null ? void 0 : _b.classThis) { - getClassLexicalEnvironment().classThis = node.emitNode.classThis; - } } + if ((_b = node.emitNode) == null ? void 0 : _b.classThis) { + getClassLexicalEnvironment().classThis = node.emitNode.classThis; + } + const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */; const isExport = hasSyntacticModifier(node, 1 /* Export */); const isDefault = hasSyntacticModifier(node, 1024 /* Default */); let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); @@ -94591,6 +94774,11 @@ function transformClassFields(context) { ) )); } + const alias = getClassLexicalEnvironment().classConstructor; + if (isClassWithConstructorReference && alias) { + enableSubstitutionForClassAliases(); + classAliases[getOriginalNodeId(node)] = alias; + } const classDecl = factory2.updateClassDeclaration( node, modifiers, @@ -94613,14 +94801,14 @@ function transformClassFields(context) { var _a, _b, _c; const isDecoratedClassDeclaration = !!(facts & 1 /* ClassWasDecorated */); const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); - const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 1048576 /* ClassWithConstructorReference */; + const classCheckFlags = resolver.getNodeCheckFlags(node); + const isClassWithConstructorReference = classCheckFlags & 262144 /* ContainsConstructorReference */; let temp; function createClassTempVar() { var _a2; if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a2 = node.emitNode) == null ? void 0 : _a2.classThis)) { return getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; } - const classCheckFlags = resolver.getNodeCheckFlags(node); const requiresBlockScopedVar = classCheckFlags & 32768 /* BlockScopedBindingInLoop */; const temp2 = factory2.createTempVariable( requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, @@ -95587,7 +95775,7 @@ function transformClassFields(context) { } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 2097152 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -96441,7 +96629,7 @@ function transformLegacyDecorators(context) { } } function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 1048576 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */) { enableSubstitutionForClassAliases(); const classAlias = factory2.createUniqueName(node.name && !isGeneratedIdentifier(node.name) ? idText(node.name) : "default"); classAliases[getOriginalNodeId(node)] = classAlias; @@ -96474,7 +96662,7 @@ function transformLegacyDecorators(context) { } function trySubstituteClassAlias(node) { if (classAliases) { - if (resolver.getNodeCheckFlags(node) & 2097152 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -96500,6 +96688,7 @@ function transformESDecorators(context) { endLexicalEnvironment, hoistVariableDeclaration } = context; + const languageVersion = getEmitScriptTarget(context.getCompilerOptions()); let top; let classInfo; let classThis; @@ -98001,6 +98190,17 @@ function transformESDecorators(context) { function transformDecorator(decorator) { const expression = visitNode(decorator.expression, visitor, isExpression); setEmitFlags(expression, 3072 /* NoComments */); + const innerExpression = skipOuterExpressions(expression); + if (isAccessExpression(innerExpression)) { + const { target, thisArg } = factory2.createCallBinding( + expression, + hoistVariableDeclaration, + languageVersion, + /*cacheIdentifiers*/ + true + ); + return factory2.restoreOuterExpressions(expression, factory2.createFunctionBindCall(target, thisArg, [])); + } return expression; } function createDescriptorMethod(original, name, modifiers, asteriskToken, kind, parameters, body) { @@ -101591,10 +101791,10 @@ function transformJsx(context) { for (const prop of attr.expression.properties) { if (isSpreadAssignment(prop)) { finishObjectLiteralIfNeeded(); - expressions.push(prop.expression); + expressions.push(Debug.checkDefined(visitNode(prop.expression, visitor, isExpression))); continue; } - properties.push(prop); + properties.push(Debug.checkDefined(visitNode(prop, visitor))); } continue; } @@ -104644,10 +104844,10 @@ function transformES2015(context) { name )); const checkFlags = resolver.getNodeCheckFlags(decl); - if (checkFlags & 262144 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { + if (checkFlags & 65536 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { const outParamName = factory2.createUniqueName("out_" + idText(name)); let flags = 0 /* None */; - if (checkFlags & 262144 /* NeedsLoopOutParameter */) { + if (checkFlags & 65536 /* NeedsLoopOutParameter */) { flags |= 1 /* Body */; } if (isForStatement(container)) { @@ -115691,7 +115891,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return !(expression.numericLiteralFlags & 448 /* WithSpecifier */) && !stringContains(text, tokenToString(25 /* DotToken */)) && !stringContains(text, String.fromCharCode(69 /* E */)) && !stringContains(text, String.fromCharCode(101 /* e */)); } else if (isAccessExpression(expression)) { const constantValue = getConstantValue(expression); - return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue; + return typeof constantValue === "number" && isFinite(constantValue) && constantValue >= 0 && Math.floor(constantValue) === constantValue; } } function emitElementAccessExpression(node) { @@ -118828,14 +119028,14 @@ function getEmitListItem(emit, parenthesizerRule) { } // src/compiler/watchUtilities.ts -function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { +function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames2) { if (!host.getDirectories || !host.readDirectory) { return void 0; } const cachedReadDirectoryResult = /* @__PURE__ */ new Map(); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); return { - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, fileExists, readFile: (path, encoding) => host.readFile(path, encoding), directoryExists: host.directoryExists && directoryExists, @@ -118957,7 +119157,7 @@ function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensi const rootResult = tryReadDirectory2(rootDir, rootDirPath); let rootSymLinkResult; if (rootResult !== void 0) { - return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); + return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames2, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { @@ -119158,7 +119358,7 @@ function isIgnoredFileFromWildCardWatching({ program, extraFileExtensions, currentDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 }) { @@ -119174,7 +119374,7 @@ function isIgnoredFileFromWildCardWatching({ writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); return true; } - if (isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) { + if (isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames2, currentDirectory)) { writeLog(`Project: ${configFileName} Detected excluded file: ${fileOrDirectory}`); return true; } @@ -119237,7 +119437,7 @@ function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo2) { function createExcludeHandlingAddWatch(key) { return (file, cb, flags, options, detailInfo1, detailInfo2) => { var _a; - return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call( + return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call( /*thisArgs*/ void 0, file, @@ -119249,7 +119449,7 @@ function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo2) { ) : excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2); }; } - function useCaseSensitiveFileNames() { + function useCaseSensitiveFileNames2() { return typeof host.useCaseSensitiveFileNames === "boolean" ? host.useCaseSensitiveFileNames : host.useCaseSensitiveFileNames(); } function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) { @@ -121372,6 +121572,14 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config case 265 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); return "skip"; + case 176 /* Constructor */: + case 174 /* MethodDeclaration */: + case 262 /* FunctionDeclaration */: + if (!node.body) { + diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Signature_declarations_can_only_be_used_in_TypeScript_files)); + return "skip"; + } + return; case 266 /* EnumDeclaration */: const enumKeyword = Debug.checkDefined(tokenToString(94 /* EnumKeyword */)); diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); @@ -123287,6 +123495,9 @@ function parseConfigHostFromCompilerHostLike(host, directoryStructureHost = host return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); }, readFile: (f) => directoryStructureHost.readFile(f), + directoryExists: maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: maybeBind(directoryStructureHost, directoryStructureHost.realpath), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: () => host.getCurrentDirectory(), onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || returnUndefined, @@ -126326,12 +126537,12 @@ function getMatchedIncludeSpec(program, fileName) { return true; const isJsonFile = fileExtensionIs(fileName, ".json" /* Json */); const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); - const useCaseSensitiveFileNames = program.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = program.useCaseSensitiveFileNames(); return find((_b = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs, (includeSpec) => { if (isJsonFile && !endsWith(includeSpec, ".json" /* Json */)) return false; const pattern = getPatternFromSpec(includeSpec, basePath, "files"); - return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames).test(fileName); + return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames2).test(fileName); }); } function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) { @@ -126560,7 +126771,7 @@ function createWatchFactory(host, options) { return result; } function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost = host) { - const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); const compilerHost = { getSourceFile: createGetSourceFile( (fileName, encoding) => !encoding ? compilerHost.readFile(fileName) : host.readFile(fileName, encoding), @@ -126576,8 +126787,8 @@ function createCompilerHostFromProgramHost(host, getCompilerOptions, directorySt (path) => host.directoryExists(path) ), getCurrentDirectory: memoize(() => host.getCurrentDirectory()), - useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, - getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames), + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2, + getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames2), getNewLine: () => getNewLineCharacter(getCompilerOptions()), fileExists: (f) => host.fileExists(f), readFile: (f) => host.readFile(f), @@ -126817,7 +127028,7 @@ function createWatchProgram(host) { const sourceFilesCache = /* @__PURE__ */ new Map(); let missingFilePathsRequestedForRelease; let hasChangedCompilerOptions = false; - const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); const currentDirectory = host.getCurrentDirectory(); const { configFileName, optionsToExtend: optionsToExtendForConfigFile = {}, watchOptionsToExtend, extraFileExtensions, createProgram: createProgram2 } = host; let { rootFiles: rootFileNames, options: compilerOptions, watchOptions, projectReferences } = host; @@ -126825,7 +127036,7 @@ function createWatchProgram(host) { let configFileParsingDiagnostics; let canConfigFileJsonReportNoInputFiles = false; let hasChangedConfigFileParsingErrors = false; - const cachedDirectoryStructureHost = configFileName === void 0 ? void 0 : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + const cachedDirectoryStructureHost = configFileName === void 0 ? void 0 : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames2); const directoryStructureHost = cachedDirectoryStructureHost || host; const parseConfigFileHost = parseConfigHostFromCompilerHostLike(host, directoryStructureHost); let newLine = updateNewLine(); @@ -126843,8 +127054,8 @@ function createWatchProgram(host) { Debug.assert(compilerOptions); Debug.assert(rootFileNames); const { watchFile: watchFile2, watchDirectory, writeLog } = createWatchFactory(host, compilerOptions); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); - writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames}`); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); + writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames2}`); let configFileWatcher; if (configFileName) { configFileWatcher = watchFile2(configFileName, scheduleProgramReload, 2e3 /* High */, watchOptions, WatchType.ConfigFile); @@ -126953,7 +127164,6 @@ function createWatchProgram(host) { if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { - debugger; resolutionCache.onChangesAffectModuleResolution(); } } @@ -127350,7 +127560,7 @@ function createWatchProgram(host) { options: compilerOptions, program: getCurrentBuilderProgram() || rootFileNames, currentDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 })) @@ -127440,7 +127650,7 @@ function createWatchProgram(host) { options: config.parsedCommandLine.options, program: config.parsedCommandLine.fileNames, currentDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 })) @@ -130054,6 +130264,8 @@ var ScriptElementKind = /* @__PURE__ */ ((ScriptElementKind2) => { ScriptElementKind2["enumMemberElement"] = "enum member"; ScriptElementKind2["variableElement"] = "var"; ScriptElementKind2["localVariableElement"] = "local var"; + ScriptElementKind2["variableUsingElement"] = "using"; + ScriptElementKind2["variableAwaitUsingElement"] = "await using"; ScriptElementKind2["functionElement"] = "function"; ScriptElementKind2["localFunctionElement"] = "local function"; ScriptElementKind2["memberFunctionElement"] = "method"; @@ -132789,13 +133001,16 @@ function needsNameFromDeclaration(symbol) { return !(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */); } function getDefaultLikeExportNameFromDeclaration(symbol) { - return firstDefined( - symbol.declarations, - (d) => { - var _a, _b; - return isExportAssignment(d) ? (_a = tryCast(skipOuterExpressions(d.expression), isIdentifier)) == null ? void 0 : _a.text : (_b = tryCast(getNameOfDeclaration(d), isIdentifier)) == null ? void 0 : _b.text; + return firstDefined(symbol.declarations, (d) => { + var _a, _b, _c; + if (isExportAssignment(d)) { + return (_a = tryCast(skipOuterExpressions(d.expression), isIdentifier)) == null ? void 0 : _a.text; } - ); + if (isExportSpecifier(d) && d.symbol.flags === 2097152 /* Alias */) { + return (_b = tryCast(d.propertyName, isIdentifier)) == null ? void 0 : _b.text; + } + return (_c = tryCast(getNameOfDeclaration(d), isIdentifier)) == null ? void 0 : _c.text; + }); } function getSymbolParentOrFail(symbol) { var _a; @@ -133192,10 +133407,10 @@ function isImportablePath(fromPath, toPath3, getCanonicalFileName, globalCachePa } function forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, cb) { var _a, _b; - const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); + const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); const excludePatterns = preferences.autoImportFileExcludePatterns && mapDefined(preferences.autoImportFileExcludePatterns, (spec) => { const pattern = getPatternFromSpec(spec, "", "exclude"); - return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames) : void 0; + return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames2) : void 0; }); forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, (module2, file) => cb( module2, @@ -134657,12 +134872,12 @@ var DocumentHighlights; function isDocumentRegistryEntry(entry) { return !!entry.sourceFile; } -function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { - return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); +function createDocumentRegistry(useCaseSensitiveFileNames2, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory); } -function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory = "", externalCache) { +function createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory = "", externalCache) { const buckets = /* @__PURE__ */ new Map(); - const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); + const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames2); function reportStats() { const bucketInfoArray = arrayFrom(buckets.keys()).filter((name) => name && name.charAt(0) === "_").map((name) => { const entries = buckets.get(name); @@ -134865,12 +135080,12 @@ function getDocumentRegistryBucketKeyWithMode(key, mode) { // src/services/getEditsForFileRename.ts function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { - const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); const newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts_textChanges_exports.ChangeTracker.with({ host, formatContext, preferences }, (changeTracker) => { - updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames2); updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } @@ -134892,7 +135107,7 @@ function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) { const rel = getRelativePathFromFile(a0, b0, getCanonicalFileName); return combinePathsSafe(getDirectoryPath(a1), rel); } -function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { +function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames2) { const { configFile } = program.getCompilerOptions(); if (!configFile) return; @@ -134916,10 +135131,10 @@ function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, /*excludes*/ [], includes, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, currentDirectory ); - if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(oldFileOrDirPath) && !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(newFileOrDirPath)) { changeTracker.insertNodeAfter(configFile, last(property.initializer.elements), factory.createStringLiteral(relativePath(newFileOrDirPath))); } return; @@ -134967,7 +135182,7 @@ function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, configDir, path, /*ignoreCase*/ - !useCaseSensitiveFileNames + !useCaseSensitiveFileNames2 ); } } @@ -135757,7 +135972,7 @@ function preProcessFile(sourceText, readImportFiles = true, detectJavaScriptImpo } // src/services/sourcemaps.ts -var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; +var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+/=]+)$)?/; function getSourceMapper(host) { const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); const currentDirectory = host.getCurrentDirectory(); @@ -135942,8 +136157,8 @@ function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { diags.push(createDiagnosticForNode(init, Diagnostics.require_call_may_be_converted_to_an_import)); } } - const jsdocTypedefNode = ts_codefix_exports.getJSDocTypedefNode(node); - if (jsdocTypedefNode) { + const jsdocTypedefNodes = ts_codefix_exports.getJSDocTypedefNodes(node); + for (const jsdocTypedefNode of jsdocTypedefNodes) { diags.push(createDiagnosticForNode(jsdocTypedefNode, Diagnostics.JSDoc_typedef_may_be_converted_to_TypeScript_type)); } if (ts_codefix_exports.parameterShouldGetTypeFromJSDoc(node)) { @@ -137977,7 +138192,7 @@ function getInliningInfo(file, startPosition, tryWithReferenceToken, program) { if (!isIdentifier(token)) { return void 0; } - if (isInitializedVariable(parent2) && isVariableDeclarationInVariableStatement(parent2)) { + if (isInitializedVariable(parent2) && isVariableDeclarationInVariableStatement(parent2) && isIdentifier(parent2.name)) { if (((_a = checker.getMergedSymbol(parent2.symbol).declarations) == null ? void 0 : _a.length) !== 1) { return { error: getLocaleSpecificMessage(Diagnostics.Variables_with_multiple_declarations_cannot_be_inlined) }; } @@ -138198,7 +138413,7 @@ registerRefactor(refactorNameForMoveToFile, { if (host.fileExists(targetFile) && program.getSourceFile(targetFile) === void 0) { return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_statements_to_the_selected_file)); } - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context, context.file, interactiveRefactorArguments.targetFile, program, statements, t, context.host, context.preferences)); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context, context.file, interactiveRefactorArguments.targetFile, context.program, statements, t, context.host, context.preferences)); return { edits, renameFilename: void 0, renameLocation: void 0 }; } return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_to_file_selected_file_is_invalid)); @@ -138247,7 +138462,7 @@ function getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, chang const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax); if (typeof targetFile !== "string") { if (targetFile.statements.length > 0) { - changes.insertNodesAfter(targetFile, targetFile.statements[targetFile.statements.length - 1], body); + moveStatementsToTargetFile(changes, program, body, targetFile, toMove); } else { changes.insertNodesAtEndOfFile( targetFile, @@ -138268,7 +138483,7 @@ function getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, chang } } if (importAdder) { - importAdder.writeFixes(changes); + importAdder.writeFixes(changes, quotePreference); } if (imports.length && body.length) { return [ @@ -138834,25 +139049,25 @@ function getRangeToMove(context) { const { file } = context; const range = createTextRangeFromSpan(getRefactorContextSpan(context)); const { statements } = file; - const startNodeIndex = findIndex(statements, (s) => s.end > range.pos); + let startNodeIndex = findIndex(statements, (s) => s.end > range.pos); if (startNodeIndex === -1) return void 0; const startStatement = statements[startNodeIndex]; - if (isNamedDeclaration(startStatement) && startStatement.name && rangeContainsRange(startStatement.name, range)) { - return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; - } const overloadRangeToMove = getOverloadRangeToMove(file, startStatement); if (overloadRangeToMove) { - return overloadRangeToMove; + startNodeIndex = overloadRangeToMove.start; + } + let endNodeIndex = findIndex(statements, (s) => s.end >= range.end, startNodeIndex); + if (endNodeIndex !== -1 && range.end <= statements[endNodeIndex].getStart()) { + endNodeIndex--; + } + const endingOverloadRangeToMove = getOverloadRangeToMove(file, statements[endNodeIndex]); + if (endingOverloadRangeToMove) { + endNodeIndex = endingOverloadRangeToMove.end; } - if (range.pos > startStatement.getStart(file)) - return void 0; - const afterEndNodeIndex = findIndex(statements, (s) => s.end > range.end, startNodeIndex); - if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) - return void 0; return { - toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), - afterLast: afterEndNodeIndex === -1 ? void 0 : statements[afterEndNodeIndex] + toMove: statements.slice(startNodeIndex, endNodeIndex === -1 ? statements.length : endNodeIndex + 1), + afterLast: endNodeIndex === -1 ? void 0 : statements[endNodeIndex + 1] }; } function getStatementsToMove(context) { @@ -139040,16 +139255,79 @@ function isNonVariableTopLevelDeclaration(node) { return false; } } +function moveStatementsToTargetFile(changes, program, statements, targetFile, toMove) { + var _a; + const removedExports = /* @__PURE__ */ new Set(); + const targetExports = (_a = targetFile.symbol) == null ? void 0 : _a.exports; + if (targetExports) { + const checker = program.getTypeChecker(); + const targetToSourceExports = /* @__PURE__ */ new Map(); + for (const node of toMove.all) { + if (isTopLevelDeclarationStatement(node) && hasSyntacticModifier(node, 1 /* Export */)) { + forEachTopLevelDeclaration(node, (declaration) => { + var _a2; + const targetDeclarations = canHaveSymbol(declaration) ? (_a2 = targetExports.get(declaration.symbol.escapedName)) == null ? void 0 : _a2.declarations : void 0; + const exportDeclaration = firstDefined(targetDeclarations, (d) => isExportDeclaration(d) ? d : isExportSpecifier(d) ? tryCast(d.parent.parent, isExportDeclaration) : void 0); + if (exportDeclaration && exportDeclaration.moduleSpecifier) { + targetToSourceExports.set( + exportDeclaration, + (targetToSourceExports.get(exportDeclaration) || /* @__PURE__ */ new Set()).add(declaration) + ); + } + }); + } + } + for (const [exportDeclaration, topLevelDeclarations] of arrayFrom(targetToSourceExports)) { + if (exportDeclaration.exportClause && isNamedExports(exportDeclaration.exportClause) && length(exportDeclaration.exportClause.elements)) { + const elements = exportDeclaration.exportClause.elements; + const updatedElements = filter(elements, (elem) => find(skipAlias(elem.symbol, checker).declarations, (d) => isTopLevelDeclaration(d) && topLevelDeclarations.has(d)) === void 0); + if (length(updatedElements) === 0) { + changes.deleteNode(targetFile, exportDeclaration); + removedExports.add(exportDeclaration); + continue; + } + if (length(updatedElements) < length(elements)) { + changes.replaceNode( + targetFile, + exportDeclaration, + factory.updateExportDeclaration( + exportDeclaration, + exportDeclaration.modifiers, + exportDeclaration.isTypeOnly, + factory.updateNamedExports(exportDeclaration.exportClause, factory.createNodeArray(updatedElements, elements.hasTrailingComma)), + exportDeclaration.moduleSpecifier, + exportDeclaration.assertClause + ) + ); + } + } + } + } + const lastReExport = findLast(targetFile.statements, (n) => isExportDeclaration(n) && !!n.moduleSpecifier && !removedExports.has(n)); + if (lastReExport) { + changes.insertNodesBefore( + targetFile, + lastReExport, + statements, + /*blankLineBetween*/ + true + ); + } else { + changes.insertNodesAfter(targetFile, targetFile.statements[targetFile.statements.length - 1], statements); + } +} function getOverloadRangeToMove(sourceFile, statement) { if (isFunctionLikeDeclaration(statement)) { const declarations = statement.symbol.declarations; if (declarations === void 0 || length(declarations) <= 1 || !contains(declarations, statement)) { return void 0; } + const firstDecl = declarations[0]; const lastDecl = declarations[length(declarations) - 1]; const statementsToMove = mapDefined(declarations, (d) => getSourceFileOfNode(d) === sourceFile && isStatement(d) ? d : void 0); - const end = findLastIndex(sourceFile.statements, (s) => s.end > lastDecl.end); - return { toMove: statementsToMove, afterLast: end >= 0 ? sourceFile.statements[end] : void 0 }; + const end = findIndex(sourceFile.statements, (s) => s.end >= lastDecl.end); + const start2 = findIndex(sourceFile.statements, (s) => s.end >= firstDecl.end); + return { toMove: statementsToMove, start: start2, end }; } return void 0; } @@ -143505,10 +143783,10 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h host.log(message); } } - const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const sourceMapper = getSourceMapper({ - useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2, getCurrentDirectory: () => currentDirectory, getProgram, fileExists: maybeBind(host, host.fileExists), @@ -143556,7 +143834,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h getSourceFileByPath: getOrCreateSourceFileByPath, getCancellationToken: () => cancellationToken, getCanonicalFileName, - useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2, getNewLine: () => getNewLineCharacter(newSettings), getDefaultLibFileName: (options2) => host.getDefaultLibFileName(options2), writeFile: noop, @@ -143600,9 +143878,12 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h compilerHost.getSourceFile = getSourceFileWithCache; (_c = host.setCompilerHost) == null ? void 0 : _c.call(host, compilerHost); const parseConfigHost = { - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, fileExists: (fileName) => compilerHost.fileExists(fileName), readFile: (fileName) => compilerHost.readFile(fileName), + directoryExists: (f) => compilerHost.directoryExists(f), + getDirectories: (f) => compilerHost.getDirectories(f), + realpath: compilerHost.realpath, readDirectory: (...args) => compilerHost.readDirectory(...args), trace: compilerHost.trace, getCurrentDirectory: compilerHost.getCurrentDirectory, @@ -144475,7 +144756,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h } return result; function escapeRegExp(str) { - return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); + return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&"); } function getTodoCommentsRegExp() { const singleLineCommentStart = /(?:\/\/+\s*)/.source; @@ -146698,7 +146979,7 @@ __export(ts_codefix_exports, { getFixes: () => getFixes, getImportCompletionAction: () => getImportCompletionAction, getImportKind: () => getImportKind, - getJSDocTypedefNode: () => getJSDocTypedefNode, + getJSDocTypedefNodes: () => getJSDocTypedefNodes, getNoopSymbolTrackerWithResolver: () => getNoopSymbolTrackerWithResolver, getPromoteTypeOnlyCompletionAction: () => getPromoteTypeOnlyCompletionAction, getSupportedErrorCodes: () => getSupportedErrorCodes, @@ -149420,13 +149701,14 @@ registerCodeFix({ fixIds: [fixId14], errorCodes: errorCodes15, getCodeActions(context) { + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); const node = getTokenAtPosition( context.sourceFile, context.span.start ); if (!node) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, node, context.sourceFile)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, node, context.sourceFile, newLineCharacter)); if (changes.length > 0) { return [ createCodeFixAction( @@ -149439,29 +149721,72 @@ registerCodeFix({ ]; } }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes15, (changes, diag2) => { - const node = getTokenAtPosition(diag2.file, diag2.start); - if (node) - doChange12(changes, node, diag2.file); - }) + getAllCodeActions: (context) => codeFixAll( + context, + errorCodes15, + (changes, diag2) => { + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); + const node = getTokenAtPosition(diag2.file, diag2.start); + const fixAll = true; + if (node) + doChange12(changes, node, diag2.file, newLineCharacter, fixAll); + } + ) }); -function doChange12(changes, node, sourceFile) { - if (isJSDocTypedefTag(node)) { - fixSingleTypeDef(changes, node, sourceFile); - } -} -function fixSingleTypeDef(changes, typeDefNode, sourceFile) { - if (!typeDefNode) +function doChange12(changes, node, sourceFile, newLine, fixAll = false) { + if (!isJSDocTypedefTag(node)) return; - const declaration = createDeclaration(typeDefNode); + const declaration = createDeclaration(node); if (!declaration) return; - const comment = typeDefNode.parent; - changes.replaceNode( - sourceFile, - comment, - declaration + const commentNode = node.parent; + const { leftSibling, rightSibling } = getLeftAndRightSiblings(node); + let pos = commentNode.getStart(); + let prefix = ""; + if (!leftSibling && commentNode.comment) { + pos = findEndOfTextBetween(commentNode, commentNode.getStart(), node.getStart()); + prefix = `${newLine} */${newLine}`; + } + if (leftSibling) { + if (fixAll && isJSDocTypedefTag(leftSibling)) { + pos = node.getStart(); + prefix = ""; + } else { + pos = findEndOfTextBetween(commentNode, leftSibling.getStart(), node.getStart()); + prefix = `${newLine} */${newLine}`; + } + } + let end = commentNode.getEnd(); + let suffix = ""; + if (rightSibling) { + if (fixAll && isJSDocTypedefTag(rightSibling)) { + end = rightSibling.getStart(); + suffix = `${newLine}${newLine}`; + } else { + end = rightSibling.getStart(); + suffix = `${newLine}/**${newLine} * `; + } + } + changes.replaceRange(sourceFile, { pos, end }, declaration, { prefix, suffix }); +} +function getLeftAndRightSiblings(typedefNode) { + const commentNode = typedefNode.parent; + const maxChildIndex = commentNode.getChildCount() - 1; + const currentNodeIndex = commentNode.getChildren().findIndex( + (n) => n.getStart() === typedefNode.getStart() && n.getEnd() === typedefNode.getEnd() ); + const leftSibling = currentNodeIndex > 0 ? commentNode.getChildAt(currentNodeIndex - 1) : void 0; + const rightSibling = currentNodeIndex < maxChildIndex ? commentNode.getChildAt(currentNodeIndex + 1) : void 0; + return { leftSibling, rightSibling }; +} +function findEndOfTextBetween(jsDocComment, from, to) { + const comment = jsDocComment.getText().substring(from - jsDocComment.getStart(), to - jsDocComment.getStart()); + for (let i = comment.length; i > 0; i--) { + if (!/[*/\s]/g.test(comment.substring(i - 1, i))) { + return from + i; + } + } + return to; } function createDeclaration(tag) { var _a; @@ -149482,7 +149807,7 @@ function createInterfaceForTypeLiteral(typeName, typeLiteral) { const propertySignatures = createSignatureFromTypeLiteral(typeLiteral); if (!some(propertySignatures)) return; - const interfaceDeclaration = factory.createInterfaceDeclaration( + return factory.createInterfaceDeclaration( /*modifiers*/ void 0, typeName, @@ -149492,13 +149817,12 @@ function createInterfaceForTypeLiteral(typeName, typeLiteral) { void 0, propertySignatures ); - return interfaceDeclaration; } function createTypeAliasForTypeExpression(typeName, typeExpression) { const typeReference = getSynthesizedDeepClone(typeExpression.type); if (!typeReference) return; - const declaration = factory.createTypeAliasDeclaration( + return factory.createTypeAliasDeclaration( /*modifiers*/ void 0, factory.createIdentifier(typeName), @@ -149506,7 +149830,6 @@ function createTypeAliasForTypeExpression(typeName, typeExpression) { void 0, typeReference ); - return declaration; } function createSignatureFromTypeLiteral(typeLiteral) { const propertyTags = typeLiteral.jsDocPropertyTags; @@ -149526,30 +149849,28 @@ function createSignatureFromTypeLiteral(typeLiteral) { } if (typeReference && name) { const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0; - const prop = factory.createPropertySignature( + return factory.createPropertySignature( /*modifiers*/ void 0, name, questionToken, typeReference ); - return prop; } }; - const props = mapDefined(propertyTags, getSignature); - return props; + return mapDefined(propertyTags, getSignature); } function getPropertyName(tag) { return tag.name.kind === 80 /* Identifier */ ? tag.name.text : tag.name.right.text; } -function getJSDocTypedefNode(node) { +function getJSDocTypedefNodes(node) { if (hasJSDocNodes(node)) { - return forEach(node.jsDoc, (node2) => { + return flatMap(node.jsDoc, (doc) => { var _a; - return (_a = node2.tags) == null ? void 0 : _a.find(isJSDocTypedefTag); + return (_a = doc.tags) == null ? void 0 : _a.filter((tag) => isJSDocTypedefTag(tag)); }); } - return void 0; + return []; } // src/services/codefixes/convertLiteralTypeToMappedType.ts @@ -149897,8 +150218,13 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre return `${topLevelTypeOnly ? 1 : 0}|${moduleSpecifier}`; } } - function writeFixes(changeTracker) { - const quotePreference = getQuotePreference(sourceFile, preferences); + function writeFixes(changeTracker, oldFileQuotePreference) { + let quotePreference; + if (sourceFile.imports.length === 0 && oldFileQuotePreference !== void 0) { + quotePreference = oldFileQuotePreference; + } else { + quotePreference = getQuotePreference(sourceFile, preferences); + } for (const fix of addToNamespace) { addNamespaceQualifier(changeTracker, sourceFile, fix); } @@ -150201,6 +150527,10 @@ function shouldUseRequire(sourceFile, program) { if (compilerOptions.configFile) { return getEmitModuleKind(compilerOptions) < 5 /* ES2015 */; } + if (sourceFile.impliedNodeFormat === 1 /* CommonJS */) + return true; + if (sourceFile.impliedNodeFormat === 99 /* ESNext */) + return false; for (const otherFile of program.getSourceFiles()) { if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) continue; @@ -150673,6 +151003,14 @@ function promoteFromTypeOnly(changes, aliasDeclaration, compilerOptions, sourceF } function promoteImportClause(importClause) { changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(importClause, sourceFile)); + if (!compilerOptions.allowImportingTsExtensions) { + const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(importClause.parent); + const resolvedModule = moduleSpecifier && getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation(sourceFile, moduleSpecifier)); + if (resolvedModule == null ? void 0 : resolvedModule.resolvedUsingTsExtension) { + const changedExtension = changeAnyExtension(moduleSpecifier.text, getOutputExtension(moduleSpecifier.text, compilerOptions)); + changes.replaceNode(sourceFile, moduleSpecifier, factory.createStringLiteral(changedExtension)); + } + } if (convertExistingToTypeOnly) { const namedImports = tryCast(importClause.namedBindings, isNamedImports); if (namedImports && namedImports.elements.length > 1) { @@ -151790,6 +152128,8 @@ function getInfo9(checker, sourceFile, position, errorCode) { if (!declaration || !isCallExpression(declaration.parent) || !declaration.body) return void 0; const pos = declaration.parent.arguments.indexOf(declaration); + if (pos === -1) + return void 0; const type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos); if (!type) return void 0; @@ -152790,7 +153130,7 @@ function doChange22(changes, sourceFile, arg, expression) { ); } function getSuggestion(messageText) { - const [_, suggestion] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/\'(.*)\'/) || []; + const [_, suggestion] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/'(.*)'/) || []; return suggestion; } @@ -154957,15 +155297,11 @@ var PreserveOptionalFlags = /* @__PURE__ */ ((PreserveOptionalFlags2) => { })(PreserveOptionalFlags || {}); function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement, body, preserveOptional = 3 /* All */, isAmbient = false) { const declarations = symbol.getDeclarations(); - const declaration = declarations == null ? void 0 : declarations[0]; + const declaration = firstOrUndefined(declarations); const checker = context.program.getTypeChecker(); const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); const kind = (declaration == null ? void 0 : declaration.kind) ?? 171 /* PropertySignature */; - const declarationName = getSynthesizedDeepClone( - getNameOfDeclaration(declaration), - /*includeTrivia*/ - false - ); + const declarationName = createDeclarationName(symbol, declaration); const effectiveModifierFlags = declaration ? getEffectiveModifierFlags(declaration) : 0 /* None */; let modifierFlags = effectiveModifierFlags & 32 /* Static */; modifierFlags |= effectiveModifierFlags & 4 /* Public */ ? 4 /* Public */ : effectiveModifierFlags & 16 /* Protected */ ? 16 /* Protected */ : 0 /* None */; @@ -155116,6 +155452,19 @@ function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, con false ); } + function createDeclarationName(symbol2, declaration2) { + if (getCheckFlags(symbol2) & 262144 /* Mapped */) { + const nameType = symbol2.links.nameType; + if (nameType && isTypeUsableAsPropertyName(nameType)) { + return factory.createIdentifier(unescapeLeadingUnderscores(getPropertyNameFromType(nameType))); + } + } + return getSynthesizedDeepClone( + getNameOfDeclaration(declaration2), + /*includeTrivia*/ + false + ); + } } function createSignatureDeclarationFromSignature(kind, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder) { const program = context.program; @@ -157650,6 +157999,13 @@ function createCompletionEntry(symbol, sortText, replacementToken, contextToken, data = originToCompletionEntryData(origin); hasAction = !importStatementCompletion; } + const parentNamedImportOrExport = findAncestor(location, isNamedImportsOrExports); + if ((parentNamedImportOrExport == null ? void 0 : parentNamedImportOrExport.kind) === 275 /* NamedImports */) { + const possibleToken = stringToToken(name); + if (parentNamedImportOrExport && possibleToken && (possibleToken === 135 /* AwaitKeyword */ || isNonContextualKeyword(possibleToken))) { + insertText = `${name} as ${name}_`; + } + } return { name, kind: ts_SymbolDisplay_exports.getSymbolKind(typeChecker, symbol, location), @@ -158430,7 +158786,7 @@ function createCompletionDetails(name, kindModifiers, kind, displayParts, docume } function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source, cancellationToken) { if (data == null ? void 0 : data.moduleSpecifier) { - if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken).replacementSpan) { + if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken, sourceFile).replacementSpan) { return { codeActions: void 0, sourceDisplay: [textPart(data.moduleSpecifier)] }; } } @@ -158606,7 +158962,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, return { kind: 1 /* JsDocTagName */ }; } else { const lineStart = getLineStartPositionForPosition(position, sourceFile); - if (!/[^\*|\s(/)]/.test(sourceFile.text.substring(lineStart, position))) { + if (!/[^*|\s(/)]/.test(sourceFile.text.substring(lineStart, position))) { return { kind: 2 /* JsDocTag */ }; } } @@ -158652,7 +159008,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, let isNewIdentifierLocation = false; let flags = 0 /* None */; if (contextToken) { - const importStatementCompletionInfo = getImportStatementCompletionInfo(contextToken); + const importStatementCompletionInfo = getImportStatementCompletionInfo(contextToken, sourceFile); if (importStatementCompletionInfo.keywordCompletion) { if (importStatementCompletionInfo.isKeywordOnlyCompletion) { return { @@ -158905,24 +159261,34 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, } } } - if (!isTypeLocation) { + if (!isTypeLocation || isInTypeQuery(node)) { typeChecker.tryGetThisTypeAt( node, /*includeGlobalThis*/ false ); let type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); - let insertQuestionDot = false; - if (type.isNullableType()) { - const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false; - if (canCorrectToQuestionDot || isRightOfQuestionDot) { - type = type.getNonNullableType(); - if (canCorrectToQuestionDot) { - insertQuestionDot = true; + if (!isTypeLocation) { + let insertQuestionDot = false; + if (type.isNullableType()) { + const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } } } + addTypeProperties(type, !!(node.flags & 65536 /* AwaitContext */), insertQuestionDot); + } else { + addTypeProperties( + type.getNonNullableType(), + /*insertAwait*/ + false, + /*insertQuestionDot*/ + false + ); } - addTypeProperties(type, !!(node.flags & 65536 /* AwaitContext */), insertQuestionDot); } } function addTypeProperties(type, insertAwait, insertQuestionDot) { @@ -158968,7 +159334,8 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, const leftMostName = getLeftMostName(computedPropertyName.expression); const nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); const firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); - if (firstAccessibleSymbol && addToSeen(seenPropertySymbols, getSymbolId(firstAccessibleSymbol))) { + const firstAccessibleSymbolId = firstAccessibleSymbol && getSymbolId(firstAccessibleSymbol); + if (firstAccessibleSymbolId && addToSeen(seenPropertySymbols, firstAccessibleSymbolId)) { const index = symbols.length; symbols.push(firstAccessibleSymbol); const moduleSymbol = firstAccessibleSymbol.parent; @@ -158998,6 +159365,9 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, } } } else if (preferences.includeCompletionsWithInsertText) { + if (firstAccessibleSymbolId && seenPropertySymbols.has(firstAccessibleSymbolId)) { + return; + } addSymbolOriginInfo(symbol); addSymbolSortInfo(symbol); symbols.push(symbol); @@ -160140,6 +160510,11 @@ function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken return cls; } break; + case 81 /* PrivateIdentifier */: + if (tryCast(location.parent, isPropertyDeclaration)) { + return findAncestor(location, isClassLike); + } + break; case 80 /* Identifier */: { const originalKeywordKind = identifierToKeywordKind(location); if (originalKeywordKind) { @@ -160296,7 +160671,7 @@ function tryGetObjectLiteralContextualType(node, typeChecker) { } return void 0; } -function getImportStatementCompletionInfo(contextToken) { +function getImportStatementCompletionInfo(contextToken, sourceFile) { var _a, _b, _c; let keywordCompletion; let isKeywordOnlyCompletion = false; @@ -160312,6 +160687,12 @@ function getImportStatementCompletionInfo(contextToken) { function getCandidate() { const parent2 = contextToken.parent; if (isImportEqualsDeclaration(parent2)) { + const lastToken = parent2.getLastToken(sourceFile); + if (isIdentifier(contextToken) && lastToken !== contextToken) { + keywordCompletion = 161 /* FromKeyword */; + isKeywordOnlyCompletion = true; + return void 0; + } keywordCompletion = contextToken.kind === 156 /* TypeKeyword */ ? void 0 : 156 /* TypeKeyword */; return isModuleSpecifierMissingOrEmpty(parent2.moduleReference) ? parent2 : void 0; } @@ -160813,7 +161194,7 @@ function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, c extensionOptions, host, /*moduleSpecifierIsRelative*/ - false, + true, scriptPath ).values()); } @@ -161145,16 +161526,18 @@ function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensio const fragmentDirectory = fragmentHasPath ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0; const expandedPrefixDirectory = fragmentHasPath ? combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; const normalizedSuffix = normalizePath(parsed.suffix); + const declarationExtension = normalizedSuffix && getDeclarationEmitExtensionForPath("_" + normalizedSuffix); + const matchingSuffixes = declarationExtension ? [changeExtension(normalizedSuffix, declarationExtension), normalizedSuffix] : [normalizedSuffix]; const baseDirectory = normalizePath(combinePaths(packageDirectory, expandedPrefixDirectory)); const completePrefix = fragmentHasPath ? baseDirectory : ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - const includeGlob = normalizedSuffix ? "**/*" + normalizedSuffix : "./*"; + const includeGlobs = normalizedSuffix ? matchingSuffixes.map((suffix) => "**/*" + suffix) : ["./*"]; const matches = mapDefined(tryReadDirectory( host, baseDirectory, extensionOptions.extensionsToSearch, /*exclude*/ void 0, - [includeGlob] + includeGlobs ), (match) => { const trimmedWithPattern = trimPrefixAndSuffix(match); if (trimmedWithPattern) { @@ -161168,8 +161551,10 @@ function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensio const directories = normalizedSuffix ? emptyArray : mapDefined(tryGetDirectories(host, baseDirectory), (dir) => dir === "node_modules" ? void 0 : directoryResult(dir)); return [...matches, ...directories]; function trimPrefixAndSuffix(path) { - const inner = withoutStartAndEnd(normalizePath(path), completePrefix, normalizedSuffix); - return inner === void 0 ? void 0 : removeLeadingDirectorySeparator(inner); + return firstDefined(matchingSuffixes, (suffix) => { + const inner = withoutStartAndEnd(normalizePath(path), completePrefix, suffix); + return inner === void 0 ? void 0 : removeLeadingDirectorySeparator(inner); + }); } } function withoutStartAndEnd(s, start2, end) { @@ -164312,7 +164697,7 @@ __export(ts_InlayHints_exports, { }); // src/services/inlayHints.ts -var maxHintsLength = 30; +var maxTypeHintLength = 30; var leadingParameterNameCommentRegexFactory = (name) => { return new RegExp(`^\\s?/\\*\\*?\\s?${name}\\s?\\*\\/\\s?$`); }; @@ -164322,6 +164707,9 @@ function shouldShowParameterNameHints(preferences) { function shouldShowLiteralParameterNameHintsOnly(preferences) { return preferences.includeInlayParameterNameHints === "literals"; } +function shouldUseInteractiveInlayHints(preferences) { + return preferences.interactiveInlayHints === true; +} function provideInlayHints(context) { const { file, program, span, cancellationToken, preferences } = context; const sourceFileText = file.text; @@ -164372,17 +164760,26 @@ function provideInlayHints(context) { function isSignatureSupportingReturnAnnotation(node) { return isArrowFunction(node) || isFunctionExpression(node) || isFunctionDeclaration(node) || isMethodDeclaration(node) || isGetAccessorDeclaration(node); } - function addParameterHints(text, position, isFirstVariadicArgument) { + function addParameterHints(text, parameter, position, isFirstVariadicArgument, sourceFile) { + let hintText = `${isFirstVariadicArgument ? "..." : ""}${text}`; + let displayParts; + if (shouldUseInteractiveInlayHints(preferences)) { + displayParts = [getNodeDisplayPart(hintText, parameter, sourceFile), { text: ":" }]; + hintText = ""; + } else { + hintText += ":"; + } result.push({ - text: `${isFirstVariadicArgument ? "..." : ""}${truncation(text, maxHintsLength)}:`, + text: hintText, position, kind: "Parameter" /* Parameter */, - whitespaceAfter: true + whitespaceAfter: true, + displayParts }); } function addTypeHints(text, position) { result.push({ - text: `: ${truncation(text, maxHintsLength)}`, + text: `: ${text.length > maxTypeHintLength ? text.substr(0, maxTypeHintLength - "...".length) + "..." : text}`, position, kind: "Type" /* Type */, whitespaceBefore: true @@ -164390,7 +164787,7 @@ function provideInlayHints(context) { } function addEnumMemberValueHints(text, position) { result.push({ - text: `= ${truncation(text, maxHintsLength)}`, + text: `= ${text}`, position, kind: "Enum" /* Enum */, whitespaceBefore: true @@ -164440,6 +164837,7 @@ function provideInlayHints(context) { return; } let signatureParamPos = 0; + const sourceFile = shouldUseInteractiveInlayHints(preferences) ? expr.getSourceFile() : void 0; for (const originalArg of args) { const arg = skipParentheses(originalArg); if (shouldShowLiteralParameterNameHintsOnly(preferences) && !isHintableLiteral(arg)) { @@ -164460,10 +164858,10 @@ function provideInlayHints(context) { } } } - const identifierNameInfo = checker.getParameterIdentifierNameAtPosition(signature, signatureParamPos); + const identifierInfo = checker.getParameterIdentifierInfoAtPosition(signature, signatureParamPos); signatureParamPos = signatureParamPos + (spreadArgs || 1); - if (identifierNameInfo) { - const [parameterName, isFirstVariadicArgument] = identifierNameInfo; + if (identifierInfo) { + const { parameter, parameterName, isRestParameter: isFirstVariadicArgument } = identifierInfo; const isParameterNameNotSameAsArgument = preferences.includeInlayParameterNameHintsWhenArgumentMatchesName || !identifierOrAccessExpressionPostfixMatchesParameterName(arg, parameterName); if (!isParameterNameNotSameAsArgument && !isFirstVariadicArgument) { continue; @@ -164472,7 +164870,7 @@ function provideInlayHints(context) { if (leadingCommentsContainsParameterName(arg, name)) { continue; } - addParameterHints(name, originalArg.getStart(), isFirstVariadicArgument); + addParameterHints(name, parameter, originalArg.getStart(), isFirstVariadicArgument, sourceFile); } } } @@ -164578,12 +164976,6 @@ function provideInlayHints(context) { } return printTypeInSingleLine(signatureParamType); } - function truncation(text, maxLength2) { - if (text.length > maxLength2) { - return text.substr(0, maxLength2 - "...".length) + "..."; - } - return text; - } function printTypeInSingleLine(type) { const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; const printer = createPrinterWithRemoveComments(); @@ -164614,6 +165006,13 @@ function provideInlayHints(context) { } return true; } + function getNodeDisplayPart(text, node, sourceFile) { + return { + text, + span: createTextSpanFromNode(node, sourceFile), + file: sourceFile.fileName + }; + } } // src/services/_namespaces/ts.JsDoc.ts @@ -166962,6 +167361,10 @@ function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeCheck return "parameter" /* parameterElement */; } else if (symbol.valueDeclaration && isVarConst(symbol.valueDeclaration)) { return "const" /* constElement */; + } else if (symbol.valueDeclaration && isVarUsing(symbol.valueDeclaration)) { + return "using" /* variableUsingElement */; + } else if (symbol.valueDeclaration && isVarAwaitUsing(symbol.valueDeclaration)) { + return "await using" /* variableAwaitUsingElement */; } else if (forEach(symbol.declarations, isLet)) { return "let" /* letElement */; } @@ -167029,7 +167432,7 @@ function getSymbolModifiers(typeChecker, symbol) { } return modifiers.size > 0 ? arrayFrom(modifiers.values()).join(",") : "" /* none */; } -function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning = getMeaningFromLocation(location), alias) { +function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, symbol, sourceFile, enclosingDeclaration, location, type, semanticMeaning, alias) { var _a; const displayParts = []; let documentation = []; @@ -167038,7 +167441,6 @@ function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, so let symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; let hasAddedSymbolInfo = false; const isThisExpression = location.kind === 110 /* ThisKeyword */ && isInExpressionContext(location) || isThisInTypeQuery(location); - let type; let documentationFromAlias; let tagsFromAlias; let hasMultipleSignatures = false; @@ -167067,7 +167469,7 @@ function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, so } } let signature; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + type ?? (type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location)); if (location.parent && location.parent.kind === 211 /* PropertyAccessExpression */) { const right = location.parent.name; if (right === location || right && right.getFullWidth() === 0) { @@ -167282,12 +167684,13 @@ function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, so if (declarationName && !hasAddedSymbolInfo) { const isExternalModuleDeclaration = isModuleWithStringLiteralName(resolvedNode) && hasSyntacticModifier(resolvedNode, 2 /* Ambient */); const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; - const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind( + const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKindWorker( typeChecker, resolvedSymbol, getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, + type, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol ); @@ -167355,7 +167758,7 @@ function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, so } else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); } - if (symbolKind === "property" /* memberVariableElement */ || symbolKind === "accessor" /* memberAccessorVariableElement */ || symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */ || symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || symbolKind === "index" /* indexSignatureElement */ || isThisExpression) { + if (symbolKind === "property" /* memberVariableElement */ || symbolKind === "accessor" /* memberAccessorVariableElement */ || symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */ || symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || symbolKind === "index" /* indexSignatureElement */ || symbolKind === "using" /* variableUsingElement */ || symbolKind === "await using" /* variableAwaitUsingElement */ || isThisExpression) { displayParts.push(punctuationPart(59 /* ColonToken */)); displayParts.push(spacePart()); if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */ && symbolKind !== "index" /* indexSignatureElement */) { @@ -167505,6 +167908,8 @@ function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, so case "let" /* letElement */: case "const" /* constElement */: case "constructor" /* constructorImplementationElement */: + case "using" /* variableUsingElement */: + case "await using" /* variableAwaitUsingElement */: displayParts.push(textOrKeywordPart(symbolKind2)); return; default: @@ -167540,6 +167945,19 @@ function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, so addRange(displayParts, typeParameterParts); } } +function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning = getMeaningFromLocation(location), alias) { + return getSymbolDisplayPartsDocumentationAndSymbolKindWorker( + typeChecker, + symbol, + sourceFile, + enclosingDeclaration, + location, + /*type*/ + void 0, + semanticMeaning, + alias + ); +} function isLocalVariableOrFunction(symbol) { if (symbol.parent) { return false; @@ -167889,6 +168307,9 @@ var ChangeTracker = class _ChangeTracker { insertNodeBefore(sourceFile, before, newNode, blankLineBetween = false, options = {}) { this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNode, this.getOptionsForInsertNodeBefore(before, newNode, blankLineBetween)); } + insertNodesBefore(sourceFile, before, newNodes, blankLineBetween = false, options = {}) { + this.insertNodesAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNodes, this.getOptionsForInsertNodeBefore(before, first(newNodes), blankLineBetween)); + } insertModifierAt(sourceFile, pos, modifier, options = {}) { this.insertNodeAt(sourceFile, pos, factory.createToken(modifier), options); } @@ -172327,6 +172748,7 @@ __export(ts_exports2, { getEmitModuleKind: () => getEmitModuleKind, getEmitModuleResolutionKind: () => getEmitModuleResolutionKind, getEmitScriptTarget: () => getEmitScriptTarget, + getEmitStandardClassFields: () => getEmitStandardClassFields, getEnclosingBlockScopeContainer: () => getEnclosingBlockScopeContainer, getEnclosingContainer: () => getEnclosingContainer, getEncodedSemanticClassifications: () => getEncodedSemanticClassifications, @@ -172546,6 +172968,7 @@ __export(ts_exports2, { getPropertyAssignmentAliasLikeExpression: () => getPropertyAssignmentAliasLikeExpression, getPropertyNameForPropertyNameNode: () => getPropertyNameForPropertyNameNode, getPropertyNameForUniqueESSymbol: () => getPropertyNameForUniqueESSymbol, + getPropertyNameFromType: () => getPropertyNameFromType, getPropertyNameOfBindingOrAssignmentElement: () => getPropertyNameOfBindingOrAssignmentElement, getPropertySymbolFromBindingElement: () => getPropertySymbolFromBindingElement, getPropertySymbolsFromContextualType: () => getPropertySymbolsFromContextualType, @@ -173001,6 +173424,7 @@ __export(ts_exports2, { isInString: () => isInString, isInTemplateString: () => isInTemplateString, isInTopLevelContext: () => isInTopLevelContext, + isInTypeQuery: () => isInTypeQuery, isIncrementalCompilation: () => isIncrementalCompilation, isIndexSignatureDeclaration: () => isIndexSignatureDeclaration, isIndexedAccessTypeNode: () => isIndexedAccessTypeNode, @@ -173378,6 +173802,7 @@ __export(ts_exports2, { isTypeQueryNode: () => isTypeQueryNode, isTypeReferenceNode: () => isTypeReferenceNode, isTypeReferenceType: () => isTypeReferenceType, + isTypeUsableAsPropertyName: () => isTypeUsableAsPropertyName, isUMDExportSymbol: () => isUMDExportSymbol, isUnaryExpression: () => isUnaryExpression, isUnaryExpressionWithWrite: () => isUnaryExpressionWithWrite, @@ -177058,7 +177483,7 @@ var Project3 = class _Project { return this.projectService.includePackageJsonAutoImports(); } /** @internal */ - getModuleResolutionHostForAutoImportProvider() { + getHostForAutoImportProvider() { var _a, _b; if (this.program) { return { @@ -177069,7 +177494,8 @@ var Project3 = class _Project { readFile: this.projectService.host.readFile.bind(this.projectService.host), getDirectories: this.projectService.host.getDirectories.bind(this.projectService.host), trace: (_b = this.projectService.host.trace) == null ? void 0 : _b.bind(this.projectService.host), - useCaseSensitiveFileNames: this.program.useCaseSensitiveFileNames() + useCaseSensitiveFileNames: this.program.useCaseSensitiveFileNames(), + readDirectory: this.projectService.host.readDirectory.bind(this.projectService.host) }; } return this.projectService.host; @@ -177097,7 +177523,7 @@ var Project3 = class _Project { if (dependencySelection) { (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "getPackageJsonAutoImportProvider"); const start2 = timestamp(); - this.autoImportProviderHost = AutoImportProviderProject.create(dependencySelection, this, this.getModuleResolutionHostForAutoImportProvider(), this.documentRegistry); + this.autoImportProviderHost = AutoImportProviderProject.create(dependencySelection, this, this.getHostForAutoImportProvider(), this.documentRegistry); if (this.autoImportProviderHost) { updateProjectIfDirty(this.autoImportProviderHost); this.sendPerformanceEvent("CreatePackageJsonAutoImportProvider", timestamp() - start2); @@ -177335,7 +177761,7 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec this.getParsedCommandLine = maybeBind(this.hostProject, this.hostProject.getParsedCommandLine); } /** @internal */ - static getRootFileNames(dependencySelection, hostProject, moduleResolutionHost, compilerOptions) { + static getRootFileNames(dependencySelection, hostProject, host, compilerOptions) { var _a, _b; if (!dependencySelection) { return emptyArray; @@ -177365,7 +177791,7 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec name, hostProject.currentDirectory, compilerOptions, - moduleResolutionHost, + host, program.getModuleResolutionCache() ); if (packageJson) { @@ -177382,7 +177808,7 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec `@types/${name}`, directory, compilerOptions, - moduleResolutionHost, + host, program.getModuleResolutionCache() ); if (typesPackageJson) { @@ -177422,12 +177848,12 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec const entrypoints = getEntrypointsFromPackageJsonInfo( packageJson, compilerOptions, - moduleResolutionHost, + host, program2.getModuleResolutionCache(), resolveJs ); if (entrypoints) { - const real = (_a2 = moduleResolutionHost.realpath) == null ? void 0 : _a2.call(moduleResolutionHost, packageJson.packageDirectory); + const real = (_a2 = host.realpath) == null ? void 0 : _a2.call(host, packageJson.packageDirectory); const isSymlink = real && real !== packageJson.packageDirectory; if (isSymlink) { symlinkCache.setSymlinkedDirectory(packageJson.packageDirectory, { @@ -177445,7 +177871,7 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec } } /** @internal */ - static create(dependencySelection, hostProject, moduleResolutionHost, documentRegistry) { + static create(dependencySelection, hostProject, host, documentRegistry) { if (dependencySelection === 0 /* Off */) { return void 0; } @@ -177453,7 +177879,7 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec ...hostProject.getCompilerOptions(), ...this.compilerOptionsOverrides }; - const rootNames = this.getRootFileNames(dependencySelection, hostProject, moduleResolutionHost, compilerOptions); + const rootNames = this.getRootFileNames(dependencySelection, hostProject, host, compilerOptions); if (!rootNames.length) { return void 0; } @@ -177472,7 +177898,7 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec rootFileNames = _AutoImportProviderProject.getRootFileNames( this.hostProject.includePackageJsonAutoImports(), this.hostProject, - this.hostProject.getModuleResolutionHostForAutoImportProvider(), + this.hostProject.getHostForAutoImportProvider(), this.getCompilationSettings() ); } @@ -177511,7 +177937,7 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec onPackageJsonChange() { throw new Error("package.json changes should be notified on an AutoImportProvider's host project"); } - getModuleResolutionHostForAutoImportProvider() { + getHostForAutoImportProvider() { throw new Error("AutoImportProviderProject cannot provide its own host; use `hostProject.getModuleResolutionHostForAutomImportProvider()` instead."); } getProjectReferences() { @@ -177868,7 +178294,7 @@ var indentStyle = new Map(Object.entries({ 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": { @@ -180770,7 +181196,7 @@ Dynamic files must always be opened with service's current directory or service } } if (!exclude) { - if (/^.+[\.-]min\.js$/.test(normalizedNames[i])) { + if (/^.+[.-]min\.js$/.test(normalizedNames[i])) { excludedFiles.push(normalizedNames[i]); } else { filesToKeep.push(proj.rootFiles[i]); @@ -181091,7 +181517,7 @@ Dynamic files must always be opened with service's current directory or service } }; /** Makes a filename safe to insert in a RegExp */ -_ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; +_ProjectService.filenameEscapeRegexp = /[-/\\^$*+?.()|[\]{}]/g; var ProjectService3 = _ProjectService; function createIncompleteCompletionsCache() { let info; @@ -183235,10 +183661,21 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const { file, project } = this.getFileAndProject(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); const hints = project.getLanguageService().provideInlayHints(file, args, this.getPreferences(file)); - return hints.map((hint) => ({ - ...hint, - position: scriptInfo.positionToLineOffset(hint.position) - })); + return hints.map((hint) => { + const { position, displayParts } = hint; + return { + ...hint, + position: scriptInfo.positionToLineOffset(position), + displayParts: displayParts == null ? void 0 : displayParts.map(({ text, span, file: file2 }) => ({ + text, + span: span && { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(span.start + span.length), + file: file2 + } + })) + }; + }); } setCompilerOptionsForInferredProjects(args) { this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath); @@ -186840,6 +187277,7 @@ start(initializeNodeSystem(), require("os").platform()); getEmitModuleKind, getEmitModuleResolutionKind, getEmitScriptTarget, + getEmitStandardClassFields, getEnclosingBlockScopeContainer, getEnclosingContainer, getEncodedSemanticClassifications, @@ -187059,6 +187497,7 @@ start(initializeNodeSystem(), require("os").platform()); getPropertyAssignmentAliasLikeExpression, getPropertyNameForPropertyNameNode, getPropertyNameForUniqueESSymbol, + getPropertyNameFromType, getPropertyNameOfBindingOrAssignmentElement, getPropertySymbolFromBindingElement, getPropertySymbolsFromContextualType, @@ -187514,6 +187953,7 @@ start(initializeNodeSystem(), require("os").platform()); isInString, isInTemplateString, isInTopLevelContext, + isInTypeQuery, isIncrementalCompilation, isIndexSignatureDeclaration, isIndexedAccessTypeNode, @@ -187891,6 +188331,7 @@ start(initializeNodeSystem(), require("os").platform()); isTypeQueryNode, isTypeReferenceNode, isTypeReferenceType, + isTypeUsableAsPropertyName, isUMDExportSymbol, isUnaryExpression, isUnaryExpressionWithWrite, diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 4b702907d6c69..4b9d52e470e33 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -2124,11 +2124,17 @@ declare namespace ts { arguments: InlayHintsRequestArgs; } interface InlayHintItem { + /** This property will be the empty string when displayParts is set. */ text: string; position: Location; kind: InlayHintKind; whitespaceBefore?: boolean; whitespaceAfter?: boolean; + displayParts?: InlayHintItemDisplayPart[]; + } + interface InlayHintItemDisplayPart { + text: string; + span?: FileSpan; } interface InlayHintsResponse extends Response { body?: InlayHintItem[]; @@ -2832,6 +2838,7 @@ declare namespace ts { readonly includeInlayPropertyDeclarationTypeHints?: boolean; readonly includeInlayFunctionLikeReturnTypeHints?: boolean; readonly includeInlayEnumMemberValueHints?: boolean; + readonly interactiveInlayHints?: boolean; readonly autoImportFileExcludePatterns?: string[]; /** * Indicates whether imports should be organized in a case-insensitive manner. @@ -3400,7 +3407,7 @@ declare namespace ts { markAsDirty(): void; getScriptFileNames(): string[]; getLanguageService(): never; - getModuleResolutionHostForAutoImportProvider(): never; + getHostForAutoImportProvider(): never; getProjectReferences(): readonly ts.ProjectReference[] | undefined; getTypeAcquisition(): TypeAcquisition; } @@ -5827,9 +5834,11 @@ declare namespace ts { }; }) | ExportDeclaration & { readonly isTypeOnly: true; + readonly moduleSpecifier: Expression; } | NamespaceExport & { readonly parent: ExportDeclaration & { readonly isTypeOnly: true; + readonly moduleSpecifier: Expression; }; }; type TypeOnlyAliasDeclaration = TypeOnlyImportDeclaration | TypeOnlyExportDeclaration; @@ -6274,7 +6283,7 @@ declare namespace ts { getSourceFileByPath(path: Path): SourceFile | undefined; getCurrentDirectory(): string; } - interface ParseConfigHost { + interface ParseConfigHost extends ModuleResolutionHost { useCaseSensitiveFileNames: boolean; readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[], depth?: number): readonly string[]; /** @@ -8400,6 +8409,7 @@ declare namespace ts { readonly includeInlayPropertyDeclarationTypeHints?: boolean; readonly includeInlayFunctionLikeReturnTypeHints?: boolean; readonly includeInlayEnumMemberValueHints?: boolean; + readonly interactiveInlayHints?: boolean; readonly allowRenameOfImportPath?: boolean; readonly autoImportFileExcludePatterns?: string[]; readonly organizeImportsIgnoreCase?: "auto" | boolean; @@ -10382,11 +10392,18 @@ declare namespace ts { Enum = "Enum" } interface InlayHint { + /** This property will be the empty string when displayParts is set. */ text: string; position: number; kind: InlayHintKind; whitespaceBefore?: boolean; whitespaceAfter?: boolean; + displayParts?: InlayHintDisplayPart[]; + } + interface InlayHintDisplayPart { + text: string; + span?: TextSpan; + file?: string; } interface TodoCommentDescriptor { text: string; @@ -10978,6 +10995,10 @@ declare namespace ts { variableElement = "var", /** Inside function */ localVariableElement = "local var", + /** using foo = ... */ + variableUsingElement = "using", + /** await using foo = ... */ + variableAwaitUsingElement = "await using", /** * Inside module and script only * function f() { } diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 319ad47217238..7c50c43840458 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -1464,8 +1464,8 @@ var ts = (() => { } return false; } - function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames ? identity : toFileNameLowerCase; + function createGetCanonicalFileName(useCaseSensitiveFileNames2) { + return useCaseSensitiveFileNames2 ? identity : toFileNameLowerCase; } function patternText({ prefix, suffix }) { return `${prefix}*${suffix}`; @@ -1646,7 +1646,7 @@ var ts = (() => { return void 0; }; hasOwnProperty = Object.prototype.hasOwnProperty; - fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g; + fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_. ]+/g; AssertionLevel = /* @__PURE__ */ ((AssertionLevel2) => { AssertionLevel2[AssertionLevel2["None"] = 0] = "None"; AssertionLevel2[AssertionLevel2["Normal"] = 1] = "Normal"; @@ -1951,7 +1951,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, return func.name; } else { const text = Function.prototype.toString.call(func); - const match = /^function\s+([\w\$]+)\s*\(/.exec(text); + const match = /^function\s+([\w$]+)\s*\(/.exec(text); return match ? match[1] : ""; } } @@ -2936,7 +2936,7 @@ ${lanes.join("\n")} "src/compiler/semver.ts"() { "use strict"; init_ts2(); - versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; @@ -4387,15 +4387,13 @@ ${lanes.join("\n")} NodeCheckFlags2[NodeCheckFlags2["ContainsCapturedBlockScopeBinding"] = 8192] = "ContainsCapturedBlockScopeBinding"; NodeCheckFlags2[NodeCheckFlags2["CapturedBlockScopedBinding"] = 16384] = "CapturedBlockScopedBinding"; NodeCheckFlags2[NodeCheckFlags2["BlockScopedBindingInLoop"] = 32768] = "BlockScopedBindingInLoop"; - NodeCheckFlags2[NodeCheckFlags2["ClassWithBodyScopedClassBinding"] = 65536] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags2[NodeCheckFlags2["BodyScopedClassBinding"] = 131072] = "BodyScopedClassBinding"; - NodeCheckFlags2[NodeCheckFlags2["NeedsLoopOutParameter"] = 262144] = "NeedsLoopOutParameter"; - NodeCheckFlags2[NodeCheckFlags2["AssignmentsMarked"] = 524288] = "AssignmentsMarked"; - NodeCheckFlags2[NodeCheckFlags2["ClassWithConstructorReference"] = 1048576] = "ClassWithConstructorReference"; - NodeCheckFlags2[NodeCheckFlags2["ConstructorReferenceInClass"] = 2097152] = "ConstructorReferenceInClass"; - NodeCheckFlags2[NodeCheckFlags2["ContainsClassWithPrivateIdentifiers"] = 4194304] = "ContainsClassWithPrivateIdentifiers"; - NodeCheckFlags2[NodeCheckFlags2["ContainsSuperPropertyInStaticInitializer"] = 8388608] = "ContainsSuperPropertyInStaticInitializer"; - NodeCheckFlags2[NodeCheckFlags2["InCheckIdentifier"] = 16777216] = "InCheckIdentifier"; + NodeCheckFlags2[NodeCheckFlags2["NeedsLoopOutParameter"] = 65536] = "NeedsLoopOutParameter"; + NodeCheckFlags2[NodeCheckFlags2["AssignmentsMarked"] = 131072] = "AssignmentsMarked"; + NodeCheckFlags2[NodeCheckFlags2["ContainsConstructorReference"] = 262144] = "ContainsConstructorReference"; + NodeCheckFlags2[NodeCheckFlags2["ConstructorReference"] = 536870912] = "ConstructorReference"; + NodeCheckFlags2[NodeCheckFlags2["ContainsClassWithPrivateIdentifiers"] = 1048576] = "ContainsClassWithPrivateIdentifiers"; + NodeCheckFlags2[NodeCheckFlags2["ContainsSuperPropertyInStaticInitializer"] = 2097152] = "ContainsSuperPropertyInStaticInitializer"; + NodeCheckFlags2[NodeCheckFlags2["InCheckIdentifier"] = 4194304] = "InCheckIdentifier"; return NodeCheckFlags2; })(NodeCheckFlags || {}); TypeFlags = /* @__PURE__ */ ((TypeFlags2) => { @@ -4576,7 +4574,8 @@ ${lanes.join("\n")} SignatureFlags5[SignatureFlags5["IsOuterCallChain"] = 16] = "IsOuterCallChain"; SignatureFlags5[SignatureFlags5["IsUntypedSignatureInJSFile"] = 32] = "IsUntypedSignatureInJSFile"; SignatureFlags5[SignatureFlags5["IsNonInferrable"] = 64] = "IsNonInferrable"; - SignatureFlags5[SignatureFlags5["PropagatingFlags"] = 39] = "PropagatingFlags"; + SignatureFlags5[SignatureFlags5["IsSignatureCandidateForOverloadFailure"] = 128] = "IsSignatureCandidateForOverloadFailure"; + SignatureFlags5[SignatureFlags5["PropagatingFlags"] = 167] = "PropagatingFlags"; SignatureFlags5[SignatureFlags5["CallChainFlags"] = 24] = "CallChainFlags"; return SignatureFlags5; })(SignatureFlags || {}); @@ -5425,10 +5424,10 @@ ${lanes.join("\n")} pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === 250 /* Low */ ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingInterval === 250 /* Low */ ? "pollLowPollingIntervalQueue" : "pollPollingIntervalQueue", pollingIntervalQueue(pollingInterval)); } } - function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) { + function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2) { const fileWatcherCallbacks = createMultiMap(); const dirWatchers = /* @__PURE__ */ new Map(); - const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames2); return nonPollingWatchFile; function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) { const filePath = toCanonicalName(fileName); @@ -5504,8 +5503,8 @@ ${lanes.join("\n")} pollScheduled = host.setTimeout(pollQueue, 2e3 /* High */, "pollQueue"); } } - function createSingleWatcherPerName(cache, useCaseSensitiveFileNames, name, callback, createWatcher) { - const toCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + function createSingleWatcherPerName(cache, useCaseSensitiveFileNames2, name, callback, createWatcher) { + const toCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const path = toCanonicalFileName(name); const existing = cache.get(path); if (existing) { @@ -5555,7 +5554,7 @@ ${lanes.join("\n")} } function createDirectoryWatcherSupportingRecursive({ watchDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, getAccessibleSortedChildDirectories, fileSystemEntryExists, @@ -5567,8 +5566,8 @@ ${lanes.join("\n")} const callbackCache = createMultiMap(); const cacheToUpdateChildWatches = /* @__PURE__ */ new Map(); let timerToUpdateChildWatches; - const filePathComparer = getStringComparer(!useCaseSensitiveFileNames); - const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames); + const filePathComparer = getStringComparer(!useCaseSensitiveFileNames2); + const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames2); return (dirName, callback, recursive, options) => recursive ? createDirectoryWatcher(dirName, options, callback) : watchDirectory(dirName, callback, recursive, options); function createDirectoryWatcher(dirName, options, callback) { const dirPath = toCanonicalFilePath(dirName); @@ -5735,12 +5734,12 @@ ${lanes.join("\n")} } } function isIgnoredPath(path, options) { - return some(ignoredPaths, (searchPath) => isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames, getCurrentDirectory); + return some(ignoredPaths, (searchPath) => isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames2, getCurrentDirectory); } function isInPath(path, searchPath) { if (stringContains(path, searchPath)) return true; - if (useCaseSensitiveFileNames) + if (useCaseSensitiveFileNames2) return false; return stringContains(toCanonicalFilePath(path), searchPath); } @@ -5758,14 +5757,14 @@ ${lanes.join("\n")} } }; } - function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames, getCurrentDirectory) { - return ((options == null ? void 0 : options.excludeDirectories) || (options == null ? void 0 : options.excludeFiles)) && (matchesExclude(pathToCheck, options == null ? void 0 : options.excludeFiles, useCaseSensitiveFileNames, getCurrentDirectory()) || matchesExclude(pathToCheck, options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames, getCurrentDirectory())); + function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames2, getCurrentDirectory) { + return ((options == null ? void 0 : options.excludeDirectories) || (options == null ? void 0 : options.excludeFiles)) && (matchesExclude(pathToCheck, options == null ? void 0 : options.excludeFiles, useCaseSensitiveFileNames2, getCurrentDirectory()) || matchesExclude(pathToCheck, options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2, getCurrentDirectory())); } - function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory) { + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory) { return (eventName, relativeFileName) => { if (eventName === "rename") { const fileName = !relativeFileName ? directoryName : normalizePath(combinePaths(directoryName, relativeFileName)); - if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames, getCurrentDirectory)) { + if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames2, getCurrentDirectory)) { callback(fileName); } } @@ -5778,7 +5777,7 @@ ${lanes.join("\n")} clearTimeout: clearTimeout2, fsWatchWorker, fileSystemEntryExists, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories, @@ -5850,7 +5849,7 @@ ${lanes.join("\n")} ); case 5 /* UseFsEventsOnParentDirectory */: if (!nonPollingWatchFile) { - nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames); + nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2); } return nonPollingWatchFile(fileName, callback, pollingInterval, getFallbackOptions(options)); default: @@ -5899,7 +5898,7 @@ ${lanes.join("\n")} return fsWatch( directoryName, 1 /* Directory */, - createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), + createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */, getFallbackOptions(options) @@ -5907,7 +5906,7 @@ ${lanes.join("\n")} } if (!hostRecursiveDirectoryWatcher) { hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fileSystemEntryExists, getAccessibleSortedChildDirectories, @@ -5953,7 +5952,7 @@ ${lanes.join("\n")} return fsWatch( directoryName, 1 /* Directory */, - createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), + createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */, getFallbackOptions(watchDirectoryOptions) @@ -5981,7 +5980,7 @@ ${lanes.join("\n")} function pollingWatchFile(fileName, callback, pollingInterval, options) { return createSingleWatcherPerName( pollingWatches, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, fileName, callback, (cb) => pollingWatchFileWorker(fileName, cb, pollingInterval, options) @@ -5990,7 +5989,7 @@ ${lanes.join("\n")} function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { return createSingleWatcherPerName( recursive ? fsWatchesRecursive : fsWatches, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, fileOrDirectory, callback, (cb) => fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, cb, recursive, fallbackPollingInterval, fallbackOptions) @@ -6149,7 +6148,7 @@ ${lanes.join("\n")} const Buffer2 = require("buffer").Buffer; const isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; const platform = _os.platform(); - const useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + const useCaseSensitiveFileNames2 = isFileSystemCaseSensitive(); const fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; const executingFilePath = __filename.endsWith("sys.js") ? _path.join(_path.dirname(__dirname), "__fake__.js") : __filename; const fsSupportsRecursiveFsWatch = process.platform === "win32" || process.platform === "darwin"; @@ -6160,7 +6159,7 @@ ${lanes.join("\n")} setTimeout, clearTimeout, fsWatchWorker, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fileSystemEntryExists, // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows @@ -6177,7 +6176,7 @@ ${lanes.join("\n")} const nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, write(s) { process.stdout.write(s); }, @@ -6306,12 +6305,12 @@ ${lanes.join("\n")} for (const node of profile.nodes) { if (node.callFrame.url) { const url = normalizeSlashes(node.callFrame.url); - if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) { + if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames2)) { node.callFrame.url = getRelativePathToDirectoryOrUrl( fileUrlRoot, url, fileUrlRoot, - createGetCanonicalFileName(useCaseSensitiveFileNames), + createGetCanonicalFileName(useCaseSensitiveFileNames2), /*isAbsolutePathAnUrl*/ true ); @@ -6491,7 +6490,7 @@ ${lanes.join("\n")} } } function readDirectory(path, extensions, excludes, includes, depth) { - return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); + return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames2, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path, entryKind) { const originalStackTraceLimit = Error.stackTraceLimit; @@ -7067,6 +7066,7 @@ ${lanes.join("\n")} Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, 1 /* Error */, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, 1 /* Error */, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, 1 /* Error */, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1065, 1 /* Error */, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065", "The return type of an async function or method must be the global Promise type."), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, 1 /* Error */, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, 1 /* Error */, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, 1 /* Error */, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), @@ -8769,6 +8769,7 @@ ${lanes.join("\n")} Parameter_modifiers_can_only_be_used_in_TypeScript_files: diag(8012, 1 /* Error */, "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012", "Parameter modifiers can only be used in TypeScript files."), Non_null_assertions_can_only_be_used_in_TypeScript_files: diag(8013, 1 /* Error */, "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013", "Non-null assertions can only be used in TypeScript files."), Type_assertion_expressions_can_only_be_used_in_TypeScript_files: diag(8016, 1 /* Error */, "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016", "Type assertion expressions can only be used in TypeScript files."), + Signature_declarations_can_only_be_used_in_TypeScript_files: diag(8017, 1 /* Error */, "Signature_declarations_can_only_be_used_in_TypeScript_files_8017", "Signature declarations can only be used in TypeScript files."), Report_errors_in_js_files: diag(8019, 3 /* Message */, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, 1 /* Error */, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, 1 /* Error */, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), @@ -9738,7 +9739,7 @@ ${lanes.join("\n")} if (withMinus) start2--; error2(Diagnostics.Octal_literals_are_not_allowed_Use_the_syntax_0, start2, pos - start2, literal); - return { type: 9 /* NumericLiteral */, value: tokenValue }; + return 9 /* NumericLiteral */; } } else { mainFragment = scanNumberFragment(); @@ -9778,20 +9779,18 @@ ${lanes.join("\n")} } if (tokenFlags & 8192 /* ContainsLeadingZero */) { error2(Diagnostics.Decimals_with_leading_zeros_are_not_allowed, start2, end2 - start2); - return { type: 9 /* NumericLiteral */, value: "" + +result }; + tokenValue = "" + +result; + return 9 /* NumericLiteral */; } if (decimalFragment !== void 0 || tokenFlags & 16 /* Scientific */) { checkForIdentifierStartAfterNumericLiteral(start2, decimalFragment === void 0 && !!(tokenFlags & 16 /* Scientific */)); - return { - type: 9 /* NumericLiteral */, - value: "" + +result - // if value is not an integer, it can be safely coerced to a number - }; + tokenValue = "" + +result; + return 9 /* NumericLiteral */; } else { tokenValue = result; const type = checkBigIntSuffix(); checkForIdentifierStartAfterNumericLiteral(start2); - return { type, value: tokenValue }; + return type; } } function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { @@ -10400,7 +10399,7 @@ ${lanes.join("\n")} return token = 41 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber().value; + scanNumber(); return token = 9 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { @@ -10518,8 +10517,7 @@ ${lanes.join("\n")} case 55 /* _7 */: case 56 /* _8 */: case 57 /* _9 */: - ({ type: token, value: tokenValue } = scanNumber()); - return token; + return token = scanNumber(); case 58 /* colon */: pos++; return token = 59 /* ColonToken */; @@ -11522,7 +11520,7 @@ ${lanes.join("\n")} } function validateLocaleAndSetLanguage(locale, sys2, errors) { const lowerCaseLocale = locale.toLowerCase(); - const matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); + const matchResult = /^([a-z]+)([_-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -16738,6 +16736,12 @@ ${lanes.join("\n")} function isThisIdentifier(node) { return !!node && node.kind === 80 /* Identifier */ && identifierIsThisKeyword(node); } + function isInTypeQuery(node) { + return !!findAncestor( + node, + (n) => n.kind === 186 /* TypeQuery */ ? true : n.kind === 80 /* Identifier */ || n.kind === 166 /* QualifiedName */ ? false : "quit" + ); + } function isThisInTypeQuery(node) { if (!isThisIdentifier(node)) { return false; @@ -17216,7 +17220,7 @@ ${lanes.join("\n")} return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype"; } function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return node.parent.kind === 166 /* QualifiedName */ && node.parent.right === node || node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.name === node; + return node.parent.kind === 166 /* QualifiedName */ && node.parent.right === node || node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.name === node || node.parent.kind === 236 /* MetaProperty */ && node.parent.name === node; } function isRightSideOfAccessExpression(node) { return isPropertyAccessExpression(node.parent) && node.parent.name === node || isElementAccessExpression(node.parent) && node.parent.argumentExpression === node; @@ -18219,6 +18223,9 @@ ${lanes.join("\n")} function getUseDefineForClassFields(compilerOptions) { return compilerOptions.useDefineForClassFields === void 0 ? getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ : compilerOptions.useDefineForClassFields; } + function getEmitStandardClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields !== false && getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */; + } function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return optionsHaveChanges(oldOptions, newOptions, semanticDiagnosticsOptionDeclarations); } @@ -18404,7 +18411,7 @@ ${lanes.join("\n")} function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } - function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames2, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); const absolutePath = combinePaths(currentDirectory, path); @@ -18413,22 +18420,22 @@ ${lanes.join("\n")} includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), - basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames2) }; } - function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { - return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + function getRegexFromPattern(pattern, useCaseSensitiveFileNames2) { + return new RegExp(pattern, useCaseSensitiveFileNames2 ? "" : "i"); } - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames2, currentDirectory, depth, getFileSystemEntries, realpath) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); - const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, useCaseSensitiveFileNames)); - const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); - const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames2, currentDirectory); + const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, useCaseSensitiveFileNames2)); + const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames2); + const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames2); const results = includeFileRegexes ? includeFileRegexes.map(() => []) : [[]]; const visited = /* @__PURE__ */ new Map(); - const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames); + const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames2); for (const basePath of patterns.basePaths) { visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); } @@ -18470,7 +18477,7 @@ ${lanes.join("\n")} } } } - function getBasePaths(path, includes, useCaseSensitiveFileNames) { + function getBasePaths(path, includes, useCaseSensitiveFileNames2) { const basePaths = [path]; if (includes) { const includeBasePaths = []; @@ -18478,9 +18485,9 @@ ${lanes.join("\n")} const absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); includeBasePaths.push(getIncludeBasePath(absolute)); } - includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames)); + includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames2)); for (const includeBasePath of includeBasePaths) { - if (every(basePaths, (basePath) => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames))) { + if (every(basePaths, (basePath) => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames2))) { basePaths.push(includeBasePath); } } @@ -19226,6 +19233,18 @@ ${lanes.join("\n")} function intrinsicTagNameToString(node) { return isIdentifier(node) ? idText(node) : getTextOfJsxNamespacedName(node); } + function isTypeUsableAsPropertyName(type) { + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); + } + function getPropertyNameFromType(type) { + if (type.flags & 8192 /* UniqueESSymbol */) { + return type.escapedName; + } + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + return escapeLeadingUnderscores("" + type.value); + } + return Debug.fail(); + } var resolvingEmptyArray, externalHelpersModuleNameText, defaultMaximumTruncationLength, noTruncationMaximumTruncationLength, stringWriter, GetLiteralTextFlags, fullTripleSlashReferencePathRegEx, fullTripleSlashReferenceTypeReferenceDirectiveRegEx, fullTripleSlashLibReferenceRegEx, fullTripleSlashAMDReferencePathRegEx, fullTripleSlashAMDModuleRegEx, defaultLibReferenceRegEx, AssignmentKind, FunctionFlags, Associativity, OperatorPrecedence, templateSubstitutionRegExp, doubleQuoteEscapedCharsRegExp, singleQuoteEscapedCharsRegExp, backtickQuoteEscapedCharsRegExp, escapedCharsMap, nonAsciiCharacters, jsxDoubleQuoteEscapedCharsRegExp, jsxSingleQuoteEscapedCharsRegExp, jsxEscapedCharsMap, indentStrings, base64Digits, carriageReturnLineFeed, lineFeed, objectAllocator, objectAllocatorPatchers, localizedDiagnosticMessages, reservedCharacterPattern, wildcardCharCodes, commonPackageFolders, implicitExcludePathRegexPattern, filesMatcher, directoriesMatcher, excludeMatcher, wildcardMatchers, supportedTSExtensions, supportedTSExtensionsFlat, supportedTSExtensionsWithJson, supportedTSExtensionsForExtractExtension, supportedJSExtensions, supportedJSExtensionsFlat, allSupportedExtensions, allSupportedExtensionsWithJson, supportedDeclarationExtensions, supportedTSImplementationExtensions, extensionsNotSupportingExtensionlessResolution, ModuleSpecifierEnding, extensionsToRemove, emptyFileSystemEntries; var init_utilities = __esm({ "src/compiler/utilities.ts"() { @@ -19298,9 +19317,9 @@ ${lanes.join("\n")} return OperatorPrecedence2; })(OperatorPrecedence || {}); templateSubstitutionRegExp = /\$\{/g; - doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - backtickQuoteEscapedCharsRegExp = /\r\n|[\\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g; + doubleQuoteEscapedCharsRegExp = /[\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + singleQuoteEscapedCharsRegExp = /[\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + backtickQuoteEscapedCharsRegExp = /\r\n|[\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g; escapedCharsMap = new Map(Object.entries({ " ": "\\t", "\v": "\\v", @@ -19322,8 +19341,8 @@ ${lanes.join("\n")} // special case for CRLFs in backticks })); nonAsciiCharacters = /[^\u0000-\u007F]/g; - jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g; - jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g; + jsxDoubleQuoteEscapedCharsRegExp = /["\u0000-\u001f\u2028\u2029\u0085]/g; + jsxSingleQuoteEscapedCharsRegExp = /['\u0000-\u001f\u2028\u2029\u0085]/g; jsxEscapedCharsMap = new Map(Object.entries({ '"': """, "'": "'" @@ -19344,7 +19363,7 @@ ${lanes.join("\n")} getSourceMapSourceConstructor: () => SourceMapSource }; objectAllocatorPatchers = []; - reservedCharacterPattern = /[^\w\s\/]/g; + reservedCharacterPattern = /[^\w\s/]/g; wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; implicitExcludePathRegexPattern = `(?!(${commonPackageFolders.join("|")})(/|$))`; @@ -26031,7 +26050,7 @@ ${lanes.join("\n")} text: ` var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { if (value !== null && value !== void 0) { - if (typeof value !== "object") throw new TypeError("Object expected."); + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); @@ -27651,7 +27670,7 @@ ${lanes.join("\n")} initializer ); } - function createAccessorPropertyGetRedirector(factory2, node, modifiers, name) { + function createAccessorPropertyGetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { return factory2.createGetAccessorDeclaration( modifiers, name, @@ -27661,7 +27680,7 @@ ${lanes.join("\n")} factory2.createBlock([ factory2.createReturnStatement( factory2.createPropertyAccessExpression( - factory2.createThis(), + receiver, factory2.getGeneratedPrivateNameForNode( node.name, /*prefix*/ @@ -27673,7 +27692,7 @@ ${lanes.join("\n")} ]) ); } - function createAccessorPropertySetRedirector(factory2, node, modifiers, name) { + function createAccessorPropertySetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { return factory2.createSetAccessorDeclaration( modifiers, name, @@ -27688,7 +27707,7 @@ ${lanes.join("\n")} factory2.createExpressionStatement( factory2.createAssignment( factory2.createPropertyAccessExpression( - factory2.createThis(), + receiver, factory2.getGeneratedPrivateNameForNode( node.name, /*prefix*/ @@ -29065,7 +29084,8 @@ ${lanes.join("\n")} nextToken(); const statements = parseList(0 /* SourceElements */, parseStatement); Debug.assert(token() === 1 /* EndOfFileToken */); - const endOfFileToken = addJSDocComment(parseTokenNode()); + const endHasJSDoc = hasPrecedingJSDocComment(); + const endOfFileToken = withJSDoc(parseTokenNode(), endHasJSDoc); const sourceFile = createSourceFile2(fileName, languageVersion2, scriptKind2, isDeclarationFile, statements, endOfFileToken, sourceFlags, setExternalModuleIndicator2); processCommentPragmas(sourceFile, sourceText); processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); @@ -29085,11 +29105,11 @@ ${lanes.join("\n")} parseDiagnostics.push(createDetachedDiagnostic(fileName, pos, end, diagnostic)); } } - function withJSDoc(node, hasJSDoc) { - return hasJSDoc ? addJSDocComment(node) : node; - } let hasDeprecatedTag = false; - function addJSDocComment(node) { + function withJSDoc(node, hasJSDoc) { + if (!hasJSDoc) { + return node; + } Debug.assert(!node.jsDoc); const jsDoc = mapDefined(getJSDocCommentRanges(node, sourceText), (comment) => JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); if (jsDoc.length) @@ -29883,6 +29903,9 @@ ${lanes.join("\n")} case 22 /* HeritageClauses */: return isHeritageClause2(); case 23 /* ImportOrExportSpecifiers */: + if (token() === 161 /* FromKeyword */ && lookAhead(nextTokenIsStringLiteral)) { + return false; + } return tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */; @@ -30241,6 +30264,9 @@ ${lanes.join("\n")} case 22 /* HeritageClauses */: return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_expected); case 23 /* ImportOrExportSpecifiers */: + if (token() === 161 /* FromKeyword */) { + return parseErrorAtCurrentToken(Diagnostics._0_expected, "}"); + } return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 13 /* JsxAttributes */: return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); @@ -31598,12 +31624,14 @@ ${lanes.join("\n")} return arrowExpression; } const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); if (expr.kind === 80 /* Identifier */ && token() === 39 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression( pos, expr, allowReturnTypeInArrowFunction, + hasJSDoc, /*asyncModifier*/ void 0 ); @@ -31649,7 +31677,7 @@ ${lanes.join("\n")} ), pos); } } - function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, asyncModifier) { + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier) { Debug.assert(token() === 39 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); const parameter = factory2.createParameterDeclaration( /*modifiers*/ @@ -31682,7 +31710,7 @@ ${lanes.join("\n")} equalsGreaterThanToken, body ); - return addJSDocComment(finishNode(node, pos)); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { const triState = isParenthesizedArrowFunctionExpression(); @@ -31810,9 +31838,10 @@ ${lanes.join("\n")} if (token() === 134 /* AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const asyncModifier = parseModifiersForArrowFunction(); const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); - return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier); } } return void 0; @@ -33173,10 +33202,14 @@ ${lanes.join("\n")} case 124 /* ProtectedKeyword */: case 125 /* PublicKeyword */: case 148 /* ReadonlyKeyword */: + const previousToken = token(); nextToken(); if (scanner2.hasPrecedingLineBreak()) { return false; } + if (previousToken === 138 /* DeclareKeyword */ && token() === 156 /* TypeKeyword */) { + return true; + } continue; case 162 /* GlobalKeyword */: nextToken(); @@ -33486,6 +33519,9 @@ ${lanes.join("\n")} return void 0; } } + function nextTokenIsStringLiteral() { + return nextToken() === 11 /* StringLiteral */; + } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); return !scanner2.hasPrecedingLineBreak() && (isIdentifier2() || token() === 11 /* StringLiteral */); @@ -33538,14 +33574,14 @@ ${lanes.join("\n")} function parseObjectBindingPattern() { const pos = getNodePos(); parseExpected(19 /* OpenBraceToken */); - const elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + const elements = allowInAnd(() => parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement)); parseExpected(20 /* CloseBraceToken */); return finishNode(factory2.createObjectBindingPattern(elements), pos); } function parseArrayBindingPattern() { const pos = getNodePos(); parseExpected(23 /* OpenBracketToken */); - const elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + const elements = allowInAnd(() => parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement)); parseExpected(24 /* CloseBracketToken */); return finishNode(factory2.createArrayBindingPattern(elements), pos); } @@ -34063,6 +34099,9 @@ ${lanes.join("\n")} } function parseTypeAliasDeclaration(pos, hasJSDoc, modifiers) { parseExpected(156 /* TypeKeyword */); + if (scanner2.hasPrecedingLineBreak()) { + parseErrorAtCurrentToken(Diagnostics.Line_break_not_permitted_here); + } const name = parseIdentifier(); const typeParameters = parseTypeParameters(); parseExpected(64 /* EqualsToken */); @@ -35045,7 +35084,7 @@ ${lanes.join("\n")} typeExpression = tryParseTypeExpression(); } const comment = parseTrailingTagComments(start2, getNodePos(), indent3, indentText); - const nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent3); + const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target, indent3); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -35331,7 +35370,7 @@ ${lanes.join("\n")} case 60 /* AtToken */: if (canParseTag) { const child = tryParseChildTag(target, indent3); - if (child && (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + if (child && (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */) && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } return child; @@ -35846,7 +35885,7 @@ ${lanes.join("\n")} })(IncrementalParser || (IncrementalParser = {})); namedArgRegExCache = /* @__PURE__ */ new Map(); tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; - singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + singleLinePragmaRegEx = /^\/\/\/?\s*@([^\s:]+)(.*)\s*$/im; } }); @@ -37258,19 +37297,19 @@ ${lanes.join("\n")} const wildcardFiles = arrayFrom(wildcardFileMap.values()); return literalFiles.concat(wildcardFiles, arrayFrom(wildCardJsonFileMap.values())); } - function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames, currentDirectory) { + function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames2, currentDirectory) { const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = spec; if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) return false; basePath = normalizePath(basePath); - const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames); + const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames2); if (validatedFilesSpec) { for (const fileName of validatedFilesSpec) { if (keyMapper(getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck) return false; } } - return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath); + return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath); } function invalidDotDotAfterRecursiveWildcard(s) { const wildcardIndex = startsWith(s, "**/") ? 0 : s.indexOf("/**/"); @@ -37280,17 +37319,17 @@ ${lanes.join("\n")} const lastDotIndex = endsWith(s, "/..") ? s.length : s.lastIndexOf("/../"); return lastDotIndex > wildcardIndex; } - function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory) { + function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory) { return matchesExcludeWorker( pathToCheck, filter(excludeSpecs, (spec) => !invalidDotDotAfterRecursiveWildcard(spec)), - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, currentDirectory ); } - function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath) { + function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath) { const excludePattern = getRegularExpressionForWildcard(excludeSpecs, combinePaths(normalizePath(currentDirectory), basePath), "exclude"); - const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames); + const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames2); if (!excludeRegex) return false; if (excludeRegex.test(pathToCheck)) @@ -37320,9 +37359,9 @@ ${lanes.join("\n")} return [Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec]; } } - function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }, path, useCaseSensitiveFileNames) { + function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }, path, useCaseSensitiveFileNames2) { const rawExcludeRegex = getRegularExpressionForWildcard(exclude, path, "exclude"); - const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames2 ? "" : "i"); const wildcardDirectories = {}; if (include !== void 0) { const recursiveKeys = []; @@ -37331,7 +37370,7 @@ ${lanes.join("\n")} if (excludeRegex && excludeRegex.test(spec)) { continue; } - const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); + const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2); if (match) { const { key, flags } = match; const existingFlags = wildcardDirectories[key]; @@ -37346,7 +37385,7 @@ ${lanes.join("\n")} for (const key in wildcardDirectories) { if (hasProperty(wildcardDirectories, key)) { for (const recursiveKey of recursiveKeys) { - if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames2)) { delete wildcardDirectories[key]; } } @@ -37355,20 +37394,20 @@ ${lanes.join("\n")} } return wildcardDirectories; } - function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2) { const match = wildcardDirectoryPattern.exec(spec); if (match) { const questionWildcardIndex = spec.indexOf("?"); const starWildcardIndex = spec.indexOf("*"); const lastDirectorySeperatorIndex = spec.lastIndexOf(directorySeparator); return { - key: useCaseSensitiveFileNames ? match[0] : toFileNameLowerCase(match[0]), + key: useCaseSensitiveFileNames2 ? match[0] : toFileNameLowerCase(match[0]), flags: questionWildcardIndex !== -1 && questionWildcardIndex < lastDirectorySeperatorIndex || starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex ? 1 /* Recursive */ : 0 /* None */ }; } if (isImplicitGlob(spec.substring(spec.lastIndexOf(directorySeparator) + 1))) { return { - key: removeTrailingDirectorySeparator(useCaseSensitiveFileNames ? spec : toFileNameLowerCase(spec)), + key: removeTrailingDirectorySeparator(useCaseSensitiveFileNames2 ? spec : toFileNameLowerCase(spec)), flags: 1 /* Recursive */ }; } @@ -37973,6 +38012,7 @@ ${lanes.join("\n")} { name: "checkJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: Diagnostics.JavaScript_Support, description: Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files, @@ -38199,7 +38239,7 @@ ${lanes.join("\n")} strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, - defaultValueDescription: false + defaultValueDescription: Diagnostics.false_unless_strict_is_set }, { name: "alwaysStrict", @@ -39053,6 +39093,18 @@ ${lanes.join("\n")} result.push("JSON"); return result.join(", "); } + function extensionsToExtensionsArray(extensions) { + const result = []; + if (extensions & 1 /* TypeScript */) + result.push(...supportedTSImplementationExtensions); + if (extensions & 2 /* JavaScript */) + result.push(...supportedJSExtensionsFlat); + if (extensions & 4 /* Declaration */) + result.push(...supportedDeclarationExtensions); + if (extensions & 8 /* Json */) + result.push(".json" /* Json */); + return result; + } function resolvedTypeScriptOnly(resolved) { if (!resolved) { return void 0; @@ -39225,8 +39277,8 @@ ${lanes.join("\n")} return typeRoots; } function arePathsEqual(path1, path2, host) { - const useCaseSensitiveFileNames = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; - return comparePaths(path1, path2, !useCaseSensitiveFileNames) === 0 /* EqualTo */; + const useCaseSensitiveFileNames2 = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; + return comparePaths(path1, path2, !useCaseSensitiveFileNames2) === 0 /* EqualTo */; } function getOriginalAndResolvedFileName(fileName, host, traceEnabled) { const resolvedFileName = realPath(fileName, host, traceEnabled); @@ -40489,7 +40541,7 @@ ${lanes.join("\n")} arrayIsEqualTo ); for (const conditions of conditionSets) { - const loadPackageJsonExportsState = { ...loadPackageJsonMainState, failedLookupLocations: [], conditions }; + const loadPackageJsonExportsState = { ...loadPackageJsonMainState, failedLookupLocations: [], conditions, host }; const exportResolutions = loadEntrypointsFromExportMap( packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, @@ -40521,23 +40573,42 @@ ${lanes.join("\n")} return entrypoints; function loadEntrypointsFromTargetExports(target) { var _a, _b; - if (typeof target === "string" && startsWith(target, "./") && target.indexOf("*") === -1) { - const partsAfterFirst = getPathComponents(target).slice(2); - if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) { - return false; - } - const resolvedTarget = combinePaths(scope.packageDirectory, target); - const finalPath = getNormalizedAbsolutePath(resolvedTarget, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); - const result = loadFileNameFromPackageJsonField( - extensions, - finalPath, - /*onlyRecordFailures*/ - false, - state - ); - if (result) { - entrypoints = appendIfUnique(entrypoints, result, (a, b) => a.path === b.path); - return true; + if (typeof target === "string" && startsWith(target, "./")) { + if (target.indexOf("*") >= 0 && state.host.readDirectory) { + if (target.indexOf("*") !== target.lastIndexOf("*")) { + return false; + } + state.host.readDirectory( + scope.packageDirectory, + extensionsToExtensionsArray(extensions), + /*excludes*/ + void 0, + [changeAnyExtension(target.replace("*", "**/*"), getDeclarationEmitExtensionForPath(target))] + ).forEach((entry) => { + entrypoints = appendIfUnique(entrypoints, { + path: entry, + ext: getAnyExtensionFromPath(entry), + resolvedUsingTsExtension: void 0 + }); + }); + } else { + const partsAfterFirst = getPathComponents(target).slice(2); + if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) { + return false; + } + const resolvedTarget = combinePaths(scope.packageDirectory, target); + const finalPath = getNormalizedAbsolutePath(resolvedTarget, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); + const result = loadFileNameFromPackageJsonField( + extensions, + finalPath, + /*onlyRecordFailures*/ + false, + state + ); + if (result) { + entrypoints = appendIfUnique(entrypoints, result, (a, b) => a.path === b.path); + return true; + } } } else if (Array.isArray(target)) { for (const t of target) { @@ -40746,6 +40817,9 @@ ${lanes.join("\n")} } const trailingParts = parts.slice(nameParts.length); const subpath = !length(trailingParts) ? "." : `.${directorySeparator}${trailingParts.join(directorySeparator)}`; + if (getAllowJSCompilerOption(state.compilerOptions) && !pathContainsNodeModules(directory)) { + return loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference); + } const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */); const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */); return loadModuleFromExports(scope, priorityExtensions, subpath, state, cache, redirectedReference) || loadModuleFromExports(scope, secondaryExtensions, subpath, state, cache, redirectedReference); @@ -41093,13 +41167,10 @@ ${lanes.join("\n")} function combineDirectoryPath(root, dir) { return ensureTrailingDirectorySeparator(combinePaths(root, dir)); } - function useCaseSensitiveFileNames() { - return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); - } function tryLoadInputFileForPath(finalPath, entry, packagePath, isImports2) { var _a, _b, _c, _d; - if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames()) : true)) { - const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames }); + if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true)) { + const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames: () => useCaseSensitiveFileNames(state) }); const commonSourceDirGuesses = []; if (state.compilerOptions.rootDir || state.compilerOptions.composite && state.compilerOptions.configFilePath) { const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, () => [], ((_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)) || "", getCanonicalFileName)); @@ -41128,7 +41199,7 @@ ${lanes.join("\n")} for (const commonSourceDirGuess of commonSourceDirGuesses) { const candidateDirectories = getOutputDirectoriesForBaseDirectory(commonSourceDirGuess); for (const candidateDir of candidateDirectories) { - if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames())) { + if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames(state))) { const pathFragment = finalPath.slice(candidateDir.length + 1); const possibleInputBase = combinePaths(commonSourceDirGuess, pathFragment); const jsAndDtsExtensions = [".mjs" /* Mjs */, ".cjs" /* Cjs */, ".js" /* Js */, ".json" /* Json */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */, ".d.ts" /* Dts */]; @@ -41138,7 +41209,7 @@ ${lanes.join("\n")} for (const possibleExt of inputExts) { if (!extensionIsOk(extensions, possibleExt)) continue; - const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames()); + const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames(state)); if (state.host.fileExists(possibleInputWithInputExtension)) { return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( extensions, @@ -41554,6 +41625,9 @@ ${lanes.join("\n")} trace(state.host, diagnostic, ...args); } } + function useCaseSensitiveFileNames(state) { + return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); + } var typeScriptVersion, nodeModulesAtTypes, NodeResolutionFeatures, nodeModulesPathPart, mangledScopedPackageSeparator; var init_moduleNameResolver = __esm({ "src/compiler/moduleNameResolver.ts"() { @@ -41684,6 +41758,9 @@ ${lanes.join("\n")} if (found === 1 /* Instantiated */) { return found; } + if (statement.kind === 271 /* ImportEqualsDeclaration */) { + found = 1 /* Instantiated */; + } } } if (found !== void 0) { @@ -45059,7 +45136,9 @@ ${lanes.join("\n")} for (const { ending, value } of candidates) { if (value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ ending, value })) { const matchedStar = value.substring(prefix.length, value.length - suffix.length); - return pathIsRelative(matchedStar) ? void 0 : key.replace("*", matchedStar); + if (!pathIsRelative(matchedStar)) { + return key.replace("*", matchedStar); + } } } } else if (some(candidates, (c) => c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, (c) => c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) { @@ -45131,7 +45210,7 @@ ${lanes.join("\n")} for (const key of getOwnKeys(exports)) { if (key === "default" || conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(conditions, key)) { const subTarget = exports[key]; - const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions); + const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions, mode); if (result) { return result; } @@ -45446,6 +45525,7 @@ ${lanes.join("\n")} var moduleKind = getEmitModuleKind(compilerOptions); var legacyDecorators = !!compilerOptions.experimentalDecorators; var useDefineForClassFields = getUseDefineForClassFields(compilerOptions); + var emitStandardClassFields = getEmitStandardClassFields(compilerOptions); var allowSyntheticDefaultImports = getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -45536,7 +45616,7 @@ ${lanes.join("\n")} return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, - getParameterIdentifierNameAtPosition, + getParameterIdentifierInfoAtPosition, getPromisedTypeOfPromise, getAwaitedType: (type) => getAwaitedType(type), getReturnTypeOfSignature, @@ -46189,7 +46269,7 @@ ${lanes.join("\n")} }; var amalgamatedDuplicates; var reverseMappedCache = /* @__PURE__ */ new Map(); - var inInferTypeForHomomorphicMappedType = false; + var homomorphicMappedTypeInferenceStack = []; var ambientModulesCache; var patternAmbientModules; var patternAmbientModuleAugmentations; @@ -46749,7 +46829,7 @@ ${lanes.join("\n")} return symbol; } if (symbol.flags & 2097152 /* Alias */) { - const targetFlags = getAllSymbolFlags(symbol); + const targetFlags = getSymbolFlags(symbol); if (targetFlags & meaning) { return symbol; } @@ -46800,7 +46880,7 @@ ${lanes.join("\n")} false ); } else if (isParameterPropertyDeclaration(declaration, declaration.parent)) { - return !(getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); + return !(emitStandardClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } @@ -46814,7 +46894,7 @@ ${lanes.join("\n")} return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { + if (emitStandardClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration( declaration, usage, @@ -46938,7 +47018,7 @@ ${lanes.join("\n")} return requiresScopeChangeWorker(node.name); case 172 /* PropertyDeclaration */: if (hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !useDefineForClassFields; + return !emitStandardClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -46977,7 +47057,7 @@ ${lanes.join("\n")} if (name === "const" && isConstAssertion(location)) { return void 0; } - if (isModuleDeclaration(location) && lastLocation && location.name === lastLocation) { + if (isModuleOrEnumDeclaration(location) && lastLocation && location.name === lastLocation) { lastLocation = location; location = location.parent; } @@ -47209,7 +47289,7 @@ ${lanes.join("\n")} } } function checkAndReportErrorForInvalidInitializer() { - if (propertyWithInvalidInitializer && !(useDefineForClassFields && getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */)) { + if (propertyWithInvalidInitializer && !emitStandardClassFields) { error2( errorLocation, errorLocation && propertyWithInvalidInitializer.type && textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) ? Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor : Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, @@ -47509,7 +47589,7 @@ ${lanes.join("\n")} /*isUse*/ false )); - const allFlags = symbol && getAllSymbolFlags(symbol); + const allFlags = symbol && getSymbolFlags(symbol); if (symbol && allFlags !== void 0 && !(allFlags & 111551 /* Value */)) { const rawName = unescapeLeadingUnderscores(name); if (isES2015OrLaterConstructorName(name)) { @@ -48245,11 +48325,23 @@ ${lanes.join("\n")} } return void 0; } - function getAllSymbolFlags(symbol) { - let flags = symbol.flags; + function getSymbolFlags(symbol, excludeTypeOnlyMeanings, excludeLocalMeanings) { + const typeOnlyDeclaration = excludeTypeOnlyMeanings && getTypeOnlyAliasDeclaration(symbol); + const typeOnlyDeclarationIsExportStar = typeOnlyDeclaration && isExportDeclaration(typeOnlyDeclaration); + const typeOnlyResolution = typeOnlyDeclaration && (typeOnlyDeclarationIsExportStar ? resolveExternalModuleName( + typeOnlyDeclaration.moduleSpecifier, + typeOnlyDeclaration.moduleSpecifier, + /*ignoreErrors*/ + true + ) : resolveAlias(typeOnlyDeclaration.symbol)); + const typeOnlyExportStarTargets = typeOnlyDeclarationIsExportStar && typeOnlyResolution ? getExportsOfModule(typeOnlyResolution) : void 0; + let flags = excludeLocalMeanings ? 0 /* None */ : symbol.flags; let seenSymbols; while (symbol.flags & 2097152 /* Alias */) { - const target = resolveAlias(symbol); + const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); + if (!typeOnlyDeclarationIsExportStar && target === typeOnlyResolution || (typeOnlyExportStarTargets == null ? void 0 : typeOnlyExportStarTargets.get(target.escapedName)) === target) { + break; + } if (target === unknownSymbol) { return 67108863 /* All */; } @@ -48307,7 +48399,7 @@ ${lanes.join("\n")} } if (links.typeOnlyDeclaration) { const resolved = links.typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? resolveSymbol(getExportsOfModule(links.typeOnlyDeclaration.symbol.parent).get(links.typeOnlyExportStarName || symbol.escapedName)) : resolveAlias(links.typeOnlyDeclaration.symbol); - return getAllSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0; + return getSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0; } return void 0; } @@ -48318,7 +48410,11 @@ ${lanes.join("\n")} const symbol = getSymbolOfDeclaration(node); const target = resolveAlias(symbol); if (target) { - const markAlias = target === unknownSymbol || getAllSymbolFlags(target) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */); + const markAlias = target === unknownSymbol || getSymbolFlags( + symbol, + /*excludeTypeOnlyMeanings*/ + true + ) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -48333,7 +48429,7 @@ ${lanes.join("\n")} if (!node) return Debug.fail(); if (isInternalModuleImportEqualsDeclaration(node)) { - if (getAllSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { + if (getSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { checkExpressionCached(node.moduleReference); } } @@ -48593,7 +48689,7 @@ ${lanes.join("\n")} return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation) : void 0; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) { - var _a, _b, _c, _d, _e, _f, _g, _h, _i; + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; if (startsWith(moduleReference, "@types/")) { const diag2 = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; const withoutAtTypePrefix = removePrefix(moduleReference, "@types/"); @@ -48628,8 +48724,11 @@ ${lanes.join("\n")} ); } } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) { - const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); - error2(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension); + const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); + if (!((importOrExport == null ? void 0 : importOrExport.isTypeOnly) || findAncestor(location, isImportTypeNode))) { + const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); + error2(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension); + } } if (sourceFile.symbol) { if (resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) { @@ -48646,7 +48745,7 @@ ${lanes.join("\n")} if (moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */) { const isSyncImport = currentSourceFile.impliedNodeFormat === 1 /* CommonJS */ && !findAncestor(location, isImportCall) || !!findAncestor(location, isImportEqualsDeclaration); const overrideClauseHost = findAncestor(location, (l) => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l)); - const overrideClause = overrideClauseHost && isImportTypeNode(overrideClauseHost) ? (_h = overrideClauseHost.assertions) == null ? void 0 : _h.assertClause : overrideClauseHost == null ? void 0 : overrideClauseHost.assertClause; + const overrideClause = overrideClauseHost && isImportTypeNode(overrideClauseHost) ? (_i = overrideClauseHost.assertions) == null ? void 0 : _i.assertClause : overrideClauseHost == null ? void 0 : overrideClauseHost.assertClause; if (isSyncImport && sourceFile.impliedNodeFormat === 99 /* ESNext */ && !getResolutionModeOverrideForClause(overrideClause)) { if (findAncestor(location, isImportEqualsDeclaration)) { error2(errorNode, Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); @@ -48749,7 +48848,7 @@ ${lanes.join("\n")} error2(errorNode, Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else if (mode === 99 /* ESNext */ && resolutionIsNode16OrNext && isExtensionlessRelativePathImport) { const absoluteRef = getNormalizedAbsolutePath(moduleReference, getDirectoryPath(currentSourceFile.path)); - const suggestedExt = (_i = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _i[1]; + const suggestedExt = (_j = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _j[1]; if (suggestedExt) { error2( errorNode, @@ -49181,7 +49280,7 @@ ${lanes.join("\n")} return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 && symbol.exportSymbol || symbol); } function symbolIsValue(symbol, includeTypeOnlyMembers) { - return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getAllSymbolFlags(symbol) & 111551 /* Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); + return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getSymbolFlags(symbol, !includeTypeOnlyMembers) & 111551 /* Value */); } function findConstructorDeclaration(node) { const members = node.members; @@ -49448,7 +49547,7 @@ ${lanes.join("\n")} } const shouldResolveAlias = symbolFromSymbolTable.flags & 2097152 /* Alias */ && !getDeclarationOfKind(symbolFromSymbolTable, 281 /* ExportSpecifier */); symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - const flags = shouldResolveAlias ? getAllSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; + const flags = shouldResolveAlias ? getSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; if (flags & meaning) { qualify = true; return true; @@ -50185,11 +50284,13 @@ ${lanes.join("\n")} return !!type2.target && isMappedTypeHomomorphic(type2.target) && !isMappedTypeHomomorphic(type2); } function createMappedTypeNodeFromType(type2) { + var _a2; Debug.assert(!!(type2.flags & 524288 /* Object */)); const readonlyToken = type2.declaration.readonlyToken ? factory.createToken(type2.declaration.readonlyToken.kind) : void 0; const questionToken = type2.declaration.questionToken ? factory.createToken(type2.declaration.questionToken.kind) : void 0; let appropriateConstraintTypeNode; let newTypeVariable; + const needsModifierPreservingWrapper = !isMappedTypeWithKeyofConstraintDeclaration(type2) && !(getModifiersTypeFromMappedType(type2).flags & 2 /* Unknown */) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && !(getConstraintTypeFromMappedType(type2).flags & 262144 /* TypeParameter */ && ((_a2 = getConstraintOfTypeParameter(getConstraintTypeFromMappedType(type2))) == null ? void 0 : _a2.flags) & 4194304 /* Index */); if (isMappedTypeWithKeyofConstraintDeclaration(type2)) { if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */) { const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T")); @@ -50197,6 +50298,11 @@ ${lanes.join("\n")} newTypeVariable = factory.createTypeReferenceNode(name); } appropriateConstraintTypeNode = factory.createTypeOperatorNode(143 /* KeyOfKeyword */, newTypeVariable || typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)); + } else if (needsModifierPreservingWrapper) { + const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T")); + const name = typeParameterToName(newParam, context); + newTypeVariable = factory.createTypeReferenceNode(name); + appropriateConstraintTypeNode = newTypeVariable; } else { appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context); } @@ -50227,6 +50333,18 @@ ${lanes.join("\n")} result, factory.createKeywordTypeNode(146 /* NeverKeyword */) ); + } else if (needsModifierPreservingWrapper) { + return factory.createConditionalTypeNode( + typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context), + factory.createInferTypeNode(factory.createTypeParameterDeclaration( + /*modifiers*/ + void 0, + factory.cloneNode(newTypeVariable.typeName), + factory.createTypeOperatorNode(143 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)) + )), + result, + factory.createKeywordTypeNode(146 /* NeverKeyword */) + ); } return result; } @@ -50780,6 +50898,7 @@ ${lanes.join("\n")} ); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { + var _a; const suppressAny = context.flags & 256 /* SuppressAnyReturnType */; if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; @@ -50915,6 +51034,20 @@ ${lanes.join("\n")} if (typeArguments) { node.typeArguments = factory.createNodeArray(typeArguments); } + if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 330 /* JSDocSignature */ && signature.declaration.parent.kind === 346 /* JSDocOverloadTag */) { + const comment = getTextOfNode( + signature.declaration.parent.parent, + /*includeTrivia*/ + true + ).slice(2, -2).split(/\r\n|\n|\r/).map((line) => line.replace(/^\s+/, " ")).join("\n"); + addSyntheticLeadingComment( + node, + 3 /* MultiLineCommentTrivia */, + comment, + /*hasTrailingNewLine*/ + true + ); + } cleanup == null ? void 0 : cleanup(); return node; } @@ -52276,7 +52409,7 @@ ${lanes.join("\n")} return !exports ? [] : filter(arrayFrom(exports.values()), (m) => isNamespaceMember(m) && isIdentifierText(m.escapedName, 99 /* ESNext */)); } function isTypeOnlyNamespace(symbol) { - return every(getNamespaceMembersForSerialization(symbol), (m) => !(getAllSymbolFlags(resolveSymbol(m)) & 111551 /* Value */)); + return every(getNamespaceMembersForSerialization(symbol), (m) => !(getSymbolFlags(resolveSymbol(m)) & 111551 /* Value */)); } function serializeModule(symbol, symbolName2, modifierFlags) { const members = getNamespaceMembersForSerialization(symbol); @@ -53984,7 +54117,7 @@ ${lanes.join("\n")} false, definedInMethod && !definedInConstructor )); - if (symbol.valueDeclaration && filterType(widened, (t) => !!(t.flags & ~98304 /* Nullable */)) === neverType) { + if (symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && filterType(widened, (t) => !!(t.flags & ~98304 /* Nullable */)) === neverType) { reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } @@ -54548,7 +54681,7 @@ ${lanes.join("\n")} true ); const declaredType = firstDefined(exportSymbol == null ? void 0 : exportSymbol.declarations, (d) => isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : void 0); - links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getAllSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; + links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } return links.type; } @@ -55263,9 +55396,6 @@ ${lanes.join("\n")} } return type; } - function isTypeUsableAsPropertyName(type) { - return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); - } function isLateBindableName(node) { if (!isComputedPropertyName(node) && !isElementAccessExpression(node)) { return false; @@ -55286,15 +55416,6 @@ ${lanes.join("\n")} function isNonBindableDynamicName(node) { return isDynamicName(node) && !isLateBindableName(node); } - function getPropertyNameFromType(type) { - if (type.flags & 8192 /* UniqueESSymbol */) { - return type.escapedName; - } - if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { - return escapeLeadingUnderscores("" + type.value); - } - return Debug.fail(); - } function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { Debug.assert(!!(getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol."); symbol.flags |= symbolFlags; @@ -55344,6 +55465,7 @@ ${lanes.join("\n")} return links.resolvedSymbol; } function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var _a, _b, _c; const links = getSymbolLinks(symbol); if (!links[resolutionKind]) { const isStatic2 = resolutionKind === "resolvedExports" /* resolvedExports */; @@ -55362,7 +55484,7 @@ ${lanes.join("\n")} } } } - const assignments = symbol.assignmentDeclarationMembers; + const assignments = (((_a = symbol.valueDeclaration) == null ? void 0 : _a.kind) === 219 /* ArrowFunction */ || ((_b = symbol.valueDeclaration) == null ? void 0 : _b.kind) === 218 /* FunctionExpression */) && ((_c = getSymbolOfNode(symbol.valueDeclaration.parent)) == null ? void 0 : _c.assignmentDeclarationMembers) || symbol.assignmentDeclarationMembers; if (assignments) { const decls = arrayFrom(assignments.values()); for (const member of decls) { @@ -55491,7 +55613,7 @@ ${lanes.join("\n")} /*resolvedTypePredicate*/ void 0, sig.minArgumentCount, - sig.flags & 39 /* PropagatingFlags */ + sig.flags & 167 /* PropagatingFlags */ ); result.target = sig.target; result.mapper = sig.mapper; @@ -55792,7 +55914,7 @@ ${lanes.join("\n")} /*resolvedTypePredicate*/ void 0, minArgCount, - (left.flags | right.flags) & 39 /* PropagatingFlags */ + (left.flags | right.flags) & 167 /* PropagatingFlags */ ); result.compositeKind = 1048576 /* Union */; result.compositeSignatures = concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); @@ -55940,20 +56062,17 @@ ${lanes.join("\n")} setStructuredTypeMembers(type, members2, callSignatures, constructSignatures, indexInfos2); return; } - let members = emptySymbols; + let members = getExportsOfSymbol(symbol); let indexInfos; - if (symbol.exports) { - members = getExportsOfSymbol(symbol); - if (symbol === globalThisSymbol) { - const varsOnly = /* @__PURE__ */ new Map(); - members.forEach((p) => { - var _a; - if (!(p.flags & 418 /* BlockScoped */) && !(p.flags & 512 /* ValueModule */ && ((_a = p.declarations) == null ? void 0 : _a.length) && every(p.declarations, isAmbientModule))) { - varsOnly.set(p.escapedName, p); - } - }); - members = varsOnly; - } + if (symbol === globalThisSymbol) { + const varsOnly = /* @__PURE__ */ new Map(); + members.forEach((p) => { + var _a; + if (!(p.flags & 418 /* BlockScoped */) && !(p.flags & 512 /* ValueModule */ && ((_a = p.declarations) == null ? void 0 : _a.length) && every(p.declarations, isAmbientModule))) { + varsOnly.set(p.escapedName, p); + } + }); + members = varsOnly; } let baseConstructorIndexInfo; setStructuredTypeMembers(type, members, emptyArray, emptyArray, emptyArray); @@ -56002,7 +56121,7 @@ ${lanes.join("\n")} /*resolvedTypePredicate*/ void 0, sig.minArgumentCount, - sig.flags & 39 /* PropagatingFlags */ + sig.flags & 167 /* PropagatingFlags */ ) : void 0 )); } @@ -57394,7 +57513,7 @@ ${lanes.join("\n")} return getReturnTypeOfTypeTag(declaration); } function isResolvingReturnTypeOfSignature(signature) { - return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; + return signature.compositeSignatures && some(signature.compositeSignatures, isResolvingReturnTypeOfSignature) || !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; } function getRestTypeOfSignature(signature) { return tryGetRestTypeOfSignature(signature) || anyType; @@ -58742,6 +58861,9 @@ ${lanes.join("\n")} function getEndElementCount(type, flags) { return type.elementFlags.length - findLastIndex(type.elementFlags, (f) => !(f & flags)) - 1; } + function getTotalFixedElementCount(type) { + return type.fixedLength + getEndElementCount(type, 3 /* Fixed */); + } function getElementTypes(type) { const typeArguments = getTypeArguments(type); const arity = getTypeReferenceArity(type); @@ -59647,10 +59769,7 @@ ${lanes.join("\n")} } if (index >= 0) { errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); - return mapType(objectType, (t) => { - const restType = getRestTypeOfTupleType(t) || undefinedType; - return accessFlags & 1 /* IncludeUndefined */ ? getUnionType([restType, missingType]) : restType; - }); + return getTupleElementTypeOutOfStartCount(objectType, index, accessFlags & 1 /* IncludeUndefined */ ? missingType : void 0); } } } @@ -59935,7 +60054,7 @@ ${lanes.join("\n")} } if (compilerOptions.noUncheckedIndexedAccess && accessFlags & 32 /* ExpressionPosition */) accessFlags |= 1 /* IncludeUndefined */; - if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 199 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)) || isGenericReducibleType(objectType))) { + if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 199 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target)) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target))) || isGenericReducibleType(objectType))) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } @@ -60785,7 +60904,7 @@ ${lanes.join("\n")} /*resolvedTypePredicate*/ void 0, signature.minArgumentCount, - signature.flags & 39 /* PropagatingFlags */ + signature.flags & 167 /* PropagatingFlags */ ); result.target = signature; result.mapper = mapper; @@ -62172,6 +62291,7 @@ ${lanes.join("\n")} let errorInfo; let relatedInfo; let maybeKeys; + let maybeKeysSet; let sourceStack; let targetStack; let maybeCount = 0; @@ -63041,9 +63161,13 @@ ${lanes.join("\n")} } if (!maybeKeys) { maybeKeys = []; + maybeKeysSet = /* @__PURE__ */ new Set(); sourceStack = []; targetStack = []; } else { + if (maybeKeysSet.has(id)) { + return 3 /* Maybe */; + } const broadestEquivalentId = id.startsWith("*") ? getRelationKey( source2, target2, @@ -63052,10 +63176,8 @@ ${lanes.join("\n")} /*ignoreConstraints*/ true ) : void 0; - for (let i = 0; i < maybeCount; i++) { - if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) { - return 3 /* Maybe */; - } + if (broadestEquivalentId && maybeKeysSet.has(broadestEquivalentId)) { + return 3 /* Maybe */; } if (sourceDepth === 100 || targetDepth === 100) { overflow = true; @@ -63064,6 +63186,7 @@ ${lanes.join("\n")} } const maybeStart = maybeCount; maybeKeys[maybeCount] = id; + maybeKeysSet.add(id); maybeCount++; const saveExpandingFlags = expandingFlags; if (recursionFlags & 1 /* Source */) { @@ -63116,17 +63239,34 @@ ${lanes.join("\n")} if (result2) { if (result2 === -1 /* True */ || sourceDepth === 0 && targetDepth === 0) { if (result2 === -1 /* True */ || result2 === 3 /* Maybe */) { - for (let i = maybeStart; i < maybeCount; i++) { - relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags); - } + resetMaybeStack( + /*markAllAsSucceeded*/ + true + ); + } else { + resetMaybeStack( + /*markAllAsSucceeded*/ + false + ); } - maybeCount = maybeStart; } } else { relation.set(id, (reportErrors2 ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags); - maybeCount = maybeStart; + resetMaybeStack( + /*markAllAsSucceeded*/ + false + ); } return result2; + function resetMaybeStack(markAllAsSucceeded) { + for (let i = maybeStart; i < maybeCount; i++) { + maybeKeysSet.delete(maybeKeys[i]); + if (markAllAsSucceeded) { + relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags); + } + } + maybeCount = maybeStart; + } } function structuredTypeRelatedTo(source2, target2, reportErrors2, intersectionState) { const saveErrorInfo = captureErrorCalculationState(); @@ -63538,26 +63678,6 @@ ${lanes.join("\n")} )) { return result2; } - if (sourceFlags & 8388608 /* IndexedAccess */) { - const indexType = source2.indexType; - if (indexType.flags & 4194304 /* Index */) { - const unresolvedIndexConstraint = getBaseConstraintOfType(indexType.type); - const indexConstraint = unresolvedIndexConstraint && unresolvedIndexConstraint !== noConstraintType ? getIndexType(unresolvedIndexConstraint) : keyofConstraintType; - const constraint2 = getIndexedAccessType(source2.objectType, indexConstraint); - if (result2 = isRelatedTo( - constraint2, - target2, - 1 /* Source */, - /*reportErrors*/ - false, - /*headMessage*/ - void 0, - intersectionState - )) { - return result2; - } - } - } if (isMappedTypeGenericIndexedAccess(source2)) { const indexConstraint = getConstraintOfType(source2.indexType); if (indexConstraint) { @@ -64954,7 +65074,8 @@ ${lanes.join("\n")} return !!elementType && isEmptyLiteralType(elementType); } function isTupleLikeType(type) { - return isTupleType(type) || !!getPropertyOfType(type, "0"); + let lengthType; + return isTupleType(type) || !!getPropertyOfType(type, "0") || isArrayLikeType(type) && !!(lengthType = getTypeOfPropertyOfType(type, "length")) && everyType(lengthType, (t) => !!(t.flags & 256 /* NumberLiteral */)); } function isArrayOrTupleLikeType(type) { return isArrayLikeType(type) || isTupleLikeType(type); @@ -64965,17 +65086,7 @@ ${lanes.join("\n")} return propType; } if (everyType(type, isTupleType)) { - return mapType(type, (t) => { - const tupleType = t; - const restType = getRestTypeOfTupleType(tupleType); - if (!restType) { - return undefinedType; - } - if (compilerOptions.noUncheckedIndexedAccess && index >= tupleType.target.fixedLength + getEndElementCount(tupleType.target, 3 /* Fixed */)) { - return getUnionType([restType, undefinedType]); - } - return restType; - }); + return getTupleElementTypeOutOfStartCount(type, index, compilerOptions.noUncheckedIndexedAccess ? undefinedType : void 0); } return void 0; } @@ -65043,6 +65154,19 @@ ${lanes.join("\n")} function getRestTypeOfTupleType(type) { return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength); } + function getTupleElementTypeOutOfStartCount(type, index, undefinedOrMissingType2) { + return mapType(type, (t) => { + const tupleType = t; + const restType = getRestTypeOfTupleType(tupleType); + if (!restType) { + return undefinedType; + } + if (undefinedOrMissingType2 && index >= getTotalFixedElementCount(tupleType.target)) { + return getUnionType([restType, undefinedOrMissingType2]); + } + return restType; + }); + } function getRestArrayTypeOfTupleType(type) { const restType = getRestTypeOfTupleType(type); return restType && createArrayType(restType); @@ -65577,17 +65701,18 @@ ${lanes.join("\n")} ); } function inferTypeForHomomorphicMappedType(source, target, constraint) { - if (inInferTypeForHomomorphicMappedType) { - return void 0; + const cacheKey = source.id + "," + target.id + "," + constraint.id; + if (reverseMappedCache.has(cacheKey)) { + return reverseMappedCache.get(cacheKey); } - const key = source.id + "," + target.id + "," + constraint.id; - if (reverseMappedCache.has(key)) { - return reverseMappedCache.get(key); + const recursionKey = source.id + "," + (target.target || target).id; + if (contains(homomorphicMappedTypeInferenceStack, recursionKey)) { + return void 0; } - inInferTypeForHomomorphicMappedType = true; + homomorphicMappedTypeInferenceStack.push(recursionKey); const type = createReverseMappedType(source, target, constraint); - inInferTypeForHomomorphicMappedType = false; - reverseMappedCache.set(key, type); + homomorphicMappedTypeInferenceStack.pop(); + reverseMappedCache.set(cacheKey, type); return type; } function isPartiallyInferableType(type) { @@ -66541,12 +66666,6 @@ ${lanes.join("\n")} } return links.resolvedSymbol; } - function isInTypeQuery(node) { - return !!findAncestor( - node, - (n) => n.kind === 186 /* TypeQuery */ ? true : n.kind === 80 /* Identifier */ || n.kind === 166 /* QualifiedName */ ? false : "quit" - ); - } function isInAmbientOrTypeNode(node) { return !!(node.flags & 33554432 /* Ambient */ || findAncestor(node, (n) => isInterfaceDeclaration(n) || isTypeAliasDeclaration(n) || isTypeLiteralNode(n))); } @@ -68044,12 +68163,15 @@ ${lanes.join("\n")} return narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue); } const target = getReferenceCandidate(expr.right); - const leftType = getTypeOfExpression(expr.left); - if (leftType.flags & 8576 /* StringOrNumberLiteralOrUnique */) { - if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target) && getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) { + if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target)) { + const leftType = getTypeOfExpression(expr.left); + if (isTypeUsableAsPropertyName(leftType) && getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) { return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */); } - if (isMatchingReference(reference, target)) { + } + if (isMatchingReference(reference, target)) { + const leftType = getTypeOfExpression(expr.left); + if (isTypeUsableAsPropertyName(leftType)) { return narrowTypeByInKeyword(type, leftType, assumeTrue); } } @@ -68497,8 +68619,8 @@ ${lanes.join("\n")} } const parent2 = getRootDeclaration(symbol.valueDeclaration).parent; const links = getNodeLinks(parent2); - if (!(links.flags & 524288 /* AssignmentsMarked */)) { - links.flags |= 524288 /* AssignmentsMarked */; + if (!(links.flags & 131072 /* AssignmentsMarked */)) { + links.flags |= 131072 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(parent2)) { markNodeAssignments(parent2); } @@ -68506,7 +68628,7 @@ ${lanes.join("\n")} return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!findAncestor(node.parent, (node2) => (isFunctionLike(node2) || isCatchClause(node2)) && !!(getNodeLinks(node2).flags & 524288 /* AssignmentsMarked */)); + return !!findAncestor(node.parent, (node2) => (isFunctionLike(node2) || isCatchClause(node2)) && !!(getNodeLinks(node2).flags & 131072 /* AssignmentsMarked */)); } function markNodeAssignments(node) { if (node.kind === 80 /* Identifier */) { @@ -68588,9 +68710,13 @@ ${lanes.join("\n")} symbol, /*excludes*/ 111551 /* Value */ - ) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */)) { + ) && !isInTypeQuery(location)) { const target = resolveAlias(symbol); - if (getAllSymbolFlags(target) & (111551 /* Value */ | 1048576 /* ExportValue */)) { + if (getSymbolFlags( + symbol, + /*excludeTypeOnlyMeanings*/ + true + ) & (111551 /* Value */ | 1048576 /* ExportValue */)) { if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); } else { @@ -68608,11 +68734,11 @@ ${lanes.join("\n")} const parent2 = declaration.parent.parent; if (parent2.kind === 260 /* VariableDeclaration */ && getCombinedNodeFlagsCached(declaration) & 6 /* Constant */ || parent2.kind === 169 /* Parameter */) { const links = getNodeLinks(parent2); - if (!(links.flags & 16777216 /* InCheckIdentifier */)) { - links.flags |= 16777216 /* InCheckIdentifier */; + if (!(links.flags & 4194304 /* InCheckIdentifier */)) { + links.flags |= 4194304 /* InCheckIdentifier */; const parentType = getTypeForBindingElementParent(parent2, 0 /* Normal */); const parentTypeConstraint = parentType && mapType(parentType, getBaseConstraintOrType); - links.flags &= ~16777216 /* InCheckIdentifier */; + links.flags &= ~4194304 /* InCheckIdentifier */; if (parentTypeConstraint && parentTypeConstraint.flags & 1048576 /* Union */ && !(parent2.kind === 169 /* Parameter */ && isSymbolAssigned(symbol))) { const pattern = declaration.parent; const narrowedType = getFlowTypeOfReference( @@ -68689,17 +68815,7 @@ ${lanes.join("\n")} } let declaration = localOrExportSymbol.valueDeclaration; if (declaration && localOrExportSymbol.flags & 32 /* Class */) { - if (declaration.kind === 263 /* ClassDeclaration */ && nodeIsDecorated(legacyDecorators, declaration)) { - let container = getContainingClass(node); - while (container !== void 0) { - if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 1048576 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 2097152 /* ConstructorReferenceInClass */; - break; - } - container = getContainingClass(container); - } - } else if (declaration.kind === 231 /* ClassExpression */) { + if (isClassLike(declaration) && declaration.name !== node) { let container = getThisContainer( node, /*includeArrowFunctions*/ @@ -68707,14 +68823,7 @@ ${lanes.join("\n")} /*includeClassComputedPropertyName*/ false ); - while (container.kind !== 312 /* SourceFile */) { - if (container.parent === declaration) { - if (isPropertyDeclaration(container) && isStatic(container) || isClassStaticBlockDeclaration(container)) { - getNodeLinks(declaration).flags |= 1048576 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 2097152 /* ConstructorReferenceInClass */; - } - break; - } + while (container.kind !== 312 /* SourceFile */ && container.parent !== declaration) { container = getThisContainer( container, /*includeArrowFunctions*/ @@ -68723,6 +68832,11 @@ ${lanes.join("\n")} false ); } + if (container.kind !== 312 /* SourceFile */) { + getNodeLinks(declaration).flags |= 262144 /* ContainsConstructorReference */; + getNodeLinks(container).flags |= 262144 /* ContainsConstructorReference */; + getNodeLinks(node).flags |= 536870912 /* ConstructorReference */; + } } } checkNestedBlockScopedBinding(node, symbol); @@ -68853,7 +68967,7 @@ ${lanes.join("\n")} if (isForStatement(container)) { const varDeclList = getAncestor(symbol.valueDeclaration, 261 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 65536 /* NeedsLoopOutParameter */; } } getNodeLinks(symbol.valueDeclaration).flags |= 32768 /* BlockScopedBindingInLoop */; @@ -69131,7 +69245,7 @@ ${lanes.join("\n")} if (!isCallExpression2 && languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */ && (isPropertyDeclaration(container) || isClassStaticBlockDeclaration(container))) { forEachEnclosingBlockScopeContainer(node.parent, (current) => { if (!isSourceFile(current) || isExternalOrCommonJsModule(current)) { - getNodeLinks(current).flags |= 8388608 /* ContainsSuperPropertyInStaticInitializer */; + getNodeLinks(current).flags |= 2097152 /* ContainsSuperPropertyInStaticInitializer */; } }); } @@ -70232,7 +70346,7 @@ ${lanes.join("\n")} /*resolvedTypePredicate*/ void 0, minArgCount, - (left.flags | right.flags) & 39 /* PropagatingFlags */ + (left.flags | right.flags) & 167 /* PropagatingFlags */ ); result.compositeKind = 2097152 /* Intersection */; result.compositeSignatures = concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); @@ -70316,6 +70430,10 @@ ${lanes.join("\n")} function hasDefaultValue(node) { return node.kind === 208 /* BindingElement */ && !!node.initializer || node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */; } + function isSpreadIntoCallOrNew(node) { + const parent2 = walkUpParenthesizedExpressions(node.parent); + return isSpreadElement(parent2) && isCallOrNewExpression(parent2.parent); + } function checkArrayLiteral(node, checkMode, forceTuple) { const elements = node.elements; const elementCount = elements.length; @@ -70323,14 +70441,13 @@ ${lanes.join("\n")} const elementFlags = []; pushCachedContextualType(node); const inDestructuringPattern = isAssignmentTarget(node); - const isSpreadIntoCallOrNew = isSpreadElement(node.parent) && isCallOrNewExpression(node.parent.parent); - const inConstContext = isSpreadIntoCallOrNew || isConstContext(node); + const inConstContext = isConstContext(node); const contextualType = getApparentTypeOfContextualType( node, /*contextFlags*/ void 0 ); - const inTupleContext = isSpreadIntoCallOrNew || !!contextualType && someType(contextualType, isTupleLikeType); + const inTupleContext = isSpreadIntoCallOrNew(node) || !!contextualType && someType(contextualType, isTupleLikeType); let hasOmittedExpression = false; for (let i = 0; i < elementCount; i++) { const e = elements[i]; @@ -71763,7 +71880,7 @@ ${lanes.join("\n")} } let diagnosticMessage; const declarationName = idText(right); - if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & 32 /* Static */) && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { + if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & 32 /* Static */) && (useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { diagnosticMessage = error2(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } else if (valueDeclaration.kind === 263 /* ClassDeclaration */ && node.parent.kind !== 183 /* TypeReference */ && !(valueDeclaration.flags & 33554432 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error2(right, Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -72670,7 +72787,7 @@ ${lanes.join("\n")} } } function getThisArgumentOfCall(node) { - const expression = node.kind === 213 /* CallExpression */ ? node.expression : node.kind === 215 /* TaggedTemplateExpression */ ? node.tag : void 0; + const expression = node.kind === 213 /* CallExpression */ ? node.expression : node.kind === 215 /* TaggedTemplateExpression */ ? node.tag : node.kind === 170 /* Decorator */ && !legacyDecorators ? node.expression : void 0; if (expression) { const callee = skipOuterExpressions(expression); if (isAccessExpression(callee)) { @@ -73258,7 +73375,7 @@ ${lanes.join("\n")} parameters.push(createCombinedSymbolFromTypes(symbols, mapDefined(candidates, (candidate) => tryGetTypeAtPosition(candidate, i)))); } const restParameterSymbols = mapDefined(candidates, (c) => signatureHasRestParameter(c) ? last(c.parameters) : void 0); - let flags = 0 /* None */; + let flags = 128 /* IsSignatureCandidateForOverloadFailure */; if (restParameterSymbols.length !== 0) { const type = createArrayType(getUnionType(mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); @@ -73982,6 +74099,8 @@ ${lanes.join("\n")} return returnType; } function checkDeprecatedSignature(signature, node) { + if (signature.flags & 128 /* IsSignatureCandidateForOverloadFailure */) + return; if (signature.declaration && signature.declaration.flags & 536870912 /* Deprecated */) { const suggestionNode = getDeprecatedSuggestionNode(node); const name = tryGetPropertyAccessOrIdentifierToString(getInvokedExpression(node)); @@ -74455,7 +74574,7 @@ ${lanes.join("\n")} } return restParameter.escapedName; } - function getParameterIdentifierNameAtPosition(signature, pos) { + function getParameterIdentifierInfoAtPosition(signature, pos) { var _a; if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 324 /* JSDocFunctionType */) { return void 0; @@ -74463,10 +74582,16 @@ ${lanes.join("\n")} const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { const param = signature.parameters[pos]; - return isParameterDeclarationWithIdentifierName(param) ? [param.escapedName, false] : void 0; + const paramIdent = getParameterDeclarationIdentifier(param); + return paramIdent ? { + parameter: paramIdent, + parameterName: param.escapedName, + isRestParameter: false + } : void 0; } const restParameter = signature.parameters[paramCount] || unknownSymbol; - if (!isParameterDeclarationWithIdentifierName(restParameter)) { + const restIdent = getParameterDeclarationIdentifier(restParameter); + if (!restIdent) { return void 0; } const restType = getTypeOfSymbol(restParameter); @@ -74475,18 +74600,19 @@ ${lanes.join("\n")} const index = pos - paramCount; const associatedName = associatedNames == null ? void 0 : associatedNames[index]; const isRestTupleElement = !!(associatedName == null ? void 0 : associatedName.dotDotDotToken); - return associatedName ? [ - getTupleElementLabel(associatedName), - isRestTupleElement - ] : void 0; + if (associatedName) { + Debug.assert(isIdentifier(associatedName.name)); + return { parameter: associatedName.name, parameterName: associatedName.name.escapedText, isRestParameter: isRestTupleElement }; + } + return void 0; } if (pos === paramCount) { - return [restParameter.escapedName, true]; + return { parameter: restIdent, parameterName: restParameter.escapedName, isRestParameter: true }; } return void 0; } - function isParameterDeclarationWithIdentifierName(symbol) { - return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name); + function getParameterDeclarationIdentifier(symbol) { + return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name) && symbol.valueDeclaration.name; } function isValidDeclarationForTupleLabel(d) { return d.kind === 202 /* NamedTupleMember */ || isParameter(d) && d.name && isIdentifier(d.name); @@ -77349,7 +77475,18 @@ ${lanes.join("\n")} addLazyDiagnostic(checkSignatureDeclarationDiagnostics); function checkSignatureDeclarationDiagnostics() { checkCollisionWithArgumentsInGeneratedCode(node); - const returnTypeNode = getEffectiveReturnTypeNode(node); + let returnTypeNode = getEffectiveReturnTypeNode(node); + let returnTypeErrorLocation = returnTypeNode; + if (isInJSFile(node)) { + const typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && isTypeReferenceNode(typeTag.typeExpression.type)) { + const signature = getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + if (signature && signature.declaration) { + returnTypeNode = getEffectiveReturnTypeNode(signature.declaration); + returnTypeErrorLocation = typeTag.typeExpression.type; + } + } + } if (noImplicitAny && !returnTypeNode) { switch (node.kind) { case 180 /* ConstructSignature */: @@ -77360,21 +77497,21 @@ ${lanes.join("\n")} break; } } - if (returnTypeNode) { + if (returnTypeNode && returnTypeErrorLocation) { const functionFlags2 = getFunctionFlags(node); if ((functionFlags2 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { const returnType = getTypeFromTypeNode(returnTypeNode); if (returnType === voidType) { - error2(returnTypeNode, Diagnostics.A_generator_cannot_have_a_void_type_annotation); + error2(returnTypeErrorLocation, Diagnostics.A_generator_cannot_have_a_void_type_annotation); } else { const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags2 & 2 /* Async */) !== 0) || anyType; const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags2 & 2 /* Async */) !== 0) || generatorYieldType; const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags2 & 2 /* Async */) !== 0) || unknownType; const generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags2 & 2 /* Async */)); - checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode); + checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeErrorLocation); } } else if ((functionFlags2 & 3 /* AsyncGenerator */) === 2 /* Async */) { - checkAsyncFunctionReturnType(node, returnTypeNode); + checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation); } } if (node.kind !== 181 /* IndexSignature */ && node.kind !== 324 /* JSDocFunctionType */) { @@ -77455,7 +77592,7 @@ ${lanes.join("\n")} case "length": case "caller": case "arguments": - if (compilerOptions.useDefineForClassFields) { + if (useDefineForClassFields) { break; } case "prototype": @@ -77557,7 +77694,7 @@ ${lanes.join("\n")} function setNodeLinksForPrivateIdentifierScope(node) { if (isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { for (let lexicalScope = getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = getEnclosingBlockScopeContainer(lexicalScope)) { - getNodeLinks(lexicalScope).flags |= 4194304 /* ContainsClassWithPrivateIdentifiers */; + getNodeLinks(lexicalScope).flags |= 1048576 /* ContainsClassWithPrivateIdentifiers */; } if (isClassExpression(node.parent)) { const enclosingIterationStatement = getEnclosingIterationStatement(node.parent); @@ -77603,7 +77740,7 @@ ${lanes.join("\n")} if (classExtendsNull) { error2(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - const superCallShouldBeRootLevel = (getEmitScriptTarget(compilerOptions) !== 99 /* ESNext */ || !useDefineForClassFields) && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p) => hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */))); + const superCallShouldBeRootLevel = !emitStandardClassFields && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p) => hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */))); if (superCallShouldBeRootLevel) { if (!superCallIsRootLevelInConstructor(superCall, node.body)) { error2(superCall, Diagnostics.A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers); @@ -78456,7 +78593,7 @@ ${lanes.join("\n")} } return typeAsAwaitable.awaitedTypeOfType = type; } - function checkAsyncFunctionReturnType(node, returnTypeNode) { + function checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation) { const returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { if (isErrorType(returnType)) { @@ -78467,7 +78604,7 @@ ${lanes.join("\n")} true ); if (globalPromiseType !== emptyGenericType && !isReferenceToType2(returnType, globalPromiseType)) { - error2(returnTypeNode, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedTypeNoAlias(returnType) || voidType)); + reportErrorForInvalidReturnType(Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, returnTypeNode, returnTypeErrorLocation, typeToString(getAwaitedTypeNoAlias(returnType) || voidType)); return; } } else { @@ -78477,7 +78614,7 @@ ${lanes.join("\n")} } const promiseConstructorName = getEntityNameFromTypeNode(returnTypeNode); if (promiseConstructorName === void 0) { - error2(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, typeToString(returnType)); return; } const promiseConstructorSymbol = resolveEntityName( @@ -78492,9 +78629,9 @@ ${lanes.join("\n")} /*reportErrors*/ false )) { - error2(returnTypeNode, Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + error2(returnTypeErrorLocation, Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { - error2(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, entityNameToString(promiseConstructorName)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); } return; } @@ -78503,15 +78640,16 @@ ${lanes.join("\n")} true ); if (globalPromiseConstructorLikeType === emptyObjectType) { - error2(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, entityNameToString(promiseConstructorName)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); return; } - if (!checkTypeAssignableTo( - promiseConstructorType, - globalPromiseConstructorLikeType, - returnTypeNode, - Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value - )) { + const headMessage = Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value; + const errorInfo = () => returnTypeNode === returnTypeErrorLocation ? void 0 : chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type + ); + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeErrorLocation, headMessage, errorInfo)) { return; } const rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); @@ -78533,6 +78671,14 @@ ${lanes.join("\n")} node, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member ); + function reportErrorForInvalidReturnType(message, returnTypeNode2, returnTypeErrorLocation2, typeName) { + if (returnTypeNode2 === returnTypeErrorLocation2) { + error2(returnTypeErrorLocation2, message, typeName); + } else { + const diag2 = error2(returnTypeErrorLocation2, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + addRelatedInfo(diag2, createDiagnosticForNode(returnTypeNode2, message, typeName)); + } + } } function checkDecorator(node) { const signature = getResolvedSignature(node); @@ -78759,6 +78905,7 @@ ${lanes.join("\n")} for (const parameter of containingSignature.parameters) { markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(containingSignature)); break; } } @@ -79300,7 +79447,7 @@ ${lanes.join("\n")} } function checkWeakMapSetCollision(node) { const enclosingBlockScope = getEnclosingBlockScopeContainer(node); - if (getNodeCheckFlags(enclosingBlockScope) & 4194304 /* ContainsClassWithPrivateIdentifiers */) { + if (getNodeCheckFlags(enclosingBlockScope) & 1048576 /* ContainsClassWithPrivateIdentifiers */) { Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier"); errorSkippedOn("noEmit", node, Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText); } @@ -79314,18 +79461,18 @@ ${lanes.join("\n")} let hasCollision = false; if (isClassExpression(node)) { for (const member of node.members) { - if (getNodeCheckFlags(member) & 8388608 /* ContainsSuperPropertyInStaticInitializer */) { + if (getNodeCheckFlags(member) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { hasCollision = true; break; } } } else if (isFunctionExpression(node)) { - if (getNodeCheckFlags(node) & 8388608 /* ContainsSuperPropertyInStaticInitializer */) { + if (getNodeCheckFlags(node) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { hasCollision = true; } } else { const container = getEnclosingBlockScopeContainer(node); - if (container && getNodeCheckFlags(container) & 8388608 /* ContainsSuperPropertyInStaticInitializer */) { + if (container && getNodeCheckFlags(container) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { hasCollision = true; } } @@ -79360,9 +79507,6 @@ ${lanes.join("\n")} if ((getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */) !== 0 || isParameterDeclaration(node)) { return; } - if (node.kind === 260 /* VariableDeclaration */ && !node.initializer) { - return; - } const symbol = getSymbolOfDeclaration(node); if (symbol.flags & 1 /* FunctionScopedVariable */) { if (!isIdentifier(node.name)) @@ -80872,7 +81016,7 @@ ${lanes.join("\n")} node ); const willTransformPrivateElementsOrClassStaticBlocks = languageVersion <= 9 /* ES2022 */; - const willTransformInitializers = !useDefineForClassFields || languageVersion < 9 /* ES2022 */; + const willTransformInitializers = !emitStandardClassFields; if (willTransformStaticElementsOfDecoratedClass || willTransformPrivateElementsOrClassStaticBlocks) { for (const member of node.members) { if (willTransformStaticElementsOfDecoratedClass && classElementOrClassElementParameterIsDecorated( @@ -81630,10 +81774,22 @@ ${lanes.join("\n")} return +expr.text; case 217 /* ParenthesizedExpression */: return evaluate(expr.expression, location); - case 80 /* Identifier */: - if (isInfinityOrNaNString(expr.escapedText)) { - return +expr.escapedText; + case 80 /* Identifier */: { + const identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText) && resolveEntityName( + identifier, + 111551 /* Value */, + /*ignoreErrors*/ + true + ) === getGlobalSymbol( + identifier.escapedText, + 111551 /* Value */, + /*diagnostic*/ + void 0 + )) { + return +identifier.escapedText; } + } case 211 /* PropertyAccessExpression */: if (isEntityNameExpression(expr)) { const symbol = resolveEntityName( @@ -81972,7 +82128,7 @@ ${lanes.join("\n")} } return; } - const targetFlags = getAllSymbolFlags(target); + const targetFlags = getSymbolFlags(target); const excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) | (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (targetFlags & excludedMeanings) { const message = node.kind === 281 /* ExportSpecifier */ ? Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; @@ -82130,7 +82286,7 @@ ${lanes.join("\n")} if (node.moduleReference.kind !== 283 /* ExternalModuleReference */) { const target = resolveAlias(getSymbolOfDeclaration(node)); if (target !== unknownSymbol) { - const targetFlags = getAllSymbolFlags(target); + const targetFlags = getSymbolFlags(target); if (targetFlags & 111551 /* Value */) { const moduleName = getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { @@ -82270,7 +82426,7 @@ ${lanes.join("\n")} markExportAsReferenced(node); } const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol); - if (!target || getAllSymbolFlags(target) & 111551 /* Value */) { + if (!target || getSymbolFlags(target) & 111551 /* Value */) { checkExpressionCached(node.propertyName || node.name); } } @@ -82315,7 +82471,7 @@ ${lanes.join("\n")} )); if (sym) { markAliasReferenced(sym, id); - if (getAllSymbolFlags(sym) & 111551 /* Value */) { + if (getSymbolFlags(sym) & 111551 /* Value */) { checkExpressionCached(id); if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && getTypeOnlyAliasDeclaration(sym, 111551 /* Value */)) { error2( @@ -82936,7 +83092,7 @@ ${lanes.join("\n")} function copyLocallyVisibleExportSymbols(source, meaning2) { if (meaning2) { source.forEach((symbol) => { - if (!getDeclarationOfKind(symbol, 281 /* ExportSpecifier */) && !getDeclarationOfKind(symbol, 280 /* NamespaceExport */)) { + if (!getDeclarationOfKind(symbol, 281 /* ExportSpecifier */) && !getDeclarationOfKind(symbol, 280 /* NamespaceExport */) && symbol.escapedName !== "default" /* Default */) { copySymbol(symbol, meaning2); } }); @@ -83562,7 +83718,7 @@ ${lanes.join("\n")} return symbolLinks2.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(getAllSymbolFlags(s) & 111551 /* Value */); + return s && !!(getSymbolFlags(s) & 111551 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -83692,7 +83848,11 @@ ${lanes.join("\n")} case 276 /* ImportSpecifier */: case 281 /* ExportSpecifier */: const symbol = getSymbolOfDeclaration(node); - return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */); + return !!symbol && isAliasResolvedToValue( + symbol, + /*excludeTypeOnlyValues*/ + true + ); case 278 /* ExportDeclaration */: const exportClause = node.exportClause; return !!exportClause && (isNamespaceExport(exportClause) || some(exportClause.elements, isValueAliasDeclaration)); @@ -83709,7 +83869,7 @@ ${lanes.join("\n")} const isValue = isAliasResolvedToValue(getSymbolOfDeclaration(node)); return isValue && node.moduleReference && !nodeIsMissing(node.moduleReference); } - function isAliasResolvedToValue(symbol) { + function isAliasResolvedToValue(symbol, excludeTypeOnlyValues) { if (!symbol) { return false; } @@ -83717,7 +83877,12 @@ ${lanes.join("\n")} if (target === unknownSymbol) { return true; } - return !!((getAllSymbolFlags(target) ?? -1) & 111551 /* Value */) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); + return !!(getSymbolFlags( + symbol, + excludeTypeOnlyValues, + /*excludeLocalMeanings*/ + true + ) & 111551 /* Value */) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -83731,7 +83896,7 @@ ${lanes.join("\n")} return true; } const target = getSymbolLinks(symbol).aliasTarget; - if (target && getEffectiveModifierFlags(node) & 1 /* Export */ && getAllSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { + if (target && getEffectiveModifierFlags(node) & 1 /* Export */ && getSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { return true; } } @@ -91353,7 +91518,7 @@ ${lanes.join("\n")} const constantValue = tryGetConstEnumValue(node); if (constantValue !== void 0) { setConstantValue(node, constantValue); - const substitute = typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : factory2.createNumericLiteral(constantValue); + const substitute = typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : constantValue < 0 ? factory2.createPrefixUnaryExpression(41 /* MinusToken */, factory2.createNumericLiteral(Math.abs(constantValue))) : factory2.createNumericLiteral(constantValue); if (!compilerOptions.removeComments) { const originalNode = getOriginalNode(node, isAccessExpression); addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, ` ${safeMultiLineComment(getTextOfNode(originalNode))} `); @@ -91786,6 +91951,11 @@ ${lanes.join("\n")} } } } + function getClassThis() { + const lex = getClassLexicalEnvironment(); + const classThis = lex.classThis ?? lex.classConstructor ?? (currentClassContainer == null ? void 0 : currentClassContainer.name); + return Debug.checkDefined(classThis); + } function transformAutoAccessor(node) { const commentRange = getCommentRange(node); const sourceMapRange = getSourceMapRange(node); @@ -91812,11 +91982,13 @@ ${lanes.join("\n")} setOriginalNode(backingField, node); setEmitFlags(backingField, 3072 /* NoComments */); setSourceMapRange(backingField, sourceMapRange); - const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName); + const receiver = isStatic(node) ? getClassThis() : factory2.createThis(); + const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName, receiver); setOriginalNode(getter, node); setCommentRange(getter, commentRange); setSourceMapRange(getter, sourceMapRange); - const setter = createAccessorPropertySetRedirector(factory2, node, modifiers, setterName); + const setterModifiers = factory2.createModifiersFromModifierFlags(modifiersToFlags(modifiers)); + const setter = createAccessorPropertySetRedirector(factory2, node, setterModifiers, setterName, receiver); setOriginalNode(setter, node); setEmitFlags(setter, 3072 /* NoComments */); setSourceMapRange(setter, sourceMapRange); @@ -92373,6 +92545,7 @@ ${lanes.join("\n")} return filter(node.members, isNonStaticMethodOrAccessorWithPrivateName); } function getClassFacts(node) { + var _a; let facts = 0 /* None */; const original = getOriginalNode(node); if (isClassDeclaration(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) { @@ -92389,6 +92562,8 @@ ${lanes.join("\n")} if (isStatic(member)) { if (member.name && (isPrivateIdentifier(member.name) || isAutoAccessorPropertyDeclaration(member)) && shouldTransformPrivateElementsOrClassStaticBlocks) { facts |= 2 /* NeedsClassConstructorReference */; + } else if (isAutoAccessorPropertyDeclaration(member) && shouldTransformAutoAccessors === -1 /* True */ && !node.name && !((_a = node.emitNode) == null ? void 0 : _a.classThis)) { + facts |= 2 /* NeedsClassConstructorReference */; } if (isPropertyDeclaration(member) || isClassStaticBlockDeclaration(member)) { if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* ContainsLexicalThis */) { @@ -92409,6 +92584,9 @@ ${lanes.join("\n")} containsInstancePrivateElements || (containsInstancePrivateElements = isPrivateIdentifierClassElementDeclaration(member)); } else if (isPrivateIdentifierClassElementDeclaration(member)) { containsInstancePrivateElements = true; + if (resolver.getNodeCheckFlags(member) & 262144 /* ContainsConstructorReference */) { + facts |= 2 /* NeedsClassConstructorReference */; + } } else if (isPropertyDeclaration(member)) { containsPublicInstanceFields = true; containsInitializedPublicInstanceFields || (containsInitializedPublicInstanceFields = !!member.initializer); @@ -92509,10 +92687,11 @@ ${lanes.join("\n")} getClassLexicalEnvironment().classConstructor = factory2.cloneNode(temp); pendingClassReferenceAssignment = factory2.createAssignment(temp, factory2.getInternalName(node)); } - if ((_b = node.emitNode) == null ? void 0 : _b.classThis) { - getClassLexicalEnvironment().classThis = node.emitNode.classThis; - } } + if ((_b = node.emitNode) == null ? void 0 : _b.classThis) { + getClassLexicalEnvironment().classThis = node.emitNode.classThis; + } + const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */; const isExport = hasSyntacticModifier(node, 1 /* Export */); const isDefault = hasSyntacticModifier(node, 1024 /* Default */); let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); @@ -92547,6 +92726,11 @@ ${lanes.join("\n")} ) )); } + const alias = getClassLexicalEnvironment().classConstructor; + if (isClassWithConstructorReference && alias) { + enableSubstitutionForClassAliases(); + classAliases[getOriginalNodeId(node)] = alias; + } const classDecl = factory2.updateClassDeclaration( node, modifiers, @@ -92569,14 +92753,14 @@ ${lanes.join("\n")} var _a, _b, _c; const isDecoratedClassDeclaration = !!(facts & 1 /* ClassWasDecorated */); const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); - const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 1048576 /* ClassWithConstructorReference */; + const classCheckFlags = resolver.getNodeCheckFlags(node); + const isClassWithConstructorReference = classCheckFlags & 262144 /* ContainsConstructorReference */; let temp; function createClassTempVar() { var _a2; if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a2 = node.emitNode) == null ? void 0 : _a2.classThis)) { return getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; } - const classCheckFlags = resolver.getNodeCheckFlags(node); const requiresBlockScopedVar = classCheckFlags & 32768 /* BlockScopedBindingInLoop */; const temp2 = factory2.createTempVariable( requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, @@ -93543,7 +93727,7 @@ ${lanes.join("\n")} } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 2097152 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -94409,7 +94593,7 @@ ${lanes.join("\n")} } } function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 1048576 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */) { enableSubstitutionForClassAliases(); const classAlias = factory2.createUniqueName(node.name && !isGeneratedIdentifier(node.name) ? idText(node.name) : "default"); classAliases[getOriginalNodeId(node)] = classAlias; @@ -94442,7 +94626,7 @@ ${lanes.join("\n")} } function trySubstituteClassAlias(node) { if (classAliases) { - if (resolver.getNodeCheckFlags(node) & 2097152 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -94474,6 +94658,7 @@ ${lanes.join("\n")} endLexicalEnvironment, hoistVariableDeclaration } = context; + const languageVersion = getEmitScriptTarget(context.getCompilerOptions()); let top; let classInfo; let classThis; @@ -95975,6 +96160,17 @@ ${lanes.join("\n")} function transformDecorator(decorator) { const expression = visitNode(decorator.expression, visitor, isExpression); setEmitFlags(expression, 3072 /* NoComments */); + const innerExpression = skipOuterExpressions(expression); + if (isAccessExpression(innerExpression)) { + const { target, thisArg } = factory2.createCallBinding( + expression, + hoistVariableDeclaration, + languageVersion, + /*cacheIdentifiers*/ + true + ); + return factory2.restoreOuterExpressions(expression, factory2.createFunctionBindCall(target, thisArg, [])); + } return expression; } function createDescriptorMethod(original, name, modifiers, asteriskToken, kind, parameters, body) { @@ -99607,10 +99803,10 @@ ${lanes.join("\n")} for (const prop of attr.expression.properties) { if (isSpreadAssignment(prop)) { finishObjectLiteralIfNeeded(); - expressions.push(prop.expression); + expressions.push(Debug.checkDefined(visitNode(prop.expression, visitor, isExpression))); continue; } - properties.push(prop); + properties.push(Debug.checkDefined(visitNode(prop, visitor))); } continue; } @@ -102673,10 +102869,10 @@ ${lanes.join("\n")} name )); const checkFlags = resolver.getNodeCheckFlags(decl); - if (checkFlags & 262144 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { + if (checkFlags & 65536 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { const outParamName = factory2.createUniqueName("out_" + idText(name)); let flags = 0 /* None */; - if (checkFlags & 262144 /* NeedsLoopOutParameter */) { + if (checkFlags & 65536 /* NeedsLoopOutParameter */) { flags |= 1 /* Body */; } if (isForStatement(container)) { @@ -113736,7 +113932,7 @@ ${lanes.join("\n")} return !(expression.numericLiteralFlags & 448 /* WithSpecifier */) && !stringContains(text, tokenToString(25 /* DotToken */)) && !stringContains(text, String.fromCharCode(69 /* E */)) && !stringContains(text, String.fromCharCode(101 /* e */)); } else if (isAccessExpression(expression)) { const constantValue = getConstantValue(expression); - return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue; + return typeof constantValue === "number" && isFinite(constantValue) && constantValue >= 0 && Math.floor(constantValue) === constantValue; } } function emitElementAccessExpression(node) { @@ -116931,14 +117127,14 @@ ${lanes.join("\n")} }); // src/compiler/watchUtilities.ts - function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames2) { if (!host.getDirectories || !host.readDirectory) { return void 0; } const cachedReadDirectoryResult = /* @__PURE__ */ new Map(); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); return { - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, fileExists, readFile: (path, encoding) => host.readFile(path, encoding), directoryExists: host.directoryExists && directoryExists, @@ -117060,7 +117256,7 @@ ${lanes.join("\n")} const rootResult = tryReadDirectory2(rootDir, rootDirPath); let rootSymLinkResult; if (rootResult !== void 0) { - return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); + return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames2, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { @@ -117255,7 +117451,7 @@ ${lanes.join("\n")} program, extraFileExtensions, currentDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 }) { @@ -117271,7 +117467,7 @@ ${lanes.join("\n")} writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); return true; } - if (isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) { + if (isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames2, currentDirectory)) { writeLog(`Project: ${configFileName} Detected excluded file: ${fileOrDirectory}`); return true; } @@ -117328,7 +117524,7 @@ ${lanes.join("\n")} function createExcludeHandlingAddWatch(key) { return (file, cb, flags, options, detailInfo1, detailInfo2) => { var _a; - return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call( + return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call( /*thisArgs*/ void 0, file, @@ -117340,7 +117536,7 @@ ${lanes.join("\n")} ) : excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2); }; } - function useCaseSensitiveFileNames() { + function useCaseSensitiveFileNames2() { return typeof host.useCaseSensitiveFileNames === "boolean" ? host.useCaseSensitiveFileNames : host.useCaseSensitiveFileNames(); } function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) { @@ -119358,6 +119554,14 @@ ${lanes.join("\n")} case 265 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); return "skip"; + case 176 /* Constructor */: + case 174 /* MethodDeclaration */: + case 262 /* FunctionDeclaration */: + if (!node.body) { + diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Signature_declarations_can_only_be_used_in_TypeScript_files)); + return "skip"; + } + return; case 266 /* EnumDeclaration */: const enumKeyword = Debug.checkDefined(tokenToString(94 /* EnumKeyword */)); diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); @@ -121272,6 +121476,9 @@ ${lanes.join("\n")} return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); }, readFile: (f) => directoryStructureHost.readFile(f), + directoryExists: maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: maybeBind(directoryStructureHost, directoryStructureHost.realpath), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: () => host.getCurrentDirectory(), onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || returnUndefined, @@ -124467,12 +124674,12 @@ ${lanes.join("\n")} return true; const isJsonFile = fileExtensionIs(fileName, ".json" /* Json */); const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); - const useCaseSensitiveFileNames = program.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = program.useCaseSensitiveFileNames(); return find((_b = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs, (includeSpec) => { if (isJsonFile && !endsWith(includeSpec, ".json" /* Json */)) return false; const pattern = getPatternFromSpec(includeSpec, basePath, "files"); - return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames).test(fileName); + return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames2).test(fileName); }); } function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) { @@ -124676,7 +124883,7 @@ ${lanes.join("\n")} return result; } function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost = host) { - const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); const compilerHost = { getSourceFile: createGetSourceFile( (fileName, encoding) => !encoding ? compilerHost.readFile(fileName) : host.readFile(fileName, encoding), @@ -124692,8 +124899,8 @@ ${lanes.join("\n")} (path) => host.directoryExists(path) ), getCurrentDirectory: memoize(() => host.getCurrentDirectory()), - useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, - getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames), + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2, + getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames2), getNewLine: () => getNewLineCharacter(getCompilerOptions()), fileExists: (f) => host.fileExists(f), readFile: (f) => host.readFile(f), @@ -124974,7 +125181,7 @@ ${lanes.join("\n")} const sourceFilesCache = /* @__PURE__ */ new Map(); let missingFilePathsRequestedForRelease; let hasChangedCompilerOptions = false; - const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); const currentDirectory = host.getCurrentDirectory(); const { configFileName, optionsToExtend: optionsToExtendForConfigFile = {}, watchOptionsToExtend, extraFileExtensions, createProgram: createProgram2 } = host; let { rootFiles: rootFileNames, options: compilerOptions, watchOptions, projectReferences } = host; @@ -124982,7 +125189,7 @@ ${lanes.join("\n")} let configFileParsingDiagnostics; let canConfigFileJsonReportNoInputFiles = false; let hasChangedConfigFileParsingErrors = false; - const cachedDirectoryStructureHost = configFileName === void 0 ? void 0 : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + const cachedDirectoryStructureHost = configFileName === void 0 ? void 0 : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames2); const directoryStructureHost = cachedDirectoryStructureHost || host; const parseConfigFileHost = parseConfigHostFromCompilerHostLike(host, directoryStructureHost); let newLine = updateNewLine(); @@ -125000,8 +125207,8 @@ ${lanes.join("\n")} Debug.assert(compilerOptions); Debug.assert(rootFileNames); const { watchFile: watchFile2, watchDirectory, writeLog } = createWatchFactory(host, compilerOptions); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); - writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames}`); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); + writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames2}`); let configFileWatcher; if (configFileName) { configFileWatcher = watchFile2(configFileName, scheduleProgramReload, 2e3 /* High */, watchOptions, WatchType.ConfigFile); @@ -125110,7 +125317,6 @@ ${lanes.join("\n")} if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { - debugger; resolutionCache.onChangesAffectModuleResolution(); } } @@ -125507,7 +125713,7 @@ ${lanes.join("\n")} options: compilerOptions, program: getCurrentBuilderProgram() || rootFileNames, currentDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 })) @@ -125597,7 +125803,7 @@ ${lanes.join("\n")} options: config.parsedCommandLine.options, program: config.parsedCommandLine.fileNames, currentDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 })) @@ -128360,6 +128566,8 @@ ${lanes.join("\n")} ScriptElementKind2["enumMemberElement"] = "enum member"; ScriptElementKind2["variableElement"] = "var"; ScriptElementKind2["localVariableElement"] = "local var"; + ScriptElementKind2["variableUsingElement"] = "using"; + ScriptElementKind2["variableAwaitUsingElement"] = "await using"; ScriptElementKind2["functionElement"] = "function"; ScriptElementKind2["localFunctionElement"] = "local function"; ScriptElementKind2["memberFunctionElement"] = "method"; @@ -131047,13 +131255,16 @@ ${lanes.join("\n")} return !(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */); } function getDefaultLikeExportNameFromDeclaration(symbol) { - return firstDefined( - symbol.declarations, - (d) => { - var _a, _b; - return isExportAssignment(d) ? (_a = tryCast(skipOuterExpressions(d.expression), isIdentifier)) == null ? void 0 : _a.text : (_b = tryCast(getNameOfDeclaration(d), isIdentifier)) == null ? void 0 : _b.text; + return firstDefined(symbol.declarations, (d) => { + var _a, _b, _c; + if (isExportAssignment(d)) { + return (_a = tryCast(skipOuterExpressions(d.expression), isIdentifier)) == null ? void 0 : _a.text; } - ); + if (isExportSpecifier(d) && d.symbol.flags === 2097152 /* Alias */) { + return (_b = tryCast(d.propertyName, isIdentifier)) == null ? void 0 : _b.text; + } + return (_c = tryCast(getNameOfDeclaration(d), isIdentifier)) == null ? void 0 : _c.text; + }); } function getSymbolParentOrFail(symbol) { var _a; @@ -131493,10 +131704,10 @@ ${lanes.join("\n")} } function forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, cb) { var _a, _b; - const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); + const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); const excludePatterns = preferences.autoImportFileExcludePatterns && mapDefined(preferences.autoImportFileExcludePatterns, (spec) => { const pattern = getPatternFromSpec(spec, "", "exclude"); - return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames) : void 0; + return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames2) : void 0; }); forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, (module2, file) => cb( module2, @@ -132992,12 +133203,12 @@ ${lanes.join("\n")} function isDocumentRegistryEntry(entry) { return !!entry.sourceFile; } - function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { - return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + function createDocumentRegistry(useCaseSensitiveFileNames2, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory); } - function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory = "", externalCache) { + function createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory = "", externalCache) { const buckets = /* @__PURE__ */ new Map(); - const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); + const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames2); function reportStats() { const bucketInfoArray = arrayFrom(buckets.keys()).filter((name) => name && name.charAt(0) === "_").map((name) => { const entries = buckets.get(name); @@ -133206,12 +133417,12 @@ ${lanes.join("\n")} // src/services/getEditsForFileRename.ts function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { - const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); const newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts_textChanges_exports.ChangeTracker.with({ host, formatContext, preferences }, (changeTracker) => { - updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames2); updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } @@ -133233,7 +133444,7 @@ ${lanes.join("\n")} const rel = getRelativePathFromFile(a0, b0, getCanonicalFileName); return combinePathsSafe(getDirectoryPath(a1), rel); } - function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { + function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames2) { const { configFile } = program.getCompilerOptions(); if (!configFile) return; @@ -133257,10 +133468,10 @@ ${lanes.join("\n")} /*excludes*/ [], includes, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, currentDirectory ); - if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(oldFileOrDirPath) && !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(newFileOrDirPath)) { changeTracker.insertNodeAfter(configFile, last(property.initializer.elements), factory.createStringLiteral(relativePath(newFileOrDirPath))); } return; @@ -133308,7 +133519,7 @@ ${lanes.join("\n")} configDir, path, /*ignoreCase*/ - !useCaseSensitiveFileNames + !useCaseSensitiveFileNames2 ); } } @@ -134260,7 +134471,7 @@ ${lanes.join("\n")} "src/services/sourcemaps.ts"() { "use strict"; init_ts4(); - base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+/=]+)$)?/; } }); @@ -134308,8 +134519,8 @@ ${lanes.join("\n")} diags.push(createDiagnosticForNode(init, Diagnostics.require_call_may_be_converted_to_an_import)); } } - const jsdocTypedefNode = ts_codefix_exports.getJSDocTypedefNode(node); - if (jsdocTypedefNode) { + const jsdocTypedefNodes = ts_codefix_exports.getJSDocTypedefNodes(node); + for (const jsdocTypedefNode of jsdocTypedefNodes) { diags.push(createDiagnosticForNode(jsdocTypedefNode, Diagnostics.JSDoc_typedef_may_be_converted_to_TypeScript_type)); } if (ts_codefix_exports.parameterShouldGetTypeFromJSDoc(node)) { @@ -136315,7 +136526,7 @@ ${lanes.join("\n")} if (!isIdentifier(token)) { return void 0; } - if (isInitializedVariable(parent2) && isVariableDeclarationInVariableStatement(parent2)) { + if (isInitializedVariable(parent2) && isVariableDeclarationInVariableStatement(parent2) && isIdentifier(parent2.name)) { if (((_a = checker.getMergedSymbol(parent2.symbol).declarations) == null ? void 0 : _a.length) !== 1) { return { error: getLocaleSpecificMessage(Diagnostics.Variables_with_multiple_declarations_cannot_be_inlined) }; } @@ -136622,7 +136833,7 @@ ${lanes.join("\n")} const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax); if (typeof targetFile !== "string") { if (targetFile.statements.length > 0) { - changes.insertNodesAfter(targetFile, targetFile.statements[targetFile.statements.length - 1], body); + moveStatementsToTargetFile(changes, program, body, targetFile, toMove); } else { changes.insertNodesAtEndOfFile( targetFile, @@ -136643,7 +136854,7 @@ ${lanes.join("\n")} } } if (importAdder) { - importAdder.writeFixes(changes); + importAdder.writeFixes(changes, quotePreference); } if (imports.length && body.length) { return [ @@ -137209,25 +137420,25 @@ ${lanes.join("\n")} const { file } = context; const range = createTextRangeFromSpan(getRefactorContextSpan(context)); const { statements } = file; - const startNodeIndex = findIndex(statements, (s) => s.end > range.pos); + let startNodeIndex = findIndex(statements, (s) => s.end > range.pos); if (startNodeIndex === -1) return void 0; const startStatement = statements[startNodeIndex]; - if (isNamedDeclaration(startStatement) && startStatement.name && rangeContainsRange(startStatement.name, range)) { - return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; - } const overloadRangeToMove = getOverloadRangeToMove(file, startStatement); if (overloadRangeToMove) { - return overloadRangeToMove; + startNodeIndex = overloadRangeToMove.start; + } + let endNodeIndex = findIndex(statements, (s) => s.end >= range.end, startNodeIndex); + if (endNodeIndex !== -1 && range.end <= statements[endNodeIndex].getStart()) { + endNodeIndex--; + } + const endingOverloadRangeToMove = getOverloadRangeToMove(file, statements[endNodeIndex]); + if (endingOverloadRangeToMove) { + endNodeIndex = endingOverloadRangeToMove.end; } - if (range.pos > startStatement.getStart(file)) - return void 0; - const afterEndNodeIndex = findIndex(statements, (s) => s.end > range.end, startNodeIndex); - if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) - return void 0; return { - toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), - afterLast: afterEndNodeIndex === -1 ? void 0 : statements[afterEndNodeIndex] + toMove: statements.slice(startNodeIndex, endNodeIndex === -1 ? statements.length : endNodeIndex + 1), + afterLast: endNodeIndex === -1 ? void 0 : statements[endNodeIndex + 1] }; } function getStatementsToMove(context) { @@ -137415,16 +137626,79 @@ ${lanes.join("\n")} return false; } } + function moveStatementsToTargetFile(changes, program, statements, targetFile, toMove) { + var _a; + const removedExports = /* @__PURE__ */ new Set(); + const targetExports = (_a = targetFile.symbol) == null ? void 0 : _a.exports; + if (targetExports) { + const checker = program.getTypeChecker(); + const targetToSourceExports = /* @__PURE__ */ new Map(); + for (const node of toMove.all) { + if (isTopLevelDeclarationStatement(node) && hasSyntacticModifier(node, 1 /* Export */)) { + forEachTopLevelDeclaration(node, (declaration) => { + var _a2; + const targetDeclarations = canHaveSymbol(declaration) ? (_a2 = targetExports.get(declaration.symbol.escapedName)) == null ? void 0 : _a2.declarations : void 0; + const exportDeclaration = firstDefined(targetDeclarations, (d) => isExportDeclaration(d) ? d : isExportSpecifier(d) ? tryCast(d.parent.parent, isExportDeclaration) : void 0); + if (exportDeclaration && exportDeclaration.moduleSpecifier) { + targetToSourceExports.set( + exportDeclaration, + (targetToSourceExports.get(exportDeclaration) || /* @__PURE__ */ new Set()).add(declaration) + ); + } + }); + } + } + for (const [exportDeclaration, topLevelDeclarations] of arrayFrom(targetToSourceExports)) { + if (exportDeclaration.exportClause && isNamedExports(exportDeclaration.exportClause) && length(exportDeclaration.exportClause.elements)) { + const elements = exportDeclaration.exportClause.elements; + const updatedElements = filter(elements, (elem) => find(skipAlias(elem.symbol, checker).declarations, (d) => isTopLevelDeclaration(d) && topLevelDeclarations.has(d)) === void 0); + if (length(updatedElements) === 0) { + changes.deleteNode(targetFile, exportDeclaration); + removedExports.add(exportDeclaration); + continue; + } + if (length(updatedElements) < length(elements)) { + changes.replaceNode( + targetFile, + exportDeclaration, + factory.updateExportDeclaration( + exportDeclaration, + exportDeclaration.modifiers, + exportDeclaration.isTypeOnly, + factory.updateNamedExports(exportDeclaration.exportClause, factory.createNodeArray(updatedElements, elements.hasTrailingComma)), + exportDeclaration.moduleSpecifier, + exportDeclaration.assertClause + ) + ); + } + } + } + } + const lastReExport = findLast(targetFile.statements, (n) => isExportDeclaration(n) && !!n.moduleSpecifier && !removedExports.has(n)); + if (lastReExport) { + changes.insertNodesBefore( + targetFile, + lastReExport, + statements, + /*blankLineBetween*/ + true + ); + } else { + changes.insertNodesAfter(targetFile, targetFile.statements[targetFile.statements.length - 1], statements); + } + } function getOverloadRangeToMove(sourceFile, statement) { if (isFunctionLikeDeclaration(statement)) { const declarations = statement.symbol.declarations; if (declarations === void 0 || length(declarations) <= 1 || !contains(declarations, statement)) { return void 0; } + const firstDecl = declarations[0]; const lastDecl = declarations[length(declarations) - 1]; const statementsToMove = mapDefined(declarations, (d) => getSourceFileOfNode(d) === sourceFile && isStatement(d) ? d : void 0); - const end = findLastIndex(sourceFile.statements, (s) => s.end > lastDecl.end); - return { toMove: statementsToMove, afterLast: end >= 0 ? sourceFile.statements[end] : void 0 }; + const end = findIndex(sourceFile.statements, (s) => s.end >= lastDecl.end); + const start = findIndex(sourceFile.statements, (s) => s.end >= firstDecl.end); + return { toMove: statementsToMove, start, end }; } return void 0; } @@ -137471,7 +137745,7 @@ ${lanes.join("\n")} if (host.fileExists(targetFile) && program.getSourceFile(targetFile) === void 0) { return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_statements_to_the_selected_file)); } - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context, context.file, interactiveRefactorArguments.targetFile, program, statements, t, context.host, context.preferences)); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context, context.file, interactiveRefactorArguments.targetFile, context.program, statements, t, context.host, context.preferences)); return { edits, renameFilename: void 0, renameLocation: void 0 }; } return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_to_file_selected_file_is_invalid)); @@ -141450,10 +141724,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} host.log(message); } } - const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const sourceMapper = getSourceMapper({ - useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2, getCurrentDirectory: () => currentDirectory, getProgram, fileExists: maybeBind(host, host.fileExists), @@ -141501,7 +141775,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} getSourceFileByPath: getOrCreateSourceFileByPath, getCancellationToken: () => cancellationToken, getCanonicalFileName, - useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2, getNewLine: () => getNewLineCharacter(newSettings), getDefaultLibFileName: (options2) => host.getDefaultLibFileName(options2), writeFile: noop, @@ -141545,9 +141819,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} compilerHost.getSourceFile = getSourceFileWithCache; (_c = host.setCompilerHost) == null ? void 0 : _c.call(host, compilerHost); const parseConfigHost = { - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, fileExists: (fileName) => compilerHost.fileExists(fileName), readFile: (fileName) => compilerHost.readFile(fileName), + directoryExists: (f) => compilerHost.directoryExists(f), + getDirectories: (f) => compilerHost.getDirectories(f), + realpath: compilerHost.realpath, readDirectory: (...args) => compilerHost.readDirectory(...args), trace: compilerHost.trace, getCurrentDirectory: compilerHost.getCurrentDirectory, @@ -142420,7 +142697,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return result; function escapeRegExp(str) { - return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); + return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&"); } function getTodoCommentsRegExp() { const singleLineCommentStart = /(?:\/\/+\s*)/.source; @@ -148173,23 +148450,60 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }); // src/services/codefixes/convertTypedefToType.ts - function doChange12(changes, node, sourceFile) { - if (isJSDocTypedefTag(node)) { - fixSingleTypeDef(changes, node, sourceFile); - } - } - function fixSingleTypeDef(changes, typeDefNode, sourceFile) { - if (!typeDefNode) + function doChange12(changes, node, sourceFile, newLine, fixAll = false) { + if (!isJSDocTypedefTag(node)) return; - const declaration = createDeclaration(typeDefNode); + const declaration = createDeclaration(node); if (!declaration) return; - const comment = typeDefNode.parent; - changes.replaceNode( - sourceFile, - comment, - declaration + const commentNode = node.parent; + const { leftSibling, rightSibling } = getLeftAndRightSiblings(node); + let pos = commentNode.getStart(); + let prefix = ""; + if (!leftSibling && commentNode.comment) { + pos = findEndOfTextBetween(commentNode, commentNode.getStart(), node.getStart()); + prefix = `${newLine} */${newLine}`; + } + if (leftSibling) { + if (fixAll && isJSDocTypedefTag(leftSibling)) { + pos = node.getStart(); + prefix = ""; + } else { + pos = findEndOfTextBetween(commentNode, leftSibling.getStart(), node.getStart()); + prefix = `${newLine} */${newLine}`; + } + } + let end = commentNode.getEnd(); + let suffix = ""; + if (rightSibling) { + if (fixAll && isJSDocTypedefTag(rightSibling)) { + end = rightSibling.getStart(); + suffix = `${newLine}${newLine}`; + } else { + end = rightSibling.getStart(); + suffix = `${newLine}/**${newLine} * `; + } + } + changes.replaceRange(sourceFile, { pos, end }, declaration, { prefix, suffix }); + } + function getLeftAndRightSiblings(typedefNode) { + const commentNode = typedefNode.parent; + const maxChildIndex = commentNode.getChildCount() - 1; + const currentNodeIndex = commentNode.getChildren().findIndex( + (n) => n.getStart() === typedefNode.getStart() && n.getEnd() === typedefNode.getEnd() ); + const leftSibling = currentNodeIndex > 0 ? commentNode.getChildAt(currentNodeIndex - 1) : void 0; + const rightSibling = currentNodeIndex < maxChildIndex ? commentNode.getChildAt(currentNodeIndex + 1) : void 0; + return { leftSibling, rightSibling }; + } + function findEndOfTextBetween(jsDocComment, from, to) { + const comment = jsDocComment.getText().substring(from - jsDocComment.getStart(), to - jsDocComment.getStart()); + for (let i = comment.length; i > 0; i--) { + if (!/[*/\s]/g.test(comment.substring(i - 1, i))) { + return from + i; + } + } + return to; } function createDeclaration(tag) { var _a; @@ -148210,7 +148524,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const propertySignatures = createSignatureFromTypeLiteral(typeLiteral); if (!some(propertySignatures)) return; - const interfaceDeclaration = factory.createInterfaceDeclaration( + return factory.createInterfaceDeclaration( /*modifiers*/ void 0, typeName, @@ -148220,13 +148534,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} void 0, propertySignatures ); - return interfaceDeclaration; } function createTypeAliasForTypeExpression(typeName, typeExpression) { const typeReference = getSynthesizedDeepClone(typeExpression.type); if (!typeReference) return; - const declaration = factory.createTypeAliasDeclaration( + return factory.createTypeAliasDeclaration( /*modifiers*/ void 0, factory.createIdentifier(typeName), @@ -148234,7 +148547,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} void 0, typeReference ); - return declaration; } function createSignatureFromTypeLiteral(typeLiteral) { const propertyTags = typeLiteral.jsDocPropertyTags; @@ -148254,30 +148566,28 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (typeReference && name) { const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0; - const prop = factory.createPropertySignature( + return factory.createPropertySignature( /*modifiers*/ void 0, name, questionToken, typeReference ); - return prop; } }; - const props = mapDefined(propertyTags, getSignature); - return props; + return mapDefined(propertyTags, getSignature); } function getPropertyName(tag) { return tag.name.kind === 80 /* Identifier */ ? tag.name.text : tag.name.right.text; } - function getJSDocTypedefNode(node) { + function getJSDocTypedefNodes(node) { if (hasJSDocNodes(node)) { - return forEach(node.jsDoc, (node2) => { + return flatMap(node.jsDoc, (doc) => { var _a; - return (_a = node2.tags) == null ? void 0 : _a.find(isJSDocTypedefTag); + return (_a = doc.tags) == null ? void 0 : _a.filter((tag) => isJSDocTypedefTag(tag)); }); } - return void 0; + return []; } var fixId14, errorCodes15; var init_convertTypedefToType = __esm({ @@ -148291,13 +148601,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} fixIds: [fixId14], errorCodes: errorCodes15, getCodeActions(context) { + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); const node = getTokenAtPosition( context.sourceFile, context.span.start ); if (!node) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, node, context.sourceFile)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, node, context.sourceFile, newLineCharacter)); if (changes.length > 0) { return [ createCodeFixAction( @@ -148310,11 +148621,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} ]; } }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes15, (changes, diag2) => { - const node = getTokenAtPosition(diag2.file, diag2.start); - if (node) - doChange12(changes, node, diag2.file); - }) + getAllCodeActions: (context) => codeFixAll( + context, + errorCodes15, + (changes, diag2) => { + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); + const node = getTokenAtPosition(diag2.file, diag2.start); + const fixAll = true; + if (node) + doChange12(changes, node, diag2.file, newLineCharacter, fixAll); + } + ) }); } }); @@ -148627,8 +148944,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return `${topLevelTypeOnly ? 1 : 0}|${moduleSpecifier}`; } } - function writeFixes(changeTracker) { - const quotePreference = getQuotePreference(sourceFile, preferences); + function writeFixes(changeTracker, oldFileQuotePreference) { + let quotePreference; + if (sourceFile.imports.length === 0 && oldFileQuotePreference !== void 0) { + quotePreference = oldFileQuotePreference; + } else { + quotePreference = getQuotePreference(sourceFile, preferences); + } for (const fix of addToNamespace) { addNamespaceQualifier(changeTracker, sourceFile, fix); } @@ -148931,6 +149253,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (compilerOptions.configFile) { return getEmitModuleKind(compilerOptions) < 5 /* ES2015 */; } + if (sourceFile.impliedNodeFormat === 1 /* CommonJS */) + return true; + if (sourceFile.impliedNodeFormat === 99 /* ESNext */) + return false; for (const otherFile of program.getSourceFiles()) { if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) continue; @@ -149403,6 +149729,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function promoteImportClause(importClause) { changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(importClause, sourceFile)); + if (!compilerOptions.allowImportingTsExtensions) { + const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(importClause.parent); + const resolvedModule = moduleSpecifier && getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation(sourceFile, moduleSpecifier)); + if (resolvedModule == null ? void 0 : resolvedModule.resolvedUsingTsExtension) { + const changedExtension = changeAnyExtension(moduleSpecifier.text, getOutputExtension(moduleSpecifier.text, compilerOptions)); + changes.replaceNode(sourceFile, moduleSpecifier, factory.createStringLiteral(changedExtension)); + } + } if (convertExistingToTypeOnly) { const namedImports = tryCast(importClause.namedBindings, isNamedImports); if (namedImports && namedImports.elements.length > 1) { @@ -150580,6 +150914,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!declaration || !isCallExpression(declaration.parent) || !declaration.body) return void 0; const pos = declaration.parent.arguments.indexOf(declaration); + if (pos === -1) + return void 0; const type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos); if (!type) return void 0; @@ -151676,7 +152012,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} ); } function getSuggestion(messageText) { - const [_, suggestion] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/\'(.*)\'/) || []; + const [_, suggestion] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/'(.*)'/) || []; return suggestion; } var fixId28, errorCodes34; @@ -154005,15 +154341,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement, body, preserveOptional = 3 /* All */, isAmbient = false) { const declarations = symbol.getDeclarations(); - const declaration = declarations == null ? void 0 : declarations[0]; + const declaration = firstOrUndefined(declarations); const checker = context.program.getTypeChecker(); const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); const kind = (declaration == null ? void 0 : declaration.kind) ?? 171 /* PropertySignature */; - const declarationName = getSynthesizedDeepClone( - getNameOfDeclaration(declaration), - /*includeTrivia*/ - false - ); + const declarationName = createDeclarationName(symbol, declaration); const effectiveModifierFlags = declaration ? getEffectiveModifierFlags(declaration) : 0 /* None */; let modifierFlags = effectiveModifierFlags & 32 /* Static */; modifierFlags |= effectiveModifierFlags & 4 /* Public */ ? 4 /* Public */ : effectiveModifierFlags & 16 /* Protected */ ? 16 /* Protected */ : 0 /* None */; @@ -154164,6 +154496,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} false ); } + function createDeclarationName(symbol2, declaration2) { + if (getCheckFlags(symbol2) & 262144 /* Mapped */) { + const nameType = symbol2.links.nameType; + if (nameType && isTypeUsableAsPropertyName(nameType)) { + return factory.createIdentifier(unescapeLeadingUnderscores(getPropertyNameFromType(nameType))); + } + } + return getSynthesizedDeepClone( + getNameOfDeclaration(declaration2), + /*includeTrivia*/ + false + ); + } } function createSignatureDeclarationFromSignature(kind, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder) { const program = context.program; @@ -155819,7 +156164,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} getFixes: () => getFixes, getImportCompletionAction: () => getImportCompletionAction, getImportKind: () => getImportKind, - getJSDocTypedefNode: () => getJSDocTypedefNode, + getJSDocTypedefNodes: () => getJSDocTypedefNodes, getNoopSymbolTrackerWithResolver: () => getNoopSymbolTrackerWithResolver, getPromoteTypeOnlyCompletionAction: () => getPromoteTypeOnlyCompletionAction, getSupportedErrorCodes: () => getSupportedErrorCodes, @@ -156882,6 +157227,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} data = originToCompletionEntryData(origin); hasAction = !importStatementCompletion; } + const parentNamedImportOrExport = findAncestor(location, isNamedImportsOrExports); + if ((parentNamedImportOrExport == null ? void 0 : parentNamedImportOrExport.kind) === 275 /* NamedImports */) { + const possibleToken = stringToToken(name); + if (parentNamedImportOrExport && possibleToken && (possibleToken === 135 /* AwaitKeyword */ || isNonContextualKeyword(possibleToken))) { + insertText = `${name} as ${name}_`; + } + } return { name, kind: ts_SymbolDisplay_exports.getSymbolKind(typeChecker, symbol, location), @@ -157662,7 +158014,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source, cancellationToken) { if (data == null ? void 0 : data.moduleSpecifier) { - if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken).replacementSpan) { + if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken, sourceFile).replacementSpan) { return { codeActions: void 0, sourceDisplay: [textPart(data.moduleSpecifier)] }; } } @@ -157829,7 +158181,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return { kind: 1 /* JsDocTagName */ }; } else { const lineStart = getLineStartPositionForPosition(position, sourceFile); - if (!/[^\*|\s(/)]/.test(sourceFile.text.substring(lineStart, position))) { + if (!/[^*|\s(/)]/.test(sourceFile.text.substring(lineStart, position))) { return { kind: 2 /* JsDocTag */ }; } } @@ -157875,7 +158227,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let isNewIdentifierLocation = false; let flags = 0 /* None */; if (contextToken) { - const importStatementCompletionInfo = getImportStatementCompletionInfo(contextToken); + const importStatementCompletionInfo = getImportStatementCompletionInfo(contextToken, sourceFile); if (importStatementCompletionInfo.keywordCompletion) { if (importStatementCompletionInfo.isKeywordOnlyCompletion) { return { @@ -158128,24 +158480,34 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } } - if (!isTypeLocation) { + if (!isTypeLocation || isInTypeQuery(node)) { typeChecker.tryGetThisTypeAt( node, /*includeGlobalThis*/ false ); let type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); - let insertQuestionDot = false; - if (type.isNullableType()) { - const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false; - if (canCorrectToQuestionDot || isRightOfQuestionDot) { - type = type.getNonNullableType(); - if (canCorrectToQuestionDot) { - insertQuestionDot = true; + if (!isTypeLocation) { + let insertQuestionDot = false; + if (type.isNullableType()) { + const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } } } + addTypeProperties(type, !!(node.flags & 65536 /* AwaitContext */), insertQuestionDot); + } else { + addTypeProperties( + type.getNonNullableType(), + /*insertAwait*/ + false, + /*insertQuestionDot*/ + false + ); } - addTypeProperties(type, !!(node.flags & 65536 /* AwaitContext */), insertQuestionDot); } } function addTypeProperties(type, insertAwait, insertQuestionDot) { @@ -158191,7 +158553,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const leftMostName = getLeftMostName(computedPropertyName.expression); const nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); const firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); - if (firstAccessibleSymbol && addToSeen(seenPropertySymbols, getSymbolId(firstAccessibleSymbol))) { + const firstAccessibleSymbolId = firstAccessibleSymbol && getSymbolId(firstAccessibleSymbol); + if (firstAccessibleSymbolId && addToSeen(seenPropertySymbols, firstAccessibleSymbolId)) { const index = symbols.length; symbols.push(firstAccessibleSymbol); const moduleSymbol = firstAccessibleSymbol.parent; @@ -158221,6 +158584,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } } else if (preferences.includeCompletionsWithInsertText) { + if (firstAccessibleSymbolId && seenPropertySymbols.has(firstAccessibleSymbolId)) { + return; + } addSymbolOriginInfo(symbol); addSymbolSortInfo(symbol); symbols.push(symbol); @@ -159350,6 +159716,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return cls; } break; + case 81 /* PrivateIdentifier */: + if (tryCast(location.parent, isPropertyDeclaration)) { + return findAncestor(location, isClassLike); + } + break; case 80 /* Identifier */: { const originalKeywordKind = identifierToKeywordKind(location); if (originalKeywordKind) { @@ -159506,7 +159877,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return void 0; } - function getImportStatementCompletionInfo(contextToken) { + function getImportStatementCompletionInfo(contextToken, sourceFile) { var _a, _b, _c; let keywordCompletion; let isKeywordOnlyCompletion = false; @@ -159522,6 +159893,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getCandidate() { const parent2 = contextToken.parent; if (isImportEqualsDeclaration(parent2)) { + const lastToken = parent2.getLastToken(sourceFile); + if (isIdentifier(contextToken) && lastToken !== contextToken) { + keywordCompletion = 161 /* FromKeyword */; + isKeywordOnlyCompletion = true; + return void 0; + } keywordCompletion = contextToken.kind === 156 /* TypeKeyword */ ? void 0 : 156 /* TypeKeyword */; return isModuleSpecifierMissingOrEmpty(parent2.moduleReference) ? parent2 : void 0; } @@ -160089,7 +160466,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} extensionOptions, host, /*moduleSpecifierIsRelative*/ - false, + true, scriptPath ).values()); } @@ -160421,16 +160798,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const fragmentDirectory = fragmentHasPath ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0; const expandedPrefixDirectory = fragmentHasPath ? combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; const normalizedSuffix = normalizePath(parsed.suffix); + const declarationExtension = normalizedSuffix && getDeclarationEmitExtensionForPath("_" + normalizedSuffix); + const matchingSuffixes = declarationExtension ? [changeExtension(normalizedSuffix, declarationExtension), normalizedSuffix] : [normalizedSuffix]; const baseDirectory = normalizePath(combinePaths(packageDirectory, expandedPrefixDirectory)); const completePrefix = fragmentHasPath ? baseDirectory : ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - const includeGlob = normalizedSuffix ? "**/*" + normalizedSuffix : "./*"; + const includeGlobs = normalizedSuffix ? matchingSuffixes.map((suffix) => "**/*" + suffix) : ["./*"]; const matches = mapDefined(tryReadDirectory( host, baseDirectory, extensionOptions.extensionsToSearch, /*exclude*/ void 0, - [includeGlob] + includeGlobs ), (match) => { const trimmedWithPattern = trimPrefixAndSuffix(match); if (trimmedWithPattern) { @@ -160444,8 +160823,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const directories = normalizedSuffix ? emptyArray : mapDefined(tryGetDirectories(host, baseDirectory), (dir) => dir === "node_modules" ? void 0 : directoryResult(dir)); return [...matches, ...directories]; function trimPrefixAndSuffix(path) { - const inner = withoutStartAndEnd(normalizePath(path), completePrefix, normalizedSuffix); - return inner === void 0 ? void 0 : removeLeadingDirectorySeparator(inner); + return firstDefined(matchingSuffixes, (suffix) => { + const inner = withoutStartAndEnd(normalizePath(path), completePrefix, suffix); + return inner === void 0 ? void 0 : removeLeadingDirectorySeparator(inner); + }); } } function withoutStartAndEnd(s, start, end) { @@ -163674,6 +164055,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function shouldShowLiteralParameterNameHintsOnly(preferences) { return preferences.includeInlayParameterNameHints === "literals"; } + function shouldUseInteractiveInlayHints(preferences) { + return preferences.interactiveInlayHints === true; + } function provideInlayHints(context) { const { file, program, span, cancellationToken, preferences } = context; const sourceFileText = file.text; @@ -163724,17 +164108,26 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function isSignatureSupportingReturnAnnotation(node) { return isArrowFunction(node) || isFunctionExpression(node) || isFunctionDeclaration(node) || isMethodDeclaration(node) || isGetAccessorDeclaration(node); } - function addParameterHints(text, position, isFirstVariadicArgument) { + function addParameterHints(text, parameter, position, isFirstVariadicArgument, sourceFile) { + let hintText = `${isFirstVariadicArgument ? "..." : ""}${text}`; + let displayParts; + if (shouldUseInteractiveInlayHints(preferences)) { + displayParts = [getNodeDisplayPart(hintText, parameter, sourceFile), { text: ":" }]; + hintText = ""; + } else { + hintText += ":"; + } result.push({ - text: `${isFirstVariadicArgument ? "..." : ""}${truncation(text, maxHintsLength)}:`, + text: hintText, position, kind: "Parameter" /* Parameter */, - whitespaceAfter: true + whitespaceAfter: true, + displayParts }); } function addTypeHints(text, position) { result.push({ - text: `: ${truncation(text, maxHintsLength)}`, + text: `: ${text.length > maxTypeHintLength ? text.substr(0, maxTypeHintLength - "...".length) + "..." : text}`, position, kind: "Type" /* Type */, whitespaceBefore: true @@ -163742,7 +164135,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function addEnumMemberValueHints(text, position) { result.push({ - text: `= ${truncation(text, maxHintsLength)}`, + text: `= ${text}`, position, kind: "Enum" /* Enum */, whitespaceBefore: true @@ -163792,6 +164185,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return; } let signatureParamPos = 0; + const sourceFile = shouldUseInteractiveInlayHints(preferences) ? expr.getSourceFile() : void 0; for (const originalArg of args) { const arg = skipParentheses(originalArg); if (shouldShowLiteralParameterNameHintsOnly(preferences) && !isHintableLiteral(arg)) { @@ -163812,10 +164206,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } } - const identifierNameInfo = checker.getParameterIdentifierNameAtPosition(signature, signatureParamPos); + const identifierInfo = checker.getParameterIdentifierInfoAtPosition(signature, signatureParamPos); signatureParamPos = signatureParamPos + (spreadArgs || 1); - if (identifierNameInfo) { - const [parameterName, isFirstVariadicArgument] = identifierNameInfo; + if (identifierInfo) { + const { parameter, parameterName, isRestParameter: isFirstVariadicArgument } = identifierInfo; const isParameterNameNotSameAsArgument = preferences.includeInlayParameterNameHintsWhenArgumentMatchesName || !identifierOrAccessExpressionPostfixMatchesParameterName(arg, parameterName); if (!isParameterNameNotSameAsArgument && !isFirstVariadicArgument) { continue; @@ -163824,7 +164218,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (leadingCommentsContainsParameterName(arg, name)) { continue; } - addParameterHints(name, originalArg.getStart(), isFirstVariadicArgument); + addParameterHints(name, parameter, originalArg.getStart(), isFirstVariadicArgument, sourceFile); } } } @@ -163930,12 +164324,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return printTypeInSingleLine(signatureParamType); } - function truncation(text, maxLength2) { - if (text.length > maxLength2) { - return text.substr(0, maxLength2 - "...".length) + "..."; - } - return text; - } function printTypeInSingleLine(type) { const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; const printer = createPrinterWithRemoveComments(); @@ -163966,13 +164354,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return true; } + function getNodeDisplayPart(text, node, sourceFile) { + return { + text, + span: createTextSpanFromNode(node, sourceFile), + file: sourceFile.fileName + }; + } } - var maxHintsLength, leadingParameterNameCommentRegexFactory; + var maxTypeHintLength, leadingParameterNameCommentRegexFactory; var init_inlayHints = __esm({ "src/services/inlayHints.ts"() { "use strict"; init_ts4(); - maxHintsLength = 30; + maxTypeHintLength = 30; leadingParameterNameCommentRegexFactory = (name) => { return new RegExp(`^\\s?/\\*\\*?\\s?${name}\\s?\\*\\/\\s?$`); }; @@ -166403,6 +166798,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return "parameter" /* parameterElement */; } else if (symbol.valueDeclaration && isVarConst(symbol.valueDeclaration)) { return "const" /* constElement */; + } else if (symbol.valueDeclaration && isVarUsing(symbol.valueDeclaration)) { + return "using" /* variableUsingElement */; + } else if (symbol.valueDeclaration && isVarAwaitUsing(symbol.valueDeclaration)) { + return "await using" /* variableAwaitUsingElement */; } else if (forEach(symbol.declarations, isLet)) { return "let" /* letElement */; } @@ -166470,7 +166869,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return modifiers.size > 0 ? arrayFrom(modifiers.values()).join(",") : "" /* none */; } - function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning = getMeaningFromLocation(location), alias) { + function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, symbol, sourceFile, enclosingDeclaration, location, type, semanticMeaning, alias) { var _a; const displayParts = []; let documentation = []; @@ -166479,7 +166878,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; let hasAddedSymbolInfo = false; const isThisExpression = location.kind === 110 /* ThisKeyword */ && isInExpressionContext(location) || isThisInTypeQuery(location); - let type; let documentationFromAlias; let tagsFromAlias; let hasMultipleSignatures = false; @@ -166508,7 +166906,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } let signature; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + type ?? (type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location)); if (location.parent && location.parent.kind === 211 /* PropertyAccessExpression */) { const right = location.parent.name; if (right === location || right && right.getFullWidth() === 0) { @@ -166723,12 +167121,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (declarationName && !hasAddedSymbolInfo) { const isExternalModuleDeclaration = isModuleWithStringLiteralName(resolvedNode) && hasSyntacticModifier(resolvedNode, 2 /* Ambient */); const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; - const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind( + const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKindWorker( typeChecker, resolvedSymbol, getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, + type, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol ); @@ -166796,7 +167195,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); } - if (symbolKind === "property" /* memberVariableElement */ || symbolKind === "accessor" /* memberAccessorVariableElement */ || symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */ || symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || symbolKind === "index" /* indexSignatureElement */ || isThisExpression) { + if (symbolKind === "property" /* memberVariableElement */ || symbolKind === "accessor" /* memberAccessorVariableElement */ || symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */ || symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || symbolKind === "index" /* indexSignatureElement */ || symbolKind === "using" /* variableUsingElement */ || symbolKind === "await using" /* variableAwaitUsingElement */ || isThisExpression) { displayParts.push(punctuationPart(59 /* ColonToken */)); displayParts.push(spacePart()); if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */ && symbolKind !== "index" /* indexSignatureElement */) { @@ -166946,6 +167345,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case "let" /* letElement */: case "const" /* constElement */: case "constructor" /* constructorImplementationElement */: + case "using" /* variableUsingElement */: + case "await using" /* variableAwaitUsingElement */: displayParts.push(textOrKeywordPart(symbolKind2)); return; default: @@ -166981,6 +167382,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} addRange(displayParts, typeParameterParts); } } + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning = getMeaningFromLocation(location), alias) { + return getSymbolDisplayPartsDocumentationAndSymbolKindWorker( + typeChecker, + symbol, + sourceFile, + enclosingDeclaration, + location, + /*type*/ + void 0, + semanticMeaning, + alias + ); + } function isLocalVariableOrFunction(symbol) { if (symbol.parent) { return false; @@ -167760,6 +168174,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} insertNodeBefore(sourceFile, before, newNode, blankLineBetween = false, options = {}) { this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNode, this.getOptionsForInsertNodeBefore(before, newNode, blankLineBetween)); } + insertNodesBefore(sourceFile, before, newNodes, blankLineBetween = false, options = {}) { + this.insertNodesAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNodes, this.getOptionsForInsertNodeBefore(before, first(newNodes), blankLineBetween)); + } insertModifierAt(sourceFile, pos, modifier, options = {}) { this.insertNodeAt(sourceFile, pos, factory.createToken(modifier), options); } @@ -174400,7 +174817,7 @@ ${options.prefix}` : "\n" : options.prefix return this.projectService.includePackageJsonAutoImports(); } /** @internal */ - getModuleResolutionHostForAutoImportProvider() { + getHostForAutoImportProvider() { var _a, _b; if (this.program) { return { @@ -174411,7 +174828,8 @@ ${options.prefix}` : "\n" : options.prefix readFile: this.projectService.host.readFile.bind(this.projectService.host), getDirectories: this.projectService.host.getDirectories.bind(this.projectService.host), trace: (_b = this.projectService.host.trace) == null ? void 0 : _b.bind(this.projectService.host), - useCaseSensitiveFileNames: this.program.useCaseSensitiveFileNames() + useCaseSensitiveFileNames: this.program.useCaseSensitiveFileNames(), + readDirectory: this.projectService.host.readDirectory.bind(this.projectService.host) }; } return this.projectService.host; @@ -174439,7 +174857,7 @@ ${options.prefix}` : "\n" : options.prefix if (dependencySelection) { (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "getPackageJsonAutoImportProvider"); const start = timestamp(); - this.autoImportProviderHost = AutoImportProviderProject.create(dependencySelection, this, this.getModuleResolutionHostForAutoImportProvider(), this.documentRegistry); + this.autoImportProviderHost = AutoImportProviderProject.create(dependencySelection, this, this.getHostForAutoImportProvider(), this.documentRegistry); if (this.autoImportProviderHost) { updateProjectIfDirty(this.autoImportProviderHost); this.sendPerformanceEvent("CreatePackageJsonAutoImportProvider", timestamp() - start); @@ -174655,7 +175073,7 @@ ${options.prefix}` : "\n" : options.prefix this.getParsedCommandLine = maybeBind(this.hostProject, this.hostProject.getParsedCommandLine); } /** @internal */ - static getRootFileNames(dependencySelection, hostProject, moduleResolutionHost, compilerOptions) { + static getRootFileNames(dependencySelection, hostProject, host, compilerOptions) { var _a, _b; if (!dependencySelection) { return emptyArray; @@ -174685,7 +175103,7 @@ ${options.prefix}` : "\n" : options.prefix name, hostProject.currentDirectory, compilerOptions, - moduleResolutionHost, + host, program.getModuleResolutionCache() ); if (packageJson) { @@ -174702,7 +175120,7 @@ ${options.prefix}` : "\n" : options.prefix `@types/${name}`, directory, compilerOptions, - moduleResolutionHost, + host, program.getModuleResolutionCache() ); if (typesPackageJson) { @@ -174742,12 +175160,12 @@ ${options.prefix}` : "\n" : options.prefix const entrypoints = getEntrypointsFromPackageJsonInfo( packageJson, compilerOptions, - moduleResolutionHost, + host, program2.getModuleResolutionCache(), resolveJs ); if (entrypoints) { - const real = (_a2 = moduleResolutionHost.realpath) == null ? void 0 : _a2.call(moduleResolutionHost, packageJson.packageDirectory); + const real = (_a2 = host.realpath) == null ? void 0 : _a2.call(host, packageJson.packageDirectory); const isSymlink = real && real !== packageJson.packageDirectory; if (isSymlink) { symlinkCache.setSymlinkedDirectory(packageJson.packageDirectory, { @@ -174765,7 +175183,7 @@ ${options.prefix}` : "\n" : options.prefix } } /** @internal */ - static create(dependencySelection, hostProject, moduleResolutionHost, documentRegistry) { + static create(dependencySelection, hostProject, host, documentRegistry) { if (dependencySelection === 0 /* Off */) { return void 0; } @@ -174773,7 +175191,7 @@ ${options.prefix}` : "\n" : options.prefix ...hostProject.getCompilerOptions(), ...this.compilerOptionsOverrides }; - const rootNames = this.getRootFileNames(dependencySelection, hostProject, moduleResolutionHost, compilerOptions); + const rootNames = this.getRootFileNames(dependencySelection, hostProject, host, compilerOptions); if (!rootNames.length) { return void 0; } @@ -174792,7 +175210,7 @@ ${options.prefix}` : "\n" : options.prefix rootFileNames = _AutoImportProviderProject.getRootFileNames( this.hostProject.includePackageJsonAutoImports(), this.hostProject, - this.hostProject.getModuleResolutionHostForAutoImportProvider(), + this.hostProject.getHostForAutoImportProvider(), this.getCompilationSettings() ); } @@ -174831,7 +175249,7 @@ ${options.prefix}` : "\n" : options.prefix onPackageJsonChange() { throw new Error("package.json changes should be notified on an AutoImportProvider's host project"); } - getModuleResolutionHostForAutoImportProvider() { + getHostForAutoImportProvider() { throw new Error("AutoImportProviderProject cannot provide its own host; use `hostProject.getModuleResolutionHostForAutomImportProvider()` instead."); } getProjectReferences() { @@ -175388,7 +175806,7 @@ ${options.prefix}` : "\n" : options.prefix 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": { @@ -178116,7 +178534,7 @@ Dynamic files must always be opened with service's current directory or service } } if (!exclude) { - if (/^.+[\.-]min\.js$/.test(normalizedNames[i])) { + if (/^.+[.-]min\.js$/.test(normalizedNames[i])) { excludedFiles.push(normalizedNames[i]); } else { filesToKeep.push(proj.rootFiles[i]); @@ -178437,7 +178855,7 @@ Dynamic files must always be opened with service's current directory or service } }; /** Makes a filename safe to insert in a RegExp */ - _ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; + _ProjectService.filenameEscapeRegexp = /[-/\\^$*+?.()|[\]{}]/g; ProjectService3 = _ProjectService; } }); @@ -180650,10 +181068,21 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const { file, project } = this.getFileAndProject(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); const hints = project.getLanguageService().provideInlayHints(file, args, this.getPreferences(file)); - return hints.map((hint) => ({ - ...hint, - position: scriptInfo.positionToLineOffset(hint.position) - })); + return hints.map((hint) => { + const { position, displayParts } = hint; + return { + ...hint, + position: scriptInfo.positionToLineOffset(position), + displayParts: displayParts == null ? void 0 : displayParts.map(({ text, span, file: file2 }) => ({ + text, + span: span && { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(span.start + span.length), + file: file2 + } + })) + }; + }); } setCompilerOptionsForInferredProjects(args) { this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath); @@ -183467,6 +183896,7 @@ ${e.message}`; getEmitModuleKind: () => getEmitModuleKind, getEmitModuleResolutionKind: () => getEmitModuleResolutionKind, getEmitScriptTarget: () => getEmitScriptTarget, + getEmitStandardClassFields: () => getEmitStandardClassFields, getEnclosingBlockScopeContainer: () => getEnclosingBlockScopeContainer, getEnclosingContainer: () => getEnclosingContainer, getEncodedSemanticClassifications: () => getEncodedSemanticClassifications, @@ -183686,6 +184116,7 @@ ${e.message}`; getPropertyAssignmentAliasLikeExpression: () => getPropertyAssignmentAliasLikeExpression, getPropertyNameForPropertyNameNode: () => getPropertyNameForPropertyNameNode, getPropertyNameForUniqueESSymbol: () => getPropertyNameForUniqueESSymbol, + getPropertyNameFromType: () => getPropertyNameFromType, getPropertyNameOfBindingOrAssignmentElement: () => getPropertyNameOfBindingOrAssignmentElement, getPropertySymbolFromBindingElement: () => getPropertySymbolFromBindingElement, getPropertySymbolsFromContextualType: () => getPropertySymbolsFromContextualType, @@ -184141,6 +184572,7 @@ ${e.message}`; isInString: () => isInString, isInTemplateString: () => isInTemplateString, isInTopLevelContext: () => isInTopLevelContext, + isInTypeQuery: () => isInTypeQuery, isIncrementalCompilation: () => isIncrementalCompilation, isIndexSignatureDeclaration: () => isIndexSignatureDeclaration, isIndexedAccessTypeNode: () => isIndexedAccessTypeNode, @@ -184518,6 +184950,7 @@ ${e.message}`; isTypeQueryNode: () => isTypeQueryNode, isTypeReferenceNode: () => isTypeReferenceNode, isTypeReferenceType: () => isTypeReferenceType, + isTypeUsableAsPropertyName: () => isTypeUsableAsPropertyName, isUMDExportSymbol: () => isUMDExportSymbol, isUnaryExpression: () => isUnaryExpression, isUnaryExpressionWithWrite: () => isUnaryExpressionWithWrite, @@ -185870,6 +186303,7 @@ ${e.message}`; getEmitModuleKind: () => getEmitModuleKind, getEmitModuleResolutionKind: () => getEmitModuleResolutionKind, getEmitScriptTarget: () => getEmitScriptTarget, + getEmitStandardClassFields: () => getEmitStandardClassFields, getEnclosingBlockScopeContainer: () => getEnclosingBlockScopeContainer, getEnclosingContainer: () => getEnclosingContainer, getEncodedSemanticClassifications: () => getEncodedSemanticClassifications, @@ -186089,6 +186523,7 @@ ${e.message}`; getPropertyAssignmentAliasLikeExpression: () => getPropertyAssignmentAliasLikeExpression, getPropertyNameForPropertyNameNode: () => getPropertyNameForPropertyNameNode, getPropertyNameForUniqueESSymbol: () => getPropertyNameForUniqueESSymbol, + getPropertyNameFromType: () => getPropertyNameFromType, getPropertyNameOfBindingOrAssignmentElement: () => getPropertyNameOfBindingOrAssignmentElement, getPropertySymbolFromBindingElement: () => getPropertySymbolFromBindingElement, getPropertySymbolsFromContextualType: () => getPropertySymbolsFromContextualType, @@ -186544,6 +186979,7 @@ ${e.message}`; isInString: () => isInString, isInTemplateString: () => isInTemplateString, isInTopLevelContext: () => isInTopLevelContext, + isInTypeQuery: () => isInTypeQuery, isIncrementalCompilation: () => isIncrementalCompilation, isIndexSignatureDeclaration: () => isIndexSignatureDeclaration, isIndexedAccessTypeNode: () => isIndexedAccessTypeNode, @@ -186921,6 +187357,7 @@ ${e.message}`; isTypeQueryNode: () => isTypeQueryNode, isTypeReferenceNode: () => isTypeReferenceNode, isTypeReferenceType: () => isTypeReferenceType, + isTypeUsableAsPropertyName: () => isTypeUsableAsPropertyName, isUMDExportSymbol: () => isUMDExportSymbol, isUnaryExpression: () => isUnaryExpression, isUnaryExpressionWithWrite: () => isUnaryExpressionWithWrite, diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index a00cc6edf7731..ead6d07d8fb2a 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -1774,9 +1774,11 @@ declare namespace ts { }; }) | ExportDeclaration & { readonly isTypeOnly: true; + readonly moduleSpecifier: Expression; } | NamespaceExport & { readonly parent: ExportDeclaration & { readonly isTypeOnly: true; + readonly moduleSpecifier: Expression; }; }; type TypeOnlyAliasDeclaration = TypeOnlyImportDeclaration | TypeOnlyExportDeclaration; @@ -2221,7 +2223,7 @@ declare namespace ts { getSourceFileByPath(path: Path): SourceFile | undefined; getCurrentDirectory(): string; } - interface ParseConfigHost { + interface ParseConfigHost extends ModuleResolutionHost { useCaseSensitiveFileNames: boolean; readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[], depth?: number): readonly string[]; /** @@ -4347,6 +4349,7 @@ declare namespace ts { readonly includeInlayPropertyDeclarationTypeHints?: boolean; readonly includeInlayFunctionLikeReturnTypeHints?: boolean; readonly includeInlayEnumMemberValueHints?: boolean; + readonly interactiveInlayHints?: boolean; readonly allowRenameOfImportPath?: boolean; readonly autoImportFileExcludePatterns?: string[]; readonly organizeImportsIgnoreCase?: "auto" | boolean; @@ -6413,11 +6416,18 @@ declare namespace ts { Enum = "Enum" } interface InlayHint { + /** This property will be the empty string when displayParts is set. */ text: string; position: number; kind: InlayHintKind; whitespaceBefore?: boolean; whitespaceAfter?: boolean; + displayParts?: InlayHintDisplayPart[]; + } + interface InlayHintDisplayPart { + text: string; + span?: TextSpan; + file?: string; } interface TodoCommentDescriptor { text: string; @@ -7009,6 +7019,10 @@ declare namespace ts { variableElement = "var", /** Inside function */ localVariableElement = "local var", + /** using foo = ... */ + variableUsingElement = "using", + /** await using foo = ... */ + variableAwaitUsingElement = "await using", /** * Inside module and script only * function f() { } diff --git a/lib/typescript.js b/lib/typescript.js index 5507168f77787..5361e5bb19b2b 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -1464,8 +1464,8 @@ var ts = (() => { } return false; } - function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames ? identity : toFileNameLowerCase; + function createGetCanonicalFileName(useCaseSensitiveFileNames2) { + return useCaseSensitiveFileNames2 ? identity : toFileNameLowerCase; } function patternText({ prefix, suffix }) { return `${prefix}*${suffix}`; @@ -1646,7 +1646,7 @@ var ts = (() => { return void 0; }; hasOwnProperty = Object.prototype.hasOwnProperty; - fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g; + fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_. ]+/g; AssertionLevel = /* @__PURE__ */ ((AssertionLevel2) => { AssertionLevel2[AssertionLevel2["None"] = 0] = "None"; AssertionLevel2[AssertionLevel2["Normal"] = 1] = "Normal"; @@ -1951,7 +1951,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, return func.name; } else { const text = Function.prototype.toString.call(func); - const match = /^function\s+([\w\$]+)\s*\(/.exec(text); + const match = /^function\s+([\w$]+)\s*\(/.exec(text); return match ? match[1] : ""; } } @@ -2936,7 +2936,7 @@ ${lanes.join("\n")} "src/compiler/semver.ts"() { "use strict"; init_ts2(); - versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; @@ -4387,15 +4387,13 @@ ${lanes.join("\n")} NodeCheckFlags2[NodeCheckFlags2["ContainsCapturedBlockScopeBinding"] = 8192] = "ContainsCapturedBlockScopeBinding"; NodeCheckFlags2[NodeCheckFlags2["CapturedBlockScopedBinding"] = 16384] = "CapturedBlockScopedBinding"; NodeCheckFlags2[NodeCheckFlags2["BlockScopedBindingInLoop"] = 32768] = "BlockScopedBindingInLoop"; - NodeCheckFlags2[NodeCheckFlags2["ClassWithBodyScopedClassBinding"] = 65536] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags2[NodeCheckFlags2["BodyScopedClassBinding"] = 131072] = "BodyScopedClassBinding"; - NodeCheckFlags2[NodeCheckFlags2["NeedsLoopOutParameter"] = 262144] = "NeedsLoopOutParameter"; - NodeCheckFlags2[NodeCheckFlags2["AssignmentsMarked"] = 524288] = "AssignmentsMarked"; - NodeCheckFlags2[NodeCheckFlags2["ClassWithConstructorReference"] = 1048576] = "ClassWithConstructorReference"; - NodeCheckFlags2[NodeCheckFlags2["ConstructorReferenceInClass"] = 2097152] = "ConstructorReferenceInClass"; - NodeCheckFlags2[NodeCheckFlags2["ContainsClassWithPrivateIdentifiers"] = 4194304] = "ContainsClassWithPrivateIdentifiers"; - NodeCheckFlags2[NodeCheckFlags2["ContainsSuperPropertyInStaticInitializer"] = 8388608] = "ContainsSuperPropertyInStaticInitializer"; - NodeCheckFlags2[NodeCheckFlags2["InCheckIdentifier"] = 16777216] = "InCheckIdentifier"; + NodeCheckFlags2[NodeCheckFlags2["NeedsLoopOutParameter"] = 65536] = "NeedsLoopOutParameter"; + NodeCheckFlags2[NodeCheckFlags2["AssignmentsMarked"] = 131072] = "AssignmentsMarked"; + NodeCheckFlags2[NodeCheckFlags2["ContainsConstructorReference"] = 262144] = "ContainsConstructorReference"; + NodeCheckFlags2[NodeCheckFlags2["ConstructorReference"] = 536870912] = "ConstructorReference"; + NodeCheckFlags2[NodeCheckFlags2["ContainsClassWithPrivateIdentifiers"] = 1048576] = "ContainsClassWithPrivateIdentifiers"; + NodeCheckFlags2[NodeCheckFlags2["ContainsSuperPropertyInStaticInitializer"] = 2097152] = "ContainsSuperPropertyInStaticInitializer"; + NodeCheckFlags2[NodeCheckFlags2["InCheckIdentifier"] = 4194304] = "InCheckIdentifier"; return NodeCheckFlags2; })(NodeCheckFlags || {}); TypeFlags = /* @__PURE__ */ ((TypeFlags2) => { @@ -4576,7 +4574,8 @@ ${lanes.join("\n")} SignatureFlags5[SignatureFlags5["IsOuterCallChain"] = 16] = "IsOuterCallChain"; SignatureFlags5[SignatureFlags5["IsUntypedSignatureInJSFile"] = 32] = "IsUntypedSignatureInJSFile"; SignatureFlags5[SignatureFlags5["IsNonInferrable"] = 64] = "IsNonInferrable"; - SignatureFlags5[SignatureFlags5["PropagatingFlags"] = 39] = "PropagatingFlags"; + SignatureFlags5[SignatureFlags5["IsSignatureCandidateForOverloadFailure"] = 128] = "IsSignatureCandidateForOverloadFailure"; + SignatureFlags5[SignatureFlags5["PropagatingFlags"] = 167] = "PropagatingFlags"; SignatureFlags5[SignatureFlags5["CallChainFlags"] = 24] = "CallChainFlags"; return SignatureFlags5; })(SignatureFlags || {}); @@ -5425,10 +5424,10 @@ ${lanes.join("\n")} pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === 250 /* Low */ ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingInterval === 250 /* Low */ ? "pollLowPollingIntervalQueue" : "pollPollingIntervalQueue", pollingIntervalQueue(pollingInterval)); } } - function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) { + function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2) { const fileWatcherCallbacks = createMultiMap(); const dirWatchers = /* @__PURE__ */ new Map(); - const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames2); return nonPollingWatchFile; function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) { const filePath = toCanonicalName(fileName); @@ -5504,8 +5503,8 @@ ${lanes.join("\n")} pollScheduled = host.setTimeout(pollQueue, 2e3 /* High */, "pollQueue"); } } - function createSingleWatcherPerName(cache, useCaseSensitiveFileNames, name, callback, createWatcher) { - const toCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + function createSingleWatcherPerName(cache, useCaseSensitiveFileNames2, name, callback, createWatcher) { + const toCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const path = toCanonicalFileName(name); const existing = cache.get(path); if (existing) { @@ -5555,7 +5554,7 @@ ${lanes.join("\n")} } function createDirectoryWatcherSupportingRecursive({ watchDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, getAccessibleSortedChildDirectories, fileSystemEntryExists, @@ -5567,8 +5566,8 @@ ${lanes.join("\n")} const callbackCache = createMultiMap(); const cacheToUpdateChildWatches = /* @__PURE__ */ new Map(); let timerToUpdateChildWatches; - const filePathComparer = getStringComparer(!useCaseSensitiveFileNames); - const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames); + const filePathComparer = getStringComparer(!useCaseSensitiveFileNames2); + const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames2); return (dirName, callback, recursive, options) => recursive ? createDirectoryWatcher(dirName, options, callback) : watchDirectory(dirName, callback, recursive, options); function createDirectoryWatcher(dirName, options, callback) { const dirPath = toCanonicalFilePath(dirName); @@ -5735,12 +5734,12 @@ ${lanes.join("\n")} } } function isIgnoredPath(path, options) { - return some(ignoredPaths, (searchPath) => isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames, getCurrentDirectory); + return some(ignoredPaths, (searchPath) => isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames2, getCurrentDirectory); } function isInPath(path, searchPath) { if (stringContains(path, searchPath)) return true; - if (useCaseSensitiveFileNames) + if (useCaseSensitiveFileNames2) return false; return stringContains(toCanonicalFilePath(path), searchPath); } @@ -5758,14 +5757,14 @@ ${lanes.join("\n")} } }; } - function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames, getCurrentDirectory) { - return ((options == null ? void 0 : options.excludeDirectories) || (options == null ? void 0 : options.excludeFiles)) && (matchesExclude(pathToCheck, options == null ? void 0 : options.excludeFiles, useCaseSensitiveFileNames, getCurrentDirectory()) || matchesExclude(pathToCheck, options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames, getCurrentDirectory())); + function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames2, getCurrentDirectory) { + return ((options == null ? void 0 : options.excludeDirectories) || (options == null ? void 0 : options.excludeFiles)) && (matchesExclude(pathToCheck, options == null ? void 0 : options.excludeFiles, useCaseSensitiveFileNames2, getCurrentDirectory()) || matchesExclude(pathToCheck, options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2, getCurrentDirectory())); } - function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory) { + function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory) { return (eventName, relativeFileName) => { if (eventName === "rename") { const fileName = !relativeFileName ? directoryName : normalizePath(combinePaths(directoryName, relativeFileName)); - if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames, getCurrentDirectory)) { + if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames2, getCurrentDirectory)) { callback(fileName); } } @@ -5778,7 +5777,7 @@ ${lanes.join("\n")} clearTimeout: clearTimeout2, fsWatchWorker, fileSystemEntryExists, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories, @@ -5850,7 +5849,7 @@ ${lanes.join("\n")} ); case 5 /* UseFsEventsOnParentDirectory */: if (!nonPollingWatchFile) { - nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames); + nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2); } return nonPollingWatchFile(fileName, callback, pollingInterval, getFallbackOptions(options)); default: @@ -5899,7 +5898,7 @@ ${lanes.join("\n")} return fsWatch( directoryName, 1 /* Directory */, - createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), + createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */, getFallbackOptions(options) @@ -5907,7 +5906,7 @@ ${lanes.join("\n")} } if (!hostRecursiveDirectoryWatcher) { hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fileSystemEntryExists, getAccessibleSortedChildDirectories, @@ -5953,7 +5952,7 @@ ${lanes.join("\n")} return fsWatch( directoryName, 1 /* Directory */, - createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), + createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */, getFallbackOptions(watchDirectoryOptions) @@ -5981,7 +5980,7 @@ ${lanes.join("\n")} function pollingWatchFile(fileName, callback, pollingInterval, options) { return createSingleWatcherPerName( pollingWatches, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, fileName, callback, (cb) => pollingWatchFileWorker(fileName, cb, pollingInterval, options) @@ -5990,7 +5989,7 @@ ${lanes.join("\n")} function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { return createSingleWatcherPerName( recursive ? fsWatchesRecursive : fsWatches, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, fileOrDirectory, callback, (cb) => fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, cb, recursive, fallbackPollingInterval, fallbackOptions) @@ -6149,7 +6148,7 @@ ${lanes.join("\n")} const Buffer2 = require("buffer").Buffer; const isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; const platform = _os.platform(); - const useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + const useCaseSensitiveFileNames2 = isFileSystemCaseSensitive(); const fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; const executingFilePath = __filename.endsWith("sys.js") ? _path.join(_path.dirname(__dirname), "__fake__.js") : __filename; const fsSupportsRecursiveFsWatch = process.platform === "win32" || process.platform === "darwin"; @@ -6160,7 +6159,7 @@ ${lanes.join("\n")} setTimeout, clearTimeout, fsWatchWorker, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fileSystemEntryExists, // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows @@ -6177,7 +6176,7 @@ ${lanes.join("\n")} const nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, write(s) { process.stdout.write(s); }, @@ -6306,12 +6305,12 @@ ${lanes.join("\n")} for (const node of profile.nodes) { if (node.callFrame.url) { const url = normalizeSlashes(node.callFrame.url); - if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) { + if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames2)) { node.callFrame.url = getRelativePathToDirectoryOrUrl( fileUrlRoot, url, fileUrlRoot, - createGetCanonicalFileName(useCaseSensitiveFileNames), + createGetCanonicalFileName(useCaseSensitiveFileNames2), /*isAbsolutePathAnUrl*/ true ); @@ -6491,7 +6490,7 @@ ${lanes.join("\n")} } } function readDirectory(path, extensions, excludes, includes, depth) { - return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); + return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames2, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path, entryKind) { const originalStackTraceLimit = Error.stackTraceLimit; @@ -7067,6 +7066,7 @@ ${lanes.join("\n")} Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, 1 /* Error */, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, 1 /* Error */, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, 1 /* Error */, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1065, 1 /* Error */, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065", "The return type of an async function or method must be the global Promise type."), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, 1 /* Error */, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, 1 /* Error */, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, 1 /* Error */, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), @@ -8769,6 +8769,7 @@ ${lanes.join("\n")} Parameter_modifiers_can_only_be_used_in_TypeScript_files: diag(8012, 1 /* Error */, "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012", "Parameter modifiers can only be used in TypeScript files."), Non_null_assertions_can_only_be_used_in_TypeScript_files: diag(8013, 1 /* Error */, "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013", "Non-null assertions can only be used in TypeScript files."), Type_assertion_expressions_can_only_be_used_in_TypeScript_files: diag(8016, 1 /* Error */, "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016", "Type assertion expressions can only be used in TypeScript files."), + Signature_declarations_can_only_be_used_in_TypeScript_files: diag(8017, 1 /* Error */, "Signature_declarations_can_only_be_used_in_TypeScript_files_8017", "Signature declarations can only be used in TypeScript files."), Report_errors_in_js_files: diag(8019, 3 /* Message */, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, 1 /* Error */, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, 1 /* Error */, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), @@ -9738,7 +9739,7 @@ ${lanes.join("\n")} if (withMinus) start2--; error2(Diagnostics.Octal_literals_are_not_allowed_Use_the_syntax_0, start2, pos - start2, literal); - return { type: 9 /* NumericLiteral */, value: tokenValue }; + return 9 /* NumericLiteral */; } } else { mainFragment = scanNumberFragment(); @@ -9778,20 +9779,18 @@ ${lanes.join("\n")} } if (tokenFlags & 8192 /* ContainsLeadingZero */) { error2(Diagnostics.Decimals_with_leading_zeros_are_not_allowed, start2, end2 - start2); - return { type: 9 /* NumericLiteral */, value: "" + +result }; + tokenValue = "" + +result; + return 9 /* NumericLiteral */; } if (decimalFragment !== void 0 || tokenFlags & 16 /* Scientific */) { checkForIdentifierStartAfterNumericLiteral(start2, decimalFragment === void 0 && !!(tokenFlags & 16 /* Scientific */)); - return { - type: 9 /* NumericLiteral */, - value: "" + +result - // if value is not an integer, it can be safely coerced to a number - }; + tokenValue = "" + +result; + return 9 /* NumericLiteral */; } else { tokenValue = result; const type = checkBigIntSuffix(); checkForIdentifierStartAfterNumericLiteral(start2); - return { type, value: tokenValue }; + return type; } } function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { @@ -10400,7 +10399,7 @@ ${lanes.join("\n")} return token = 41 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber().value; + scanNumber(); return token = 9 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { @@ -10518,8 +10517,7 @@ ${lanes.join("\n")} case 55 /* _7 */: case 56 /* _8 */: case 57 /* _9 */: - ({ type: token, value: tokenValue } = scanNumber()); - return token; + return token = scanNumber(); case 58 /* colon */: pos++; return token = 59 /* ColonToken */; @@ -11522,7 +11520,7 @@ ${lanes.join("\n")} } function validateLocaleAndSetLanguage(locale, sys2, errors) { const lowerCaseLocale = locale.toLowerCase(); - const matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); + const matchResult = /^([a-z]+)([_-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -16738,6 +16736,12 @@ ${lanes.join("\n")} function isThisIdentifier(node) { return !!node && node.kind === 80 /* Identifier */ && identifierIsThisKeyword(node); } + function isInTypeQuery(node) { + return !!findAncestor( + node, + (n) => n.kind === 186 /* TypeQuery */ ? true : n.kind === 80 /* Identifier */ || n.kind === 166 /* QualifiedName */ ? false : "quit" + ); + } function isThisInTypeQuery(node) { if (!isThisIdentifier(node)) { return false; @@ -17216,7 +17220,7 @@ ${lanes.join("\n")} return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype"; } function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return node.parent.kind === 166 /* QualifiedName */ && node.parent.right === node || node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.name === node; + return node.parent.kind === 166 /* QualifiedName */ && node.parent.right === node || node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.name === node || node.parent.kind === 236 /* MetaProperty */ && node.parent.name === node; } function isRightSideOfAccessExpression(node) { return isPropertyAccessExpression(node.parent) && node.parent.name === node || isElementAccessExpression(node.parent) && node.parent.argumentExpression === node; @@ -18219,6 +18223,9 @@ ${lanes.join("\n")} function getUseDefineForClassFields(compilerOptions) { return compilerOptions.useDefineForClassFields === void 0 ? getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ : compilerOptions.useDefineForClassFields; } + function getEmitStandardClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields !== false && getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */; + } function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return optionsHaveChanges(oldOptions, newOptions, semanticDiagnosticsOptionDeclarations); } @@ -18404,7 +18411,7 @@ ${lanes.join("\n")} function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } - function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames2, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); const absolutePath = combinePaths(currentDirectory, path); @@ -18413,22 +18420,22 @@ ${lanes.join("\n")} includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), - basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames2) }; } - function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { - return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + function getRegexFromPattern(pattern, useCaseSensitiveFileNames2) { + return new RegExp(pattern, useCaseSensitiveFileNames2 ? "" : "i"); } - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames2, currentDirectory, depth, getFileSystemEntries, realpath) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); - const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, useCaseSensitiveFileNames)); - const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); - const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames2, currentDirectory); + const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, useCaseSensitiveFileNames2)); + const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames2); + const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames2); const results = includeFileRegexes ? includeFileRegexes.map(() => []) : [[]]; const visited = /* @__PURE__ */ new Map(); - const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames); + const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames2); for (const basePath of patterns.basePaths) { visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); } @@ -18470,7 +18477,7 @@ ${lanes.join("\n")} } } } - function getBasePaths(path, includes, useCaseSensitiveFileNames) { + function getBasePaths(path, includes, useCaseSensitiveFileNames2) { const basePaths = [path]; if (includes) { const includeBasePaths = []; @@ -18478,9 +18485,9 @@ ${lanes.join("\n")} const absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); includeBasePaths.push(getIncludeBasePath(absolute)); } - includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames)); + includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames2)); for (const includeBasePath of includeBasePaths) { - if (every(basePaths, (basePath) => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames))) { + if (every(basePaths, (basePath) => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames2))) { basePaths.push(includeBasePath); } } @@ -19226,6 +19233,18 @@ ${lanes.join("\n")} function intrinsicTagNameToString(node) { return isIdentifier(node) ? idText(node) : getTextOfJsxNamespacedName(node); } + function isTypeUsableAsPropertyName(type) { + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); + } + function getPropertyNameFromType(type) { + if (type.flags & 8192 /* UniqueESSymbol */) { + return type.escapedName; + } + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + return escapeLeadingUnderscores("" + type.value); + } + return Debug.fail(); + } var resolvingEmptyArray, externalHelpersModuleNameText, defaultMaximumTruncationLength, noTruncationMaximumTruncationLength, stringWriter, GetLiteralTextFlags, fullTripleSlashReferencePathRegEx, fullTripleSlashReferenceTypeReferenceDirectiveRegEx, fullTripleSlashLibReferenceRegEx, fullTripleSlashAMDReferencePathRegEx, fullTripleSlashAMDModuleRegEx, defaultLibReferenceRegEx, AssignmentKind, FunctionFlags, Associativity, OperatorPrecedence, templateSubstitutionRegExp, doubleQuoteEscapedCharsRegExp, singleQuoteEscapedCharsRegExp, backtickQuoteEscapedCharsRegExp, escapedCharsMap, nonAsciiCharacters, jsxDoubleQuoteEscapedCharsRegExp, jsxSingleQuoteEscapedCharsRegExp, jsxEscapedCharsMap, indentStrings, base64Digits, carriageReturnLineFeed, lineFeed, objectAllocator, objectAllocatorPatchers, localizedDiagnosticMessages, reservedCharacterPattern, wildcardCharCodes, commonPackageFolders, implicitExcludePathRegexPattern, filesMatcher, directoriesMatcher, excludeMatcher, wildcardMatchers, supportedTSExtensions, supportedTSExtensionsFlat, supportedTSExtensionsWithJson, supportedTSExtensionsForExtractExtension, supportedJSExtensions, supportedJSExtensionsFlat, allSupportedExtensions, allSupportedExtensionsWithJson, supportedDeclarationExtensions, supportedTSImplementationExtensions, extensionsNotSupportingExtensionlessResolution, ModuleSpecifierEnding, extensionsToRemove, emptyFileSystemEntries; var init_utilities = __esm({ "src/compiler/utilities.ts"() { @@ -19298,9 +19317,9 @@ ${lanes.join("\n")} return OperatorPrecedence2; })(OperatorPrecedence || {}); templateSubstitutionRegExp = /\$\{/g; - doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - backtickQuoteEscapedCharsRegExp = /\r\n|[\\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g; + doubleQuoteEscapedCharsRegExp = /[\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + singleQuoteEscapedCharsRegExp = /[\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + backtickQuoteEscapedCharsRegExp = /\r\n|[\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g; escapedCharsMap = new Map(Object.entries({ " ": "\\t", "\v": "\\v", @@ -19322,8 +19341,8 @@ ${lanes.join("\n")} // special case for CRLFs in backticks })); nonAsciiCharacters = /[^\u0000-\u007F]/g; - jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g; - jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g; + jsxDoubleQuoteEscapedCharsRegExp = /["\u0000-\u001f\u2028\u2029\u0085]/g; + jsxSingleQuoteEscapedCharsRegExp = /['\u0000-\u001f\u2028\u2029\u0085]/g; jsxEscapedCharsMap = new Map(Object.entries({ '"': """, "'": "'" @@ -19344,7 +19363,7 @@ ${lanes.join("\n")} getSourceMapSourceConstructor: () => SourceMapSource }; objectAllocatorPatchers = []; - reservedCharacterPattern = /[^\w\s\/]/g; + reservedCharacterPattern = /[^\w\s/]/g; wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; implicitExcludePathRegexPattern = `(?!(${commonPackageFolders.join("|")})(/|$))`; @@ -26031,7 +26050,7 @@ ${lanes.join("\n")} text: ` var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { if (value !== null && value !== void 0) { - if (typeof value !== "object") throw new TypeError("Object expected."); + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); @@ -27651,7 +27670,7 @@ ${lanes.join("\n")} initializer ); } - function createAccessorPropertyGetRedirector(factory2, node, modifiers, name) { + function createAccessorPropertyGetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { return factory2.createGetAccessorDeclaration( modifiers, name, @@ -27661,7 +27680,7 @@ ${lanes.join("\n")} factory2.createBlock([ factory2.createReturnStatement( factory2.createPropertyAccessExpression( - factory2.createThis(), + receiver, factory2.getGeneratedPrivateNameForNode( node.name, /*prefix*/ @@ -27673,7 +27692,7 @@ ${lanes.join("\n")} ]) ); } - function createAccessorPropertySetRedirector(factory2, node, modifiers, name) { + function createAccessorPropertySetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { return factory2.createSetAccessorDeclaration( modifiers, name, @@ -27688,7 +27707,7 @@ ${lanes.join("\n")} factory2.createExpressionStatement( factory2.createAssignment( factory2.createPropertyAccessExpression( - factory2.createThis(), + receiver, factory2.getGeneratedPrivateNameForNode( node.name, /*prefix*/ @@ -29065,7 +29084,8 @@ ${lanes.join("\n")} nextToken(); const statements = parseList(0 /* SourceElements */, parseStatement); Debug.assert(token() === 1 /* EndOfFileToken */); - const endOfFileToken = addJSDocComment(parseTokenNode()); + const endHasJSDoc = hasPrecedingJSDocComment(); + const endOfFileToken = withJSDoc(parseTokenNode(), endHasJSDoc); const sourceFile = createSourceFile2(fileName, languageVersion2, scriptKind2, isDeclarationFile, statements, endOfFileToken, sourceFlags, setExternalModuleIndicator2); processCommentPragmas(sourceFile, sourceText); processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); @@ -29085,11 +29105,11 @@ ${lanes.join("\n")} parseDiagnostics.push(createDetachedDiagnostic(fileName, pos, end, diagnostic)); } } - function withJSDoc(node, hasJSDoc) { - return hasJSDoc ? addJSDocComment(node) : node; - } let hasDeprecatedTag = false; - function addJSDocComment(node) { + function withJSDoc(node, hasJSDoc) { + if (!hasJSDoc) { + return node; + } Debug.assert(!node.jsDoc); const jsDoc = mapDefined(getJSDocCommentRanges(node, sourceText), (comment) => JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); if (jsDoc.length) @@ -29883,6 +29903,9 @@ ${lanes.join("\n")} case 22 /* HeritageClauses */: return isHeritageClause2(); case 23 /* ImportOrExportSpecifiers */: + if (token() === 161 /* FromKeyword */ && lookAhead(nextTokenIsStringLiteral)) { + return false; + } return tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */; @@ -30241,6 +30264,9 @@ ${lanes.join("\n")} case 22 /* HeritageClauses */: return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_expected); case 23 /* ImportOrExportSpecifiers */: + if (token() === 161 /* FromKeyword */) { + return parseErrorAtCurrentToken(Diagnostics._0_expected, "}"); + } return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 13 /* JsxAttributes */: return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); @@ -31598,12 +31624,14 @@ ${lanes.join("\n")} return arrowExpression; } const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); if (expr.kind === 80 /* Identifier */ && token() === 39 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression( pos, expr, allowReturnTypeInArrowFunction, + hasJSDoc, /*asyncModifier*/ void 0 ); @@ -31649,7 +31677,7 @@ ${lanes.join("\n")} ), pos); } } - function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, asyncModifier) { + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier) { Debug.assert(token() === 39 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); const parameter = factory2.createParameterDeclaration( /*modifiers*/ @@ -31682,7 +31710,7 @@ ${lanes.join("\n")} equalsGreaterThanToken, body ); - return addJSDocComment(finishNode(node, pos)); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { const triState = isParenthesizedArrowFunctionExpression(); @@ -31810,9 +31838,10 @@ ${lanes.join("\n")} if (token() === 134 /* AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const asyncModifier = parseModifiersForArrowFunction(); const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); - return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier); } } return void 0; @@ -33173,10 +33202,14 @@ ${lanes.join("\n")} case 124 /* ProtectedKeyword */: case 125 /* PublicKeyword */: case 148 /* ReadonlyKeyword */: + const previousToken = token(); nextToken(); if (scanner2.hasPrecedingLineBreak()) { return false; } + if (previousToken === 138 /* DeclareKeyword */ && token() === 156 /* TypeKeyword */) { + return true; + } continue; case 162 /* GlobalKeyword */: nextToken(); @@ -33486,6 +33519,9 @@ ${lanes.join("\n")} return void 0; } } + function nextTokenIsStringLiteral() { + return nextToken() === 11 /* StringLiteral */; + } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); return !scanner2.hasPrecedingLineBreak() && (isIdentifier2() || token() === 11 /* StringLiteral */); @@ -33538,14 +33574,14 @@ ${lanes.join("\n")} function parseObjectBindingPattern() { const pos = getNodePos(); parseExpected(19 /* OpenBraceToken */); - const elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + const elements = allowInAnd(() => parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement)); parseExpected(20 /* CloseBraceToken */); return finishNode(factory2.createObjectBindingPattern(elements), pos); } function parseArrayBindingPattern() { const pos = getNodePos(); parseExpected(23 /* OpenBracketToken */); - const elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + const elements = allowInAnd(() => parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement)); parseExpected(24 /* CloseBracketToken */); return finishNode(factory2.createArrayBindingPattern(elements), pos); } @@ -34063,6 +34099,9 @@ ${lanes.join("\n")} } function parseTypeAliasDeclaration(pos, hasJSDoc, modifiers) { parseExpected(156 /* TypeKeyword */); + if (scanner2.hasPrecedingLineBreak()) { + parseErrorAtCurrentToken(Diagnostics.Line_break_not_permitted_here); + } const name = parseIdentifier(); const typeParameters = parseTypeParameters(); parseExpected(64 /* EqualsToken */); @@ -35045,7 +35084,7 @@ ${lanes.join("\n")} typeExpression = tryParseTypeExpression(); } const comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText); - const nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent2); + const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target, indent2); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -35331,7 +35370,7 @@ ${lanes.join("\n")} case 60 /* AtToken */: if (canParseTag) { const child = tryParseChildTag(target, indent2); - if (child && (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + if (child && (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */) && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } return child; @@ -35846,7 +35885,7 @@ ${lanes.join("\n")} })(IncrementalParser || (IncrementalParser = {})); namedArgRegExCache = /* @__PURE__ */ new Map(); tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; - singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; + singleLinePragmaRegEx = /^\/\/\/?\s*@([^\s:]+)(.*)\s*$/im; } }); @@ -37258,19 +37297,19 @@ ${lanes.join("\n")} const wildcardFiles = arrayFrom(wildcardFileMap.values()); return literalFiles.concat(wildcardFiles, arrayFrom(wildCardJsonFileMap.values())); } - function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames, currentDirectory) { + function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames2, currentDirectory) { const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = spec; if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) return false; basePath = normalizePath(basePath); - const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames); + const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames2); if (validatedFilesSpec) { for (const fileName of validatedFilesSpec) { if (keyMapper(getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck) return false; } } - return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath); + return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath); } function invalidDotDotAfterRecursiveWildcard(s) { const wildcardIndex = startsWith(s, "**/") ? 0 : s.indexOf("/**/"); @@ -37280,17 +37319,17 @@ ${lanes.join("\n")} const lastDotIndex = endsWith(s, "/..") ? s.length : s.lastIndexOf("/../"); return lastDotIndex > wildcardIndex; } - function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory) { + function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory) { return matchesExcludeWorker( pathToCheck, filter(excludeSpecs, (spec) => !invalidDotDotAfterRecursiveWildcard(spec)), - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, currentDirectory ); } - function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath) { + function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath) { const excludePattern = getRegularExpressionForWildcard(excludeSpecs, combinePaths(normalizePath(currentDirectory), basePath), "exclude"); - const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames); + const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames2); if (!excludeRegex) return false; if (excludeRegex.test(pathToCheck)) @@ -37320,9 +37359,9 @@ ${lanes.join("\n")} return [Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec]; } } - function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }, path, useCaseSensitiveFileNames) { + function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }, path, useCaseSensitiveFileNames2) { const rawExcludeRegex = getRegularExpressionForWildcard(exclude, path, "exclude"); - const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames2 ? "" : "i"); const wildcardDirectories = {}; if (include !== void 0) { const recursiveKeys = []; @@ -37331,7 +37370,7 @@ ${lanes.join("\n")} if (excludeRegex && excludeRegex.test(spec)) { continue; } - const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); + const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2); if (match) { const { key, flags } = match; const existingFlags = wildcardDirectories[key]; @@ -37346,7 +37385,7 @@ ${lanes.join("\n")} for (const key in wildcardDirectories) { if (hasProperty(wildcardDirectories, key)) { for (const recursiveKey of recursiveKeys) { - if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames2)) { delete wildcardDirectories[key]; } } @@ -37355,20 +37394,20 @@ ${lanes.join("\n")} } return wildcardDirectories; } - function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2) { const match = wildcardDirectoryPattern.exec(spec); if (match) { const questionWildcardIndex = spec.indexOf("?"); const starWildcardIndex = spec.indexOf("*"); const lastDirectorySeperatorIndex = spec.lastIndexOf(directorySeparator); return { - key: useCaseSensitiveFileNames ? match[0] : toFileNameLowerCase(match[0]), + key: useCaseSensitiveFileNames2 ? match[0] : toFileNameLowerCase(match[0]), flags: questionWildcardIndex !== -1 && questionWildcardIndex < lastDirectorySeperatorIndex || starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex ? 1 /* Recursive */ : 0 /* None */ }; } if (isImplicitGlob(spec.substring(spec.lastIndexOf(directorySeparator) + 1))) { return { - key: removeTrailingDirectorySeparator(useCaseSensitiveFileNames ? spec : toFileNameLowerCase(spec)), + key: removeTrailingDirectorySeparator(useCaseSensitiveFileNames2 ? spec : toFileNameLowerCase(spec)), flags: 1 /* Recursive */ }; } @@ -37973,6 +38012,7 @@ ${lanes.join("\n")} { name: "checkJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: Diagnostics.JavaScript_Support, description: Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files, @@ -38199,7 +38239,7 @@ ${lanes.join("\n")} strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, - defaultValueDescription: false + defaultValueDescription: Diagnostics.false_unless_strict_is_set }, { name: "alwaysStrict", @@ -39053,6 +39093,18 @@ ${lanes.join("\n")} result.push("JSON"); return result.join(", "); } + function extensionsToExtensionsArray(extensions) { + const result = []; + if (extensions & 1 /* TypeScript */) + result.push(...supportedTSImplementationExtensions); + if (extensions & 2 /* JavaScript */) + result.push(...supportedJSExtensionsFlat); + if (extensions & 4 /* Declaration */) + result.push(...supportedDeclarationExtensions); + if (extensions & 8 /* Json */) + result.push(".json" /* Json */); + return result; + } function resolvedTypeScriptOnly(resolved) { if (!resolved) { return void 0; @@ -39225,8 +39277,8 @@ ${lanes.join("\n")} return typeRoots; } function arePathsEqual(path1, path2, host) { - const useCaseSensitiveFileNames = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; - return comparePaths(path1, path2, !useCaseSensitiveFileNames) === 0 /* EqualTo */; + const useCaseSensitiveFileNames2 = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; + return comparePaths(path1, path2, !useCaseSensitiveFileNames2) === 0 /* EqualTo */; } function getOriginalAndResolvedFileName(fileName, host, traceEnabled) { const resolvedFileName = realPath(fileName, host, traceEnabled); @@ -40489,7 +40541,7 @@ ${lanes.join("\n")} arrayIsEqualTo ); for (const conditions of conditionSets) { - const loadPackageJsonExportsState = { ...loadPackageJsonMainState, failedLookupLocations: [], conditions }; + const loadPackageJsonExportsState = { ...loadPackageJsonMainState, failedLookupLocations: [], conditions, host }; const exportResolutions = loadEntrypointsFromExportMap( packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, @@ -40521,23 +40573,42 @@ ${lanes.join("\n")} return entrypoints; function loadEntrypointsFromTargetExports(target) { var _a, _b; - if (typeof target === "string" && startsWith(target, "./") && target.indexOf("*") === -1) { - const partsAfterFirst = getPathComponents(target).slice(2); - if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) { - return false; - } - const resolvedTarget = combinePaths(scope.packageDirectory, target); - const finalPath = getNormalizedAbsolutePath(resolvedTarget, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); - const result = loadFileNameFromPackageJsonField( - extensions, - finalPath, - /*onlyRecordFailures*/ - false, - state - ); - if (result) { - entrypoints = appendIfUnique(entrypoints, result, (a, b) => a.path === b.path); - return true; + if (typeof target === "string" && startsWith(target, "./")) { + if (target.indexOf("*") >= 0 && state.host.readDirectory) { + if (target.indexOf("*") !== target.lastIndexOf("*")) { + return false; + } + state.host.readDirectory( + scope.packageDirectory, + extensionsToExtensionsArray(extensions), + /*excludes*/ + void 0, + [changeAnyExtension(target.replace("*", "**/*"), getDeclarationEmitExtensionForPath(target))] + ).forEach((entry) => { + entrypoints = appendIfUnique(entrypoints, { + path: entry, + ext: getAnyExtensionFromPath(entry), + resolvedUsingTsExtension: void 0 + }); + }); + } else { + const partsAfterFirst = getPathComponents(target).slice(2); + if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) { + return false; + } + const resolvedTarget = combinePaths(scope.packageDirectory, target); + const finalPath = getNormalizedAbsolutePath(resolvedTarget, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); + const result = loadFileNameFromPackageJsonField( + extensions, + finalPath, + /*onlyRecordFailures*/ + false, + state + ); + if (result) { + entrypoints = appendIfUnique(entrypoints, result, (a, b) => a.path === b.path); + return true; + } } } else if (Array.isArray(target)) { for (const t of target) { @@ -40746,6 +40817,9 @@ ${lanes.join("\n")} } const trailingParts = parts.slice(nameParts.length); const subpath = !length(trailingParts) ? "." : `.${directorySeparator}${trailingParts.join(directorySeparator)}`; + if (getAllowJSCompilerOption(state.compilerOptions) && !pathContainsNodeModules(directory)) { + return loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference); + } const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */); const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */); return loadModuleFromExports(scope, priorityExtensions, subpath, state, cache, redirectedReference) || loadModuleFromExports(scope, secondaryExtensions, subpath, state, cache, redirectedReference); @@ -41093,13 +41167,10 @@ ${lanes.join("\n")} function combineDirectoryPath(root, dir) { return ensureTrailingDirectorySeparator(combinePaths(root, dir)); } - function useCaseSensitiveFileNames() { - return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); - } function tryLoadInputFileForPath(finalPath, entry, packagePath, isImports2) { var _a, _b, _c, _d; - if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames()) : true)) { - const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames }); + if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true)) { + const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames: () => useCaseSensitiveFileNames(state) }); const commonSourceDirGuesses = []; if (state.compilerOptions.rootDir || state.compilerOptions.composite && state.compilerOptions.configFilePath) { const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, () => [], ((_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)) || "", getCanonicalFileName)); @@ -41128,7 +41199,7 @@ ${lanes.join("\n")} for (const commonSourceDirGuess of commonSourceDirGuesses) { const candidateDirectories = getOutputDirectoriesForBaseDirectory(commonSourceDirGuess); for (const candidateDir of candidateDirectories) { - if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames())) { + if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames(state))) { const pathFragment = finalPath.slice(candidateDir.length + 1); const possibleInputBase = combinePaths(commonSourceDirGuess, pathFragment); const jsAndDtsExtensions = [".mjs" /* Mjs */, ".cjs" /* Cjs */, ".js" /* Js */, ".json" /* Json */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */, ".d.ts" /* Dts */]; @@ -41138,7 +41209,7 @@ ${lanes.join("\n")} for (const possibleExt of inputExts) { if (!extensionIsOk(extensions, possibleExt)) continue; - const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames()); + const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames(state)); if (state.host.fileExists(possibleInputWithInputExtension)) { return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( extensions, @@ -41554,6 +41625,9 @@ ${lanes.join("\n")} trace(state.host, diagnostic, ...args); } } + function useCaseSensitiveFileNames(state) { + return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); + } var typeScriptVersion, nodeModulesAtTypes, NodeResolutionFeatures, nodeModulesPathPart, mangledScopedPackageSeparator; var init_moduleNameResolver = __esm({ "src/compiler/moduleNameResolver.ts"() { @@ -41684,6 +41758,9 @@ ${lanes.join("\n")} if (found === 1 /* Instantiated */) { return found; } + if (statement.kind === 271 /* ImportEqualsDeclaration */) { + found = 1 /* Instantiated */; + } } } if (found !== void 0) { @@ -45059,7 +45136,9 @@ ${lanes.join("\n")} for (const { ending, value } of candidates) { if (value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ ending, value })) { const matchedStar = value.substring(prefix.length, value.length - suffix.length); - return pathIsRelative(matchedStar) ? void 0 : key.replace("*", matchedStar); + if (!pathIsRelative(matchedStar)) { + return key.replace("*", matchedStar); + } } } } else if (some(candidates, (c) => c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, (c) => c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) { @@ -45131,7 +45210,7 @@ ${lanes.join("\n")} for (const key of getOwnKeys(exports)) { if (key === "default" || conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(conditions, key)) { const subTarget = exports[key]; - const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions); + const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions, mode); if (result) { return result; } @@ -45446,6 +45525,7 @@ ${lanes.join("\n")} var moduleKind = getEmitModuleKind(compilerOptions); var legacyDecorators = !!compilerOptions.experimentalDecorators; var useDefineForClassFields = getUseDefineForClassFields(compilerOptions); + var emitStandardClassFields = getEmitStandardClassFields(compilerOptions); var allowSyntheticDefaultImports = getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -45536,7 +45616,7 @@ ${lanes.join("\n")} return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, - getParameterIdentifierNameAtPosition, + getParameterIdentifierInfoAtPosition, getPromisedTypeOfPromise, getAwaitedType: (type) => getAwaitedType(type), getReturnTypeOfSignature, @@ -46189,7 +46269,7 @@ ${lanes.join("\n")} }; var amalgamatedDuplicates; var reverseMappedCache = /* @__PURE__ */ new Map(); - var inInferTypeForHomomorphicMappedType = false; + var homomorphicMappedTypeInferenceStack = []; var ambientModulesCache; var patternAmbientModules; var patternAmbientModuleAugmentations; @@ -46749,7 +46829,7 @@ ${lanes.join("\n")} return symbol; } if (symbol.flags & 2097152 /* Alias */) { - const targetFlags = getAllSymbolFlags(symbol); + const targetFlags = getSymbolFlags(symbol); if (targetFlags & meaning) { return symbol; } @@ -46800,7 +46880,7 @@ ${lanes.join("\n")} false ); } else if (isParameterPropertyDeclaration(declaration, declaration.parent)) { - return !(getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); + return !(emitStandardClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } @@ -46814,7 +46894,7 @@ ${lanes.join("\n")} return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { + if (emitStandardClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration( declaration, usage, @@ -46938,7 +47018,7 @@ ${lanes.join("\n")} return requiresScopeChangeWorker(node.name); case 172 /* PropertyDeclaration */: if (hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !useDefineForClassFields; + return !emitStandardClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -46977,7 +47057,7 @@ ${lanes.join("\n")} if (name === "const" && isConstAssertion(location)) { return void 0; } - if (isModuleDeclaration(location) && lastLocation && location.name === lastLocation) { + if (isModuleOrEnumDeclaration(location) && lastLocation && location.name === lastLocation) { lastLocation = location; location = location.parent; } @@ -47209,7 +47289,7 @@ ${lanes.join("\n")} } } function checkAndReportErrorForInvalidInitializer() { - if (propertyWithInvalidInitializer && !(useDefineForClassFields && getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */)) { + if (propertyWithInvalidInitializer && !emitStandardClassFields) { error2( errorLocation, errorLocation && propertyWithInvalidInitializer.type && textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) ? Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor : Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, @@ -47509,7 +47589,7 @@ ${lanes.join("\n")} /*isUse*/ false )); - const allFlags = symbol && getAllSymbolFlags(symbol); + const allFlags = symbol && getSymbolFlags(symbol); if (symbol && allFlags !== void 0 && !(allFlags & 111551 /* Value */)) { const rawName = unescapeLeadingUnderscores(name); if (isES2015OrLaterConstructorName(name)) { @@ -48245,11 +48325,23 @@ ${lanes.join("\n")} } return void 0; } - function getAllSymbolFlags(symbol) { - let flags = symbol.flags; + function getSymbolFlags(symbol, excludeTypeOnlyMeanings, excludeLocalMeanings) { + const typeOnlyDeclaration = excludeTypeOnlyMeanings && getTypeOnlyAliasDeclaration(symbol); + const typeOnlyDeclarationIsExportStar = typeOnlyDeclaration && isExportDeclaration(typeOnlyDeclaration); + const typeOnlyResolution = typeOnlyDeclaration && (typeOnlyDeclarationIsExportStar ? resolveExternalModuleName( + typeOnlyDeclaration.moduleSpecifier, + typeOnlyDeclaration.moduleSpecifier, + /*ignoreErrors*/ + true + ) : resolveAlias(typeOnlyDeclaration.symbol)); + const typeOnlyExportStarTargets = typeOnlyDeclarationIsExportStar && typeOnlyResolution ? getExportsOfModule(typeOnlyResolution) : void 0; + let flags = excludeLocalMeanings ? 0 /* None */ : symbol.flags; let seenSymbols; while (symbol.flags & 2097152 /* Alias */) { - const target = resolveAlias(symbol); + const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); + if (!typeOnlyDeclarationIsExportStar && target === typeOnlyResolution || (typeOnlyExportStarTargets == null ? void 0 : typeOnlyExportStarTargets.get(target.escapedName)) === target) { + break; + } if (target === unknownSymbol) { return 67108863 /* All */; } @@ -48307,7 +48399,7 @@ ${lanes.join("\n")} } if (links.typeOnlyDeclaration) { const resolved = links.typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? resolveSymbol(getExportsOfModule(links.typeOnlyDeclaration.symbol.parent).get(links.typeOnlyExportStarName || symbol.escapedName)) : resolveAlias(links.typeOnlyDeclaration.symbol); - return getAllSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0; + return getSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0; } return void 0; } @@ -48318,7 +48410,11 @@ ${lanes.join("\n")} const symbol = getSymbolOfDeclaration(node); const target = resolveAlias(symbol); if (target) { - const markAlias = target === unknownSymbol || getAllSymbolFlags(target) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */); + const markAlias = target === unknownSymbol || getSymbolFlags( + symbol, + /*excludeTypeOnlyMeanings*/ + true + ) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -48333,7 +48429,7 @@ ${lanes.join("\n")} if (!node) return Debug.fail(); if (isInternalModuleImportEqualsDeclaration(node)) { - if (getAllSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { + if (getSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { checkExpressionCached(node.moduleReference); } } @@ -48593,7 +48689,7 @@ ${lanes.join("\n")} return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation) : void 0; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) { - var _a, _b, _c, _d, _e, _f, _g, _h, _i; + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; if (startsWith(moduleReference, "@types/")) { const diag2 = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; const withoutAtTypePrefix = removePrefix(moduleReference, "@types/"); @@ -48628,8 +48724,11 @@ ${lanes.join("\n")} ); } } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) { - const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); - error2(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension); + const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); + if (!((importOrExport == null ? void 0 : importOrExport.isTypeOnly) || findAncestor(location, isImportTypeNode))) { + const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); + error2(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension); + } } if (sourceFile.symbol) { if (resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) { @@ -48646,7 +48745,7 @@ ${lanes.join("\n")} if (moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */) { const isSyncImport = currentSourceFile.impliedNodeFormat === 1 /* CommonJS */ && !findAncestor(location, isImportCall) || !!findAncestor(location, isImportEqualsDeclaration); const overrideClauseHost = findAncestor(location, (l) => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l)); - const overrideClause = overrideClauseHost && isImportTypeNode(overrideClauseHost) ? (_h = overrideClauseHost.assertions) == null ? void 0 : _h.assertClause : overrideClauseHost == null ? void 0 : overrideClauseHost.assertClause; + const overrideClause = overrideClauseHost && isImportTypeNode(overrideClauseHost) ? (_i = overrideClauseHost.assertions) == null ? void 0 : _i.assertClause : overrideClauseHost == null ? void 0 : overrideClauseHost.assertClause; if (isSyncImport && sourceFile.impliedNodeFormat === 99 /* ESNext */ && !getResolutionModeOverrideForClause(overrideClause)) { if (findAncestor(location, isImportEqualsDeclaration)) { error2(errorNode, Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); @@ -48749,7 +48848,7 @@ ${lanes.join("\n")} error2(errorNode, Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else if (mode === 99 /* ESNext */ && resolutionIsNode16OrNext && isExtensionlessRelativePathImport) { const absoluteRef = getNormalizedAbsolutePath(moduleReference, getDirectoryPath(currentSourceFile.path)); - const suggestedExt = (_i = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _i[1]; + const suggestedExt = (_j = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _j[1]; if (suggestedExt) { error2( errorNode, @@ -49181,7 +49280,7 @@ ${lanes.join("\n")} return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 && symbol.exportSymbol || symbol); } function symbolIsValue(symbol, includeTypeOnlyMembers) { - return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getAllSymbolFlags(symbol) & 111551 /* Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); + return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getSymbolFlags(symbol, !includeTypeOnlyMembers) & 111551 /* Value */); } function findConstructorDeclaration(node) { const members = node.members; @@ -49448,7 +49547,7 @@ ${lanes.join("\n")} } const shouldResolveAlias = symbolFromSymbolTable.flags & 2097152 /* Alias */ && !getDeclarationOfKind(symbolFromSymbolTable, 281 /* ExportSpecifier */); symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - const flags = shouldResolveAlias ? getAllSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; + const flags = shouldResolveAlias ? getSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; if (flags & meaning) { qualify = true; return true; @@ -50185,11 +50284,13 @@ ${lanes.join("\n")} return !!type2.target && isMappedTypeHomomorphic(type2.target) && !isMappedTypeHomomorphic(type2); } function createMappedTypeNodeFromType(type2) { + var _a2; Debug.assert(!!(type2.flags & 524288 /* Object */)); const readonlyToken = type2.declaration.readonlyToken ? factory.createToken(type2.declaration.readonlyToken.kind) : void 0; const questionToken = type2.declaration.questionToken ? factory.createToken(type2.declaration.questionToken.kind) : void 0; let appropriateConstraintTypeNode; let newTypeVariable; + const needsModifierPreservingWrapper = !isMappedTypeWithKeyofConstraintDeclaration(type2) && !(getModifiersTypeFromMappedType(type2).flags & 2 /* Unknown */) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && !(getConstraintTypeFromMappedType(type2).flags & 262144 /* TypeParameter */ && ((_a2 = getConstraintOfTypeParameter(getConstraintTypeFromMappedType(type2))) == null ? void 0 : _a2.flags) & 4194304 /* Index */); if (isMappedTypeWithKeyofConstraintDeclaration(type2)) { if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */) { const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T")); @@ -50197,6 +50298,11 @@ ${lanes.join("\n")} newTypeVariable = factory.createTypeReferenceNode(name); } appropriateConstraintTypeNode = factory.createTypeOperatorNode(143 /* KeyOfKeyword */, newTypeVariable || typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)); + } else if (needsModifierPreservingWrapper) { + const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T")); + const name = typeParameterToName(newParam, context); + newTypeVariable = factory.createTypeReferenceNode(name); + appropriateConstraintTypeNode = newTypeVariable; } else { appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context); } @@ -50227,6 +50333,18 @@ ${lanes.join("\n")} result, factory.createKeywordTypeNode(146 /* NeverKeyword */) ); + } else if (needsModifierPreservingWrapper) { + return factory.createConditionalTypeNode( + typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context), + factory.createInferTypeNode(factory.createTypeParameterDeclaration( + /*modifiers*/ + void 0, + factory.cloneNode(newTypeVariable.typeName), + factory.createTypeOperatorNode(143 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)) + )), + result, + factory.createKeywordTypeNode(146 /* NeverKeyword */) + ); } return result; } @@ -50780,6 +50898,7 @@ ${lanes.join("\n")} ); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { + var _a; const suppressAny = context.flags & 256 /* SuppressAnyReturnType */; if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; @@ -50915,6 +51034,20 @@ ${lanes.join("\n")} if (typeArguments) { node.typeArguments = factory.createNodeArray(typeArguments); } + if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 330 /* JSDocSignature */ && signature.declaration.parent.kind === 346 /* JSDocOverloadTag */) { + const comment = getTextOfNode( + signature.declaration.parent.parent, + /*includeTrivia*/ + true + ).slice(2, -2).split(/\r\n|\n|\r/).map((line) => line.replace(/^\s+/, " ")).join("\n"); + addSyntheticLeadingComment( + node, + 3 /* MultiLineCommentTrivia */, + comment, + /*hasTrailingNewLine*/ + true + ); + } cleanup == null ? void 0 : cleanup(); return node; } @@ -52276,7 +52409,7 @@ ${lanes.join("\n")} return !exports ? [] : filter(arrayFrom(exports.values()), (m) => isNamespaceMember(m) && isIdentifierText(m.escapedName, 99 /* ESNext */)); } function isTypeOnlyNamespace(symbol) { - return every(getNamespaceMembersForSerialization(symbol), (m) => !(getAllSymbolFlags(resolveSymbol(m)) & 111551 /* Value */)); + return every(getNamespaceMembersForSerialization(symbol), (m) => !(getSymbolFlags(resolveSymbol(m)) & 111551 /* Value */)); } function serializeModule(symbol, symbolName2, modifierFlags) { const members = getNamespaceMembersForSerialization(symbol); @@ -53984,7 +54117,7 @@ ${lanes.join("\n")} false, definedInMethod && !definedInConstructor )); - if (symbol.valueDeclaration && filterType(widened, (t) => !!(t.flags & ~98304 /* Nullable */)) === neverType) { + if (symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && filterType(widened, (t) => !!(t.flags & ~98304 /* Nullable */)) === neverType) { reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } @@ -54548,7 +54681,7 @@ ${lanes.join("\n")} true ); const declaredType = firstDefined(exportSymbol == null ? void 0 : exportSymbol.declarations, (d) => isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : void 0); - links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getAllSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; + links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } return links.type; } @@ -55263,9 +55396,6 @@ ${lanes.join("\n")} } return type; } - function isTypeUsableAsPropertyName(type) { - return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); - } function isLateBindableName(node) { if (!isComputedPropertyName(node) && !isElementAccessExpression(node)) { return false; @@ -55286,15 +55416,6 @@ ${lanes.join("\n")} function isNonBindableDynamicName(node) { return isDynamicName(node) && !isLateBindableName(node); } - function getPropertyNameFromType(type) { - if (type.flags & 8192 /* UniqueESSymbol */) { - return type.escapedName; - } - if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { - return escapeLeadingUnderscores("" + type.value); - } - return Debug.fail(); - } function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { Debug.assert(!!(getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol."); symbol.flags |= symbolFlags; @@ -55344,6 +55465,7 @@ ${lanes.join("\n")} return links.resolvedSymbol; } function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var _a, _b, _c; const links = getSymbolLinks(symbol); if (!links[resolutionKind]) { const isStatic2 = resolutionKind === "resolvedExports" /* resolvedExports */; @@ -55362,7 +55484,7 @@ ${lanes.join("\n")} } } } - const assignments = symbol.assignmentDeclarationMembers; + const assignments = (((_a = symbol.valueDeclaration) == null ? void 0 : _a.kind) === 219 /* ArrowFunction */ || ((_b = symbol.valueDeclaration) == null ? void 0 : _b.kind) === 218 /* FunctionExpression */) && ((_c = getSymbolOfNode(symbol.valueDeclaration.parent)) == null ? void 0 : _c.assignmentDeclarationMembers) || symbol.assignmentDeclarationMembers; if (assignments) { const decls = arrayFrom(assignments.values()); for (const member of decls) { @@ -55491,7 +55613,7 @@ ${lanes.join("\n")} /*resolvedTypePredicate*/ void 0, sig.minArgumentCount, - sig.flags & 39 /* PropagatingFlags */ + sig.flags & 167 /* PropagatingFlags */ ); result.target = sig.target; result.mapper = sig.mapper; @@ -55792,7 +55914,7 @@ ${lanes.join("\n")} /*resolvedTypePredicate*/ void 0, minArgCount, - (left.flags | right.flags) & 39 /* PropagatingFlags */ + (left.flags | right.flags) & 167 /* PropagatingFlags */ ); result.compositeKind = 1048576 /* Union */; result.compositeSignatures = concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); @@ -55940,20 +56062,17 @@ ${lanes.join("\n")} setStructuredTypeMembers(type, members2, callSignatures, constructSignatures, indexInfos2); return; } - let members = emptySymbols; + let members = getExportsOfSymbol(symbol); let indexInfos; - if (symbol.exports) { - members = getExportsOfSymbol(symbol); - if (symbol === globalThisSymbol) { - const varsOnly = /* @__PURE__ */ new Map(); - members.forEach((p) => { - var _a; - if (!(p.flags & 418 /* BlockScoped */) && !(p.flags & 512 /* ValueModule */ && ((_a = p.declarations) == null ? void 0 : _a.length) && every(p.declarations, isAmbientModule))) { - varsOnly.set(p.escapedName, p); - } - }); - members = varsOnly; - } + if (symbol === globalThisSymbol) { + const varsOnly = /* @__PURE__ */ new Map(); + members.forEach((p) => { + var _a; + if (!(p.flags & 418 /* BlockScoped */) && !(p.flags & 512 /* ValueModule */ && ((_a = p.declarations) == null ? void 0 : _a.length) && every(p.declarations, isAmbientModule))) { + varsOnly.set(p.escapedName, p); + } + }); + members = varsOnly; } let baseConstructorIndexInfo; setStructuredTypeMembers(type, members, emptyArray, emptyArray, emptyArray); @@ -56002,7 +56121,7 @@ ${lanes.join("\n")} /*resolvedTypePredicate*/ void 0, sig.minArgumentCount, - sig.flags & 39 /* PropagatingFlags */ + sig.flags & 167 /* PropagatingFlags */ ) : void 0 )); } @@ -57394,7 +57513,7 @@ ${lanes.join("\n")} return getReturnTypeOfTypeTag(declaration); } function isResolvingReturnTypeOfSignature(signature) { - return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; + return signature.compositeSignatures && some(signature.compositeSignatures, isResolvingReturnTypeOfSignature) || !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; } function getRestTypeOfSignature(signature) { return tryGetRestTypeOfSignature(signature) || anyType; @@ -58742,6 +58861,9 @@ ${lanes.join("\n")} function getEndElementCount(type, flags) { return type.elementFlags.length - findLastIndex(type.elementFlags, (f) => !(f & flags)) - 1; } + function getTotalFixedElementCount(type) { + return type.fixedLength + getEndElementCount(type, 3 /* Fixed */); + } function getElementTypes(type) { const typeArguments = getTypeArguments(type); const arity = getTypeReferenceArity(type); @@ -59647,10 +59769,7 @@ ${lanes.join("\n")} } if (index >= 0) { errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); - return mapType(objectType, (t) => { - const restType = getRestTypeOfTupleType(t) || undefinedType; - return accessFlags & 1 /* IncludeUndefined */ ? getUnionType([restType, missingType]) : restType; - }); + return getTupleElementTypeOutOfStartCount(objectType, index, accessFlags & 1 /* IncludeUndefined */ ? missingType : void 0); } } } @@ -59935,7 +60054,7 @@ ${lanes.join("\n")} } if (compilerOptions.noUncheckedIndexedAccess && accessFlags & 32 /* ExpressionPosition */) accessFlags |= 1 /* IncludeUndefined */; - if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 199 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)) || isGenericReducibleType(objectType))) { + if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 199 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target)) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target))) || isGenericReducibleType(objectType))) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } @@ -60785,7 +60904,7 @@ ${lanes.join("\n")} /*resolvedTypePredicate*/ void 0, signature.minArgumentCount, - signature.flags & 39 /* PropagatingFlags */ + signature.flags & 167 /* PropagatingFlags */ ); result.target = signature; result.mapper = mapper; @@ -62172,6 +62291,7 @@ ${lanes.join("\n")} let errorInfo; let relatedInfo; let maybeKeys; + let maybeKeysSet; let sourceStack; let targetStack; let maybeCount = 0; @@ -63041,9 +63161,13 @@ ${lanes.join("\n")} } if (!maybeKeys) { maybeKeys = []; + maybeKeysSet = /* @__PURE__ */ new Set(); sourceStack = []; targetStack = []; } else { + if (maybeKeysSet.has(id)) { + return 3 /* Maybe */; + } const broadestEquivalentId = id.startsWith("*") ? getRelationKey( source2, target2, @@ -63052,10 +63176,8 @@ ${lanes.join("\n")} /*ignoreConstraints*/ true ) : void 0; - for (let i = 0; i < maybeCount; i++) { - if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) { - return 3 /* Maybe */; - } + if (broadestEquivalentId && maybeKeysSet.has(broadestEquivalentId)) { + return 3 /* Maybe */; } if (sourceDepth === 100 || targetDepth === 100) { overflow = true; @@ -63064,6 +63186,7 @@ ${lanes.join("\n")} } const maybeStart = maybeCount; maybeKeys[maybeCount] = id; + maybeKeysSet.add(id); maybeCount++; const saveExpandingFlags = expandingFlags; if (recursionFlags & 1 /* Source */) { @@ -63116,17 +63239,34 @@ ${lanes.join("\n")} if (result2) { if (result2 === -1 /* True */ || sourceDepth === 0 && targetDepth === 0) { if (result2 === -1 /* True */ || result2 === 3 /* Maybe */) { - for (let i = maybeStart; i < maybeCount; i++) { - relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags); - } + resetMaybeStack( + /*markAllAsSucceeded*/ + true + ); + } else { + resetMaybeStack( + /*markAllAsSucceeded*/ + false + ); } - maybeCount = maybeStart; } } else { relation.set(id, (reportErrors2 ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags); - maybeCount = maybeStart; + resetMaybeStack( + /*markAllAsSucceeded*/ + false + ); } return result2; + function resetMaybeStack(markAllAsSucceeded) { + for (let i = maybeStart; i < maybeCount; i++) { + maybeKeysSet.delete(maybeKeys[i]); + if (markAllAsSucceeded) { + relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags); + } + } + maybeCount = maybeStart; + } } function structuredTypeRelatedTo(source2, target2, reportErrors2, intersectionState) { const saveErrorInfo = captureErrorCalculationState(); @@ -63538,26 +63678,6 @@ ${lanes.join("\n")} )) { return result2; } - if (sourceFlags & 8388608 /* IndexedAccess */) { - const indexType = source2.indexType; - if (indexType.flags & 4194304 /* Index */) { - const unresolvedIndexConstraint = getBaseConstraintOfType(indexType.type); - const indexConstraint = unresolvedIndexConstraint && unresolvedIndexConstraint !== noConstraintType ? getIndexType(unresolvedIndexConstraint) : keyofConstraintType; - const constraint2 = getIndexedAccessType(source2.objectType, indexConstraint); - if (result2 = isRelatedTo( - constraint2, - target2, - 1 /* Source */, - /*reportErrors*/ - false, - /*headMessage*/ - void 0, - intersectionState - )) { - return result2; - } - } - } if (isMappedTypeGenericIndexedAccess(source2)) { const indexConstraint = getConstraintOfType(source2.indexType); if (indexConstraint) { @@ -64954,7 +65074,8 @@ ${lanes.join("\n")} return !!elementType && isEmptyLiteralType(elementType); } function isTupleLikeType(type) { - return isTupleType(type) || !!getPropertyOfType(type, "0"); + let lengthType; + return isTupleType(type) || !!getPropertyOfType(type, "0") || isArrayLikeType(type) && !!(lengthType = getTypeOfPropertyOfType(type, "length")) && everyType(lengthType, (t) => !!(t.flags & 256 /* NumberLiteral */)); } function isArrayOrTupleLikeType(type) { return isArrayLikeType(type) || isTupleLikeType(type); @@ -64965,17 +65086,7 @@ ${lanes.join("\n")} return propType; } if (everyType(type, isTupleType)) { - return mapType(type, (t) => { - const tupleType = t; - const restType = getRestTypeOfTupleType(tupleType); - if (!restType) { - return undefinedType; - } - if (compilerOptions.noUncheckedIndexedAccess && index >= tupleType.target.fixedLength + getEndElementCount(tupleType.target, 3 /* Fixed */)) { - return getUnionType([restType, undefinedType]); - } - return restType; - }); + return getTupleElementTypeOutOfStartCount(type, index, compilerOptions.noUncheckedIndexedAccess ? undefinedType : void 0); } return void 0; } @@ -65043,6 +65154,19 @@ ${lanes.join("\n")} function getRestTypeOfTupleType(type) { return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength); } + function getTupleElementTypeOutOfStartCount(type, index, undefinedOrMissingType2) { + return mapType(type, (t) => { + const tupleType = t; + const restType = getRestTypeOfTupleType(tupleType); + if (!restType) { + return undefinedType; + } + if (undefinedOrMissingType2 && index >= getTotalFixedElementCount(tupleType.target)) { + return getUnionType([restType, undefinedOrMissingType2]); + } + return restType; + }); + } function getRestArrayTypeOfTupleType(type) { const restType = getRestTypeOfTupleType(type); return restType && createArrayType(restType); @@ -65577,17 +65701,18 @@ ${lanes.join("\n")} ); } function inferTypeForHomomorphicMappedType(source, target, constraint) { - if (inInferTypeForHomomorphicMappedType) { - return void 0; + const cacheKey = source.id + "," + target.id + "," + constraint.id; + if (reverseMappedCache.has(cacheKey)) { + return reverseMappedCache.get(cacheKey); } - const key = source.id + "," + target.id + "," + constraint.id; - if (reverseMappedCache.has(key)) { - return reverseMappedCache.get(key); + const recursionKey = source.id + "," + (target.target || target).id; + if (contains(homomorphicMappedTypeInferenceStack, recursionKey)) { + return void 0; } - inInferTypeForHomomorphicMappedType = true; + homomorphicMappedTypeInferenceStack.push(recursionKey); const type = createReverseMappedType(source, target, constraint); - inInferTypeForHomomorphicMappedType = false; - reverseMappedCache.set(key, type); + homomorphicMappedTypeInferenceStack.pop(); + reverseMappedCache.set(cacheKey, type); return type; } function isPartiallyInferableType(type) { @@ -66541,12 +66666,6 @@ ${lanes.join("\n")} } return links.resolvedSymbol; } - function isInTypeQuery(node) { - return !!findAncestor( - node, - (n) => n.kind === 186 /* TypeQuery */ ? true : n.kind === 80 /* Identifier */ || n.kind === 166 /* QualifiedName */ ? false : "quit" - ); - } function isInAmbientOrTypeNode(node) { return !!(node.flags & 33554432 /* Ambient */ || findAncestor(node, (n) => isInterfaceDeclaration(n) || isTypeAliasDeclaration(n) || isTypeLiteralNode(n))); } @@ -68044,12 +68163,15 @@ ${lanes.join("\n")} return narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue); } const target = getReferenceCandidate(expr.right); - const leftType = getTypeOfExpression(expr.left); - if (leftType.flags & 8576 /* StringOrNumberLiteralOrUnique */) { - if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target) && getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) { + if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target)) { + const leftType = getTypeOfExpression(expr.left); + if (isTypeUsableAsPropertyName(leftType) && getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) { return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */); } - if (isMatchingReference(reference, target)) { + } + if (isMatchingReference(reference, target)) { + const leftType = getTypeOfExpression(expr.left); + if (isTypeUsableAsPropertyName(leftType)) { return narrowTypeByInKeyword(type, leftType, assumeTrue); } } @@ -68497,8 +68619,8 @@ ${lanes.join("\n")} } const parent2 = getRootDeclaration(symbol.valueDeclaration).parent; const links = getNodeLinks(parent2); - if (!(links.flags & 524288 /* AssignmentsMarked */)) { - links.flags |= 524288 /* AssignmentsMarked */; + if (!(links.flags & 131072 /* AssignmentsMarked */)) { + links.flags |= 131072 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(parent2)) { markNodeAssignments(parent2); } @@ -68506,7 +68628,7 @@ ${lanes.join("\n")} return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!findAncestor(node.parent, (node2) => (isFunctionLike(node2) || isCatchClause(node2)) && !!(getNodeLinks(node2).flags & 524288 /* AssignmentsMarked */)); + return !!findAncestor(node.parent, (node2) => (isFunctionLike(node2) || isCatchClause(node2)) && !!(getNodeLinks(node2).flags & 131072 /* AssignmentsMarked */)); } function markNodeAssignments(node) { if (node.kind === 80 /* Identifier */) { @@ -68588,9 +68710,13 @@ ${lanes.join("\n")} symbol, /*excludes*/ 111551 /* Value */ - ) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */)) { + ) && !isInTypeQuery(location)) { const target = resolveAlias(symbol); - if (getAllSymbolFlags(target) & (111551 /* Value */ | 1048576 /* ExportValue */)) { + if (getSymbolFlags( + symbol, + /*excludeTypeOnlyMeanings*/ + true + ) & (111551 /* Value */ | 1048576 /* ExportValue */)) { if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); } else { @@ -68608,11 +68734,11 @@ ${lanes.join("\n")} const parent2 = declaration.parent.parent; if (parent2.kind === 260 /* VariableDeclaration */ && getCombinedNodeFlagsCached(declaration) & 6 /* Constant */ || parent2.kind === 169 /* Parameter */) { const links = getNodeLinks(parent2); - if (!(links.flags & 16777216 /* InCheckIdentifier */)) { - links.flags |= 16777216 /* InCheckIdentifier */; + if (!(links.flags & 4194304 /* InCheckIdentifier */)) { + links.flags |= 4194304 /* InCheckIdentifier */; const parentType = getTypeForBindingElementParent(parent2, 0 /* Normal */); const parentTypeConstraint = parentType && mapType(parentType, getBaseConstraintOrType); - links.flags &= ~16777216 /* InCheckIdentifier */; + links.flags &= ~4194304 /* InCheckIdentifier */; if (parentTypeConstraint && parentTypeConstraint.flags & 1048576 /* Union */ && !(parent2.kind === 169 /* Parameter */ && isSymbolAssigned(symbol))) { const pattern = declaration.parent; const narrowedType = getFlowTypeOfReference( @@ -68689,17 +68815,7 @@ ${lanes.join("\n")} } let declaration = localOrExportSymbol.valueDeclaration; if (declaration && localOrExportSymbol.flags & 32 /* Class */) { - if (declaration.kind === 263 /* ClassDeclaration */ && nodeIsDecorated(legacyDecorators, declaration)) { - let container = getContainingClass(node); - while (container !== void 0) { - if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 1048576 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 2097152 /* ConstructorReferenceInClass */; - break; - } - container = getContainingClass(container); - } - } else if (declaration.kind === 231 /* ClassExpression */) { + if (isClassLike(declaration) && declaration.name !== node) { let container = getThisContainer( node, /*includeArrowFunctions*/ @@ -68707,14 +68823,7 @@ ${lanes.join("\n")} /*includeClassComputedPropertyName*/ false ); - while (container.kind !== 312 /* SourceFile */) { - if (container.parent === declaration) { - if (isPropertyDeclaration(container) && isStatic(container) || isClassStaticBlockDeclaration(container)) { - getNodeLinks(declaration).flags |= 1048576 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 2097152 /* ConstructorReferenceInClass */; - } - break; - } + while (container.kind !== 312 /* SourceFile */ && container.parent !== declaration) { container = getThisContainer( container, /*includeArrowFunctions*/ @@ -68723,6 +68832,11 @@ ${lanes.join("\n")} false ); } + if (container.kind !== 312 /* SourceFile */) { + getNodeLinks(declaration).flags |= 262144 /* ContainsConstructorReference */; + getNodeLinks(container).flags |= 262144 /* ContainsConstructorReference */; + getNodeLinks(node).flags |= 536870912 /* ConstructorReference */; + } } } checkNestedBlockScopedBinding(node, symbol); @@ -68853,7 +68967,7 @@ ${lanes.join("\n")} if (isForStatement(container)) { const varDeclList = getAncestor(symbol.valueDeclaration, 261 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 65536 /* NeedsLoopOutParameter */; } } getNodeLinks(symbol.valueDeclaration).flags |= 32768 /* BlockScopedBindingInLoop */; @@ -69131,7 +69245,7 @@ ${lanes.join("\n")} if (!isCallExpression2 && languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */ && (isPropertyDeclaration(container) || isClassStaticBlockDeclaration(container))) { forEachEnclosingBlockScopeContainer(node.parent, (current) => { if (!isSourceFile(current) || isExternalOrCommonJsModule(current)) { - getNodeLinks(current).flags |= 8388608 /* ContainsSuperPropertyInStaticInitializer */; + getNodeLinks(current).flags |= 2097152 /* ContainsSuperPropertyInStaticInitializer */; } }); } @@ -70232,7 +70346,7 @@ ${lanes.join("\n")} /*resolvedTypePredicate*/ void 0, minArgCount, - (left.flags | right.flags) & 39 /* PropagatingFlags */ + (left.flags | right.flags) & 167 /* PropagatingFlags */ ); result.compositeKind = 2097152 /* Intersection */; result.compositeSignatures = concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); @@ -70316,6 +70430,10 @@ ${lanes.join("\n")} function hasDefaultValue(node) { return node.kind === 208 /* BindingElement */ && !!node.initializer || node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */; } + function isSpreadIntoCallOrNew(node) { + const parent2 = walkUpParenthesizedExpressions(node.parent); + return isSpreadElement(parent2) && isCallOrNewExpression(parent2.parent); + } function checkArrayLiteral(node, checkMode, forceTuple) { const elements = node.elements; const elementCount = elements.length; @@ -70323,14 +70441,13 @@ ${lanes.join("\n")} const elementFlags = []; pushCachedContextualType(node); const inDestructuringPattern = isAssignmentTarget(node); - const isSpreadIntoCallOrNew = isSpreadElement(node.parent) && isCallOrNewExpression(node.parent.parent); - const inConstContext = isSpreadIntoCallOrNew || isConstContext(node); + const inConstContext = isConstContext(node); const contextualType = getApparentTypeOfContextualType( node, /*contextFlags*/ void 0 ); - const inTupleContext = isSpreadIntoCallOrNew || !!contextualType && someType(contextualType, isTupleLikeType); + const inTupleContext = isSpreadIntoCallOrNew(node) || !!contextualType && someType(contextualType, isTupleLikeType); let hasOmittedExpression = false; for (let i = 0; i < elementCount; i++) { const e = elements[i]; @@ -71763,7 +71880,7 @@ ${lanes.join("\n")} } let diagnosticMessage; const declarationName = idText(right); - if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & 32 /* Static */) && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { + if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & 32 /* Static */) && (useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { diagnosticMessage = error2(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } else if (valueDeclaration.kind === 263 /* ClassDeclaration */ && node.parent.kind !== 183 /* TypeReference */ && !(valueDeclaration.flags & 33554432 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error2(right, Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -72670,7 +72787,7 @@ ${lanes.join("\n")} } } function getThisArgumentOfCall(node) { - const expression = node.kind === 213 /* CallExpression */ ? node.expression : node.kind === 215 /* TaggedTemplateExpression */ ? node.tag : void 0; + const expression = node.kind === 213 /* CallExpression */ ? node.expression : node.kind === 215 /* TaggedTemplateExpression */ ? node.tag : node.kind === 170 /* Decorator */ && !legacyDecorators ? node.expression : void 0; if (expression) { const callee = skipOuterExpressions(expression); if (isAccessExpression(callee)) { @@ -73258,7 +73375,7 @@ ${lanes.join("\n")} parameters.push(createCombinedSymbolFromTypes(symbols, mapDefined(candidates, (candidate) => tryGetTypeAtPosition(candidate, i)))); } const restParameterSymbols = mapDefined(candidates, (c) => signatureHasRestParameter(c) ? last(c.parameters) : void 0); - let flags = 0 /* None */; + let flags = 128 /* IsSignatureCandidateForOverloadFailure */; if (restParameterSymbols.length !== 0) { const type = createArrayType(getUnionType(mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); @@ -73982,6 +74099,8 @@ ${lanes.join("\n")} return returnType; } function checkDeprecatedSignature(signature, node) { + if (signature.flags & 128 /* IsSignatureCandidateForOverloadFailure */) + return; if (signature.declaration && signature.declaration.flags & 536870912 /* Deprecated */) { const suggestionNode = getDeprecatedSuggestionNode(node); const name = tryGetPropertyAccessOrIdentifierToString(getInvokedExpression(node)); @@ -74455,7 +74574,7 @@ ${lanes.join("\n")} } return restParameter.escapedName; } - function getParameterIdentifierNameAtPosition(signature, pos) { + function getParameterIdentifierInfoAtPosition(signature, pos) { var _a; if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 324 /* JSDocFunctionType */) { return void 0; @@ -74463,10 +74582,16 @@ ${lanes.join("\n")} const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { const param = signature.parameters[pos]; - return isParameterDeclarationWithIdentifierName(param) ? [param.escapedName, false] : void 0; + const paramIdent = getParameterDeclarationIdentifier(param); + return paramIdent ? { + parameter: paramIdent, + parameterName: param.escapedName, + isRestParameter: false + } : void 0; } const restParameter = signature.parameters[paramCount] || unknownSymbol; - if (!isParameterDeclarationWithIdentifierName(restParameter)) { + const restIdent = getParameterDeclarationIdentifier(restParameter); + if (!restIdent) { return void 0; } const restType = getTypeOfSymbol(restParameter); @@ -74475,18 +74600,19 @@ ${lanes.join("\n")} const index = pos - paramCount; const associatedName = associatedNames == null ? void 0 : associatedNames[index]; const isRestTupleElement = !!(associatedName == null ? void 0 : associatedName.dotDotDotToken); - return associatedName ? [ - getTupleElementLabel(associatedName), - isRestTupleElement - ] : void 0; + if (associatedName) { + Debug.assert(isIdentifier(associatedName.name)); + return { parameter: associatedName.name, parameterName: associatedName.name.escapedText, isRestParameter: isRestTupleElement }; + } + return void 0; } if (pos === paramCount) { - return [restParameter.escapedName, true]; + return { parameter: restIdent, parameterName: restParameter.escapedName, isRestParameter: true }; } return void 0; } - function isParameterDeclarationWithIdentifierName(symbol) { - return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name); + function getParameterDeclarationIdentifier(symbol) { + return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name) && symbol.valueDeclaration.name; } function isValidDeclarationForTupleLabel(d) { return d.kind === 202 /* NamedTupleMember */ || isParameter(d) && d.name && isIdentifier(d.name); @@ -77349,7 +77475,18 @@ ${lanes.join("\n")} addLazyDiagnostic(checkSignatureDeclarationDiagnostics); function checkSignatureDeclarationDiagnostics() { checkCollisionWithArgumentsInGeneratedCode(node); - const returnTypeNode = getEffectiveReturnTypeNode(node); + let returnTypeNode = getEffectiveReturnTypeNode(node); + let returnTypeErrorLocation = returnTypeNode; + if (isInJSFile(node)) { + const typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && isTypeReferenceNode(typeTag.typeExpression.type)) { + const signature = getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + if (signature && signature.declaration) { + returnTypeNode = getEffectiveReturnTypeNode(signature.declaration); + returnTypeErrorLocation = typeTag.typeExpression.type; + } + } + } if (noImplicitAny && !returnTypeNode) { switch (node.kind) { case 180 /* ConstructSignature */: @@ -77360,21 +77497,21 @@ ${lanes.join("\n")} break; } } - if (returnTypeNode) { + if (returnTypeNode && returnTypeErrorLocation) { const functionFlags2 = getFunctionFlags(node); if ((functionFlags2 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { const returnType = getTypeFromTypeNode(returnTypeNode); if (returnType === voidType) { - error2(returnTypeNode, Diagnostics.A_generator_cannot_have_a_void_type_annotation); + error2(returnTypeErrorLocation, Diagnostics.A_generator_cannot_have_a_void_type_annotation); } else { const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags2 & 2 /* Async */) !== 0) || anyType; const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags2 & 2 /* Async */) !== 0) || generatorYieldType; const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags2 & 2 /* Async */) !== 0) || unknownType; const generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags2 & 2 /* Async */)); - checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode); + checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeErrorLocation); } } else if ((functionFlags2 & 3 /* AsyncGenerator */) === 2 /* Async */) { - checkAsyncFunctionReturnType(node, returnTypeNode); + checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation); } } if (node.kind !== 181 /* IndexSignature */ && node.kind !== 324 /* JSDocFunctionType */) { @@ -77455,7 +77592,7 @@ ${lanes.join("\n")} case "length": case "caller": case "arguments": - if (compilerOptions.useDefineForClassFields) { + if (useDefineForClassFields) { break; } case "prototype": @@ -77557,7 +77694,7 @@ ${lanes.join("\n")} function setNodeLinksForPrivateIdentifierScope(node) { if (isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { for (let lexicalScope = getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = getEnclosingBlockScopeContainer(lexicalScope)) { - getNodeLinks(lexicalScope).flags |= 4194304 /* ContainsClassWithPrivateIdentifiers */; + getNodeLinks(lexicalScope).flags |= 1048576 /* ContainsClassWithPrivateIdentifiers */; } if (isClassExpression(node.parent)) { const enclosingIterationStatement = getEnclosingIterationStatement(node.parent); @@ -77603,7 +77740,7 @@ ${lanes.join("\n")} if (classExtendsNull) { error2(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - const superCallShouldBeRootLevel = (getEmitScriptTarget(compilerOptions) !== 99 /* ESNext */ || !useDefineForClassFields) && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p) => hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */))); + const superCallShouldBeRootLevel = !emitStandardClassFields && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p) => hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */))); if (superCallShouldBeRootLevel) { if (!superCallIsRootLevelInConstructor(superCall, node.body)) { error2(superCall, Diagnostics.A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers); @@ -78456,7 +78593,7 @@ ${lanes.join("\n")} } return typeAsAwaitable.awaitedTypeOfType = type; } - function checkAsyncFunctionReturnType(node, returnTypeNode) { + function checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation) { const returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { if (isErrorType(returnType)) { @@ -78467,7 +78604,7 @@ ${lanes.join("\n")} true ); if (globalPromiseType !== emptyGenericType && !isReferenceToType2(returnType, globalPromiseType)) { - error2(returnTypeNode, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedTypeNoAlias(returnType) || voidType)); + reportErrorForInvalidReturnType(Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, returnTypeNode, returnTypeErrorLocation, typeToString(getAwaitedTypeNoAlias(returnType) || voidType)); return; } } else { @@ -78477,7 +78614,7 @@ ${lanes.join("\n")} } const promiseConstructorName = getEntityNameFromTypeNode(returnTypeNode); if (promiseConstructorName === void 0) { - error2(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, typeToString(returnType)); return; } const promiseConstructorSymbol = resolveEntityName( @@ -78492,9 +78629,9 @@ ${lanes.join("\n")} /*reportErrors*/ false )) { - error2(returnTypeNode, Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + error2(returnTypeErrorLocation, Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { - error2(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, entityNameToString(promiseConstructorName)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); } return; } @@ -78503,15 +78640,16 @@ ${lanes.join("\n")} true ); if (globalPromiseConstructorLikeType === emptyObjectType) { - error2(returnTypeNode, Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, entityNameToString(promiseConstructorName)); + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); return; } - if (!checkTypeAssignableTo( - promiseConstructorType, - globalPromiseConstructorLikeType, - returnTypeNode, - Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value - )) { + const headMessage = Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value; + const errorInfo = () => returnTypeNode === returnTypeErrorLocation ? void 0 : chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type + ); + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeErrorLocation, headMessage, errorInfo)) { return; } const rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); @@ -78533,6 +78671,14 @@ ${lanes.join("\n")} node, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member ); + function reportErrorForInvalidReturnType(message, returnTypeNode2, returnTypeErrorLocation2, typeName) { + if (returnTypeNode2 === returnTypeErrorLocation2) { + error2(returnTypeErrorLocation2, message, typeName); + } else { + const diag2 = error2(returnTypeErrorLocation2, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + addRelatedInfo(diag2, createDiagnosticForNode(returnTypeNode2, message, typeName)); + } + } } function checkDecorator(node) { const signature = getResolvedSignature(node); @@ -78759,6 +78905,7 @@ ${lanes.join("\n")} for (const parameter of containingSignature.parameters) { markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(containingSignature)); break; } } @@ -79300,7 +79447,7 @@ ${lanes.join("\n")} } function checkWeakMapSetCollision(node) { const enclosingBlockScope = getEnclosingBlockScopeContainer(node); - if (getNodeCheckFlags(enclosingBlockScope) & 4194304 /* ContainsClassWithPrivateIdentifiers */) { + if (getNodeCheckFlags(enclosingBlockScope) & 1048576 /* ContainsClassWithPrivateIdentifiers */) { Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier"); errorSkippedOn("noEmit", node, Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText); } @@ -79314,18 +79461,18 @@ ${lanes.join("\n")} let hasCollision = false; if (isClassExpression(node)) { for (const member of node.members) { - if (getNodeCheckFlags(member) & 8388608 /* ContainsSuperPropertyInStaticInitializer */) { + if (getNodeCheckFlags(member) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { hasCollision = true; break; } } } else if (isFunctionExpression(node)) { - if (getNodeCheckFlags(node) & 8388608 /* ContainsSuperPropertyInStaticInitializer */) { + if (getNodeCheckFlags(node) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { hasCollision = true; } } else { const container = getEnclosingBlockScopeContainer(node); - if (container && getNodeCheckFlags(container) & 8388608 /* ContainsSuperPropertyInStaticInitializer */) { + if (container && getNodeCheckFlags(container) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { hasCollision = true; } } @@ -79360,9 +79507,6 @@ ${lanes.join("\n")} if ((getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */) !== 0 || isParameterDeclaration(node)) { return; } - if (node.kind === 260 /* VariableDeclaration */ && !node.initializer) { - return; - } const symbol = getSymbolOfDeclaration(node); if (symbol.flags & 1 /* FunctionScopedVariable */) { if (!isIdentifier(node.name)) @@ -80872,7 +81016,7 @@ ${lanes.join("\n")} node ); const willTransformPrivateElementsOrClassStaticBlocks = languageVersion <= 9 /* ES2022 */; - const willTransformInitializers = !useDefineForClassFields || languageVersion < 9 /* ES2022 */; + const willTransformInitializers = !emitStandardClassFields; if (willTransformStaticElementsOfDecoratedClass || willTransformPrivateElementsOrClassStaticBlocks) { for (const member of node.members) { if (willTransformStaticElementsOfDecoratedClass && classElementOrClassElementParameterIsDecorated( @@ -81630,10 +81774,22 @@ ${lanes.join("\n")} return +expr.text; case 217 /* ParenthesizedExpression */: return evaluate(expr.expression, location); - case 80 /* Identifier */: - if (isInfinityOrNaNString(expr.escapedText)) { - return +expr.escapedText; + case 80 /* Identifier */: { + const identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText) && resolveEntityName( + identifier, + 111551 /* Value */, + /*ignoreErrors*/ + true + ) === getGlobalSymbol( + identifier.escapedText, + 111551 /* Value */, + /*diagnostic*/ + void 0 + )) { + return +identifier.escapedText; } + } case 211 /* PropertyAccessExpression */: if (isEntityNameExpression(expr)) { const symbol = resolveEntityName( @@ -81972,7 +82128,7 @@ ${lanes.join("\n")} } return; } - const targetFlags = getAllSymbolFlags(target); + const targetFlags = getSymbolFlags(target); const excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) | (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (targetFlags & excludedMeanings) { const message = node.kind === 281 /* ExportSpecifier */ ? Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; @@ -82130,7 +82286,7 @@ ${lanes.join("\n")} if (node.moduleReference.kind !== 283 /* ExternalModuleReference */) { const target = resolveAlias(getSymbolOfDeclaration(node)); if (target !== unknownSymbol) { - const targetFlags = getAllSymbolFlags(target); + const targetFlags = getSymbolFlags(target); if (targetFlags & 111551 /* Value */) { const moduleName = getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { @@ -82270,7 +82426,7 @@ ${lanes.join("\n")} markExportAsReferenced(node); } const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol); - if (!target || getAllSymbolFlags(target) & 111551 /* Value */) { + if (!target || getSymbolFlags(target) & 111551 /* Value */) { checkExpressionCached(node.propertyName || node.name); } } @@ -82315,7 +82471,7 @@ ${lanes.join("\n")} )); if (sym) { markAliasReferenced(sym, id); - if (getAllSymbolFlags(sym) & 111551 /* Value */) { + if (getSymbolFlags(sym) & 111551 /* Value */) { checkExpressionCached(id); if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && getTypeOnlyAliasDeclaration(sym, 111551 /* Value */)) { error2( @@ -82936,7 +83092,7 @@ ${lanes.join("\n")} function copyLocallyVisibleExportSymbols(source, meaning2) { if (meaning2) { source.forEach((symbol) => { - if (!getDeclarationOfKind(symbol, 281 /* ExportSpecifier */) && !getDeclarationOfKind(symbol, 280 /* NamespaceExport */)) { + if (!getDeclarationOfKind(symbol, 281 /* ExportSpecifier */) && !getDeclarationOfKind(symbol, 280 /* NamespaceExport */) && symbol.escapedName !== "default" /* Default */) { copySymbol(symbol, meaning2); } }); @@ -83562,7 +83718,7 @@ ${lanes.join("\n")} return symbolLinks2.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(getAllSymbolFlags(s) & 111551 /* Value */); + return s && !!(getSymbolFlags(s) & 111551 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -83692,7 +83848,11 @@ ${lanes.join("\n")} case 276 /* ImportSpecifier */: case 281 /* ExportSpecifier */: const symbol = getSymbolOfDeclaration(node); - return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */); + return !!symbol && isAliasResolvedToValue( + symbol, + /*excludeTypeOnlyValues*/ + true + ); case 278 /* ExportDeclaration */: const exportClause = node.exportClause; return !!exportClause && (isNamespaceExport(exportClause) || some(exportClause.elements, isValueAliasDeclaration)); @@ -83709,7 +83869,7 @@ ${lanes.join("\n")} const isValue = isAliasResolvedToValue(getSymbolOfDeclaration(node)); return isValue && node.moduleReference && !nodeIsMissing(node.moduleReference); } - function isAliasResolvedToValue(symbol) { + function isAliasResolvedToValue(symbol, excludeTypeOnlyValues) { if (!symbol) { return false; } @@ -83717,7 +83877,12 @@ ${lanes.join("\n")} if (target === unknownSymbol) { return true; } - return !!((getAllSymbolFlags(target) ?? -1) & 111551 /* Value */) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); + return !!(getSymbolFlags( + symbol, + excludeTypeOnlyValues, + /*excludeLocalMeanings*/ + true + ) & 111551 /* Value */) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -83731,7 +83896,7 @@ ${lanes.join("\n")} return true; } const target = getSymbolLinks(symbol).aliasTarget; - if (target && getEffectiveModifierFlags(node) & 1 /* Export */ && getAllSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { + if (target && getEffectiveModifierFlags(node) & 1 /* Export */ && getSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { return true; } } @@ -91353,7 +91518,7 @@ ${lanes.join("\n")} const constantValue = tryGetConstEnumValue(node); if (constantValue !== void 0) { setConstantValue(node, constantValue); - const substitute = typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : factory2.createNumericLiteral(constantValue); + const substitute = typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : constantValue < 0 ? factory2.createPrefixUnaryExpression(41 /* MinusToken */, factory2.createNumericLiteral(Math.abs(constantValue))) : factory2.createNumericLiteral(constantValue); if (!compilerOptions.removeComments) { const originalNode = getOriginalNode(node, isAccessExpression); addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, ` ${safeMultiLineComment(getTextOfNode(originalNode))} `); @@ -91786,6 +91951,11 @@ ${lanes.join("\n")} } } } + function getClassThis() { + const lex = getClassLexicalEnvironment(); + const classThis = lex.classThis ?? lex.classConstructor ?? (currentClassContainer == null ? void 0 : currentClassContainer.name); + return Debug.checkDefined(classThis); + } function transformAutoAccessor(node) { const commentRange = getCommentRange(node); const sourceMapRange = getSourceMapRange(node); @@ -91812,11 +91982,13 @@ ${lanes.join("\n")} setOriginalNode(backingField, node); setEmitFlags(backingField, 3072 /* NoComments */); setSourceMapRange(backingField, sourceMapRange); - const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName); + const receiver = isStatic(node) ? getClassThis() : factory2.createThis(); + const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName, receiver); setOriginalNode(getter, node); setCommentRange(getter, commentRange); setSourceMapRange(getter, sourceMapRange); - const setter = createAccessorPropertySetRedirector(factory2, node, modifiers, setterName); + const setterModifiers = factory2.createModifiersFromModifierFlags(modifiersToFlags(modifiers)); + const setter = createAccessorPropertySetRedirector(factory2, node, setterModifiers, setterName, receiver); setOriginalNode(setter, node); setEmitFlags(setter, 3072 /* NoComments */); setSourceMapRange(setter, sourceMapRange); @@ -92373,6 +92545,7 @@ ${lanes.join("\n")} return filter(node.members, isNonStaticMethodOrAccessorWithPrivateName); } function getClassFacts(node) { + var _a; let facts = 0 /* None */; const original = getOriginalNode(node); if (isClassDeclaration(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) { @@ -92389,6 +92562,8 @@ ${lanes.join("\n")} if (isStatic(member)) { if (member.name && (isPrivateIdentifier(member.name) || isAutoAccessorPropertyDeclaration(member)) && shouldTransformPrivateElementsOrClassStaticBlocks) { facts |= 2 /* NeedsClassConstructorReference */; + } else if (isAutoAccessorPropertyDeclaration(member) && shouldTransformAutoAccessors === -1 /* True */ && !node.name && !((_a = node.emitNode) == null ? void 0 : _a.classThis)) { + facts |= 2 /* NeedsClassConstructorReference */; } if (isPropertyDeclaration(member) || isClassStaticBlockDeclaration(member)) { if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* ContainsLexicalThis */) { @@ -92409,6 +92584,9 @@ ${lanes.join("\n")} containsInstancePrivateElements || (containsInstancePrivateElements = isPrivateIdentifierClassElementDeclaration(member)); } else if (isPrivateIdentifierClassElementDeclaration(member)) { containsInstancePrivateElements = true; + if (resolver.getNodeCheckFlags(member) & 262144 /* ContainsConstructorReference */) { + facts |= 2 /* NeedsClassConstructorReference */; + } } else if (isPropertyDeclaration(member)) { containsPublicInstanceFields = true; containsInitializedPublicInstanceFields || (containsInitializedPublicInstanceFields = !!member.initializer); @@ -92509,10 +92687,11 @@ ${lanes.join("\n")} getClassLexicalEnvironment().classConstructor = factory2.cloneNode(temp); pendingClassReferenceAssignment = factory2.createAssignment(temp, factory2.getInternalName(node)); } - if ((_b = node.emitNode) == null ? void 0 : _b.classThis) { - getClassLexicalEnvironment().classThis = node.emitNode.classThis; - } } + if ((_b = node.emitNode) == null ? void 0 : _b.classThis) { + getClassLexicalEnvironment().classThis = node.emitNode.classThis; + } + const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */; const isExport = hasSyntacticModifier(node, 1 /* Export */); const isDefault = hasSyntacticModifier(node, 1024 /* Default */); let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); @@ -92547,6 +92726,11 @@ ${lanes.join("\n")} ) )); } + const alias = getClassLexicalEnvironment().classConstructor; + if (isClassWithConstructorReference && alias) { + enableSubstitutionForClassAliases(); + classAliases[getOriginalNodeId(node)] = alias; + } const classDecl = factory2.updateClassDeclaration( node, modifiers, @@ -92569,14 +92753,14 @@ ${lanes.join("\n")} var _a, _b, _c; const isDecoratedClassDeclaration = !!(facts & 1 /* ClassWasDecorated */); const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); - const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 1048576 /* ClassWithConstructorReference */; + const classCheckFlags = resolver.getNodeCheckFlags(node); + const isClassWithConstructorReference = classCheckFlags & 262144 /* ContainsConstructorReference */; let temp; function createClassTempVar() { var _a2; if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a2 = node.emitNode) == null ? void 0 : _a2.classThis)) { return getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; } - const classCheckFlags = resolver.getNodeCheckFlags(node); const requiresBlockScopedVar = classCheckFlags & 32768 /* BlockScopedBindingInLoop */; const temp2 = factory2.createTempVariable( requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, @@ -93543,7 +93727,7 @@ ${lanes.join("\n")} } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 2097152 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -94409,7 +94593,7 @@ ${lanes.join("\n")} } } function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 1048576 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */) { enableSubstitutionForClassAliases(); const classAlias = factory2.createUniqueName(node.name && !isGeneratedIdentifier(node.name) ? idText(node.name) : "default"); classAliases[getOriginalNodeId(node)] = classAlias; @@ -94442,7 +94626,7 @@ ${lanes.join("\n")} } function trySubstituteClassAlias(node) { if (classAliases) { - if (resolver.getNodeCheckFlags(node) & 2097152 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -94474,6 +94658,7 @@ ${lanes.join("\n")} endLexicalEnvironment, hoistVariableDeclaration } = context; + const languageVersion = getEmitScriptTarget(context.getCompilerOptions()); let top; let classInfo; let classThis; @@ -95975,6 +96160,17 @@ ${lanes.join("\n")} function transformDecorator(decorator) { const expression = visitNode(decorator.expression, visitor, isExpression); setEmitFlags(expression, 3072 /* NoComments */); + const innerExpression = skipOuterExpressions(expression); + if (isAccessExpression(innerExpression)) { + const { target, thisArg } = factory2.createCallBinding( + expression, + hoistVariableDeclaration, + languageVersion, + /*cacheIdentifiers*/ + true + ); + return factory2.restoreOuterExpressions(expression, factory2.createFunctionBindCall(target, thisArg, [])); + } return expression; } function createDescriptorMethod(original, name, modifiers, asteriskToken, kind, parameters, body) { @@ -99607,10 +99803,10 @@ ${lanes.join("\n")} for (const prop of attr.expression.properties) { if (isSpreadAssignment(prop)) { finishObjectLiteralIfNeeded(); - expressions.push(prop.expression); + expressions.push(Debug.checkDefined(visitNode(prop.expression, visitor, isExpression))); continue; } - properties.push(prop); + properties.push(Debug.checkDefined(visitNode(prop, visitor))); } continue; } @@ -102673,10 +102869,10 @@ ${lanes.join("\n")} name )); const checkFlags = resolver.getNodeCheckFlags(decl); - if (checkFlags & 262144 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { + if (checkFlags & 65536 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { const outParamName = factory2.createUniqueName("out_" + idText(name)); let flags = 0 /* None */; - if (checkFlags & 262144 /* NeedsLoopOutParameter */) { + if (checkFlags & 65536 /* NeedsLoopOutParameter */) { flags |= 1 /* Body */; } if (isForStatement(container)) { @@ -113736,7 +113932,7 @@ ${lanes.join("\n")} return !(expression.numericLiteralFlags & 448 /* WithSpecifier */) && !stringContains(text, tokenToString(25 /* DotToken */)) && !stringContains(text, String.fromCharCode(69 /* E */)) && !stringContains(text, String.fromCharCode(101 /* e */)); } else if (isAccessExpression(expression)) { const constantValue = getConstantValue(expression); - return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue; + return typeof constantValue === "number" && isFinite(constantValue) && constantValue >= 0 && Math.floor(constantValue) === constantValue; } } function emitElementAccessExpression(node) { @@ -116931,14 +117127,14 @@ ${lanes.join("\n")} }); // src/compiler/watchUtilities.ts - function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames2) { if (!host.getDirectories || !host.readDirectory) { return void 0; } const cachedReadDirectoryResult = /* @__PURE__ */ new Map(); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); return { - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, fileExists, readFile: (path, encoding) => host.readFile(path, encoding), directoryExists: host.directoryExists && directoryExists, @@ -117060,7 +117256,7 @@ ${lanes.join("\n")} const rootResult = tryReadDirectory2(rootDir, rootDirPath); let rootSymLinkResult; if (rootResult !== void 0) { - return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); + return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames2, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { @@ -117255,7 +117451,7 @@ ${lanes.join("\n")} program, extraFileExtensions, currentDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 }) { @@ -117271,7 +117467,7 @@ ${lanes.join("\n")} writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); return true; } - if (isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) { + if (isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames2, currentDirectory)) { writeLog(`Project: ${configFileName} Detected excluded file: ${fileOrDirectory}`); return true; } @@ -117328,7 +117524,7 @@ ${lanes.join("\n")} function createExcludeHandlingAddWatch(key) { return (file, cb, flags, options, detailInfo1, detailInfo2) => { var _a; - return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call( + return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call( /*thisArgs*/ void 0, file, @@ -117340,7 +117536,7 @@ ${lanes.join("\n")} ) : excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2); }; } - function useCaseSensitiveFileNames() { + function useCaseSensitiveFileNames2() { return typeof host.useCaseSensitiveFileNames === "boolean" ? host.useCaseSensitiveFileNames : host.useCaseSensitiveFileNames(); } function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) { @@ -119358,6 +119554,14 @@ ${lanes.join("\n")} case 265 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); return "skip"; + case 176 /* Constructor */: + case 174 /* MethodDeclaration */: + case 262 /* FunctionDeclaration */: + if (!node.body) { + diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Signature_declarations_can_only_be_used_in_TypeScript_files)); + return "skip"; + } + return; case 266 /* EnumDeclaration */: const enumKeyword = Debug.checkDefined(tokenToString(94 /* EnumKeyword */)); diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); @@ -121272,6 +121476,9 @@ ${lanes.join("\n")} return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); }, readFile: (f) => directoryStructureHost.readFile(f), + directoryExists: maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: maybeBind(directoryStructureHost, directoryStructureHost.realpath), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: () => host.getCurrentDirectory(), onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || returnUndefined, @@ -124467,12 +124674,12 @@ ${lanes.join("\n")} return true; const isJsonFile = fileExtensionIs(fileName, ".json" /* Json */); const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); - const useCaseSensitiveFileNames = program.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = program.useCaseSensitiveFileNames(); return find((_b = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs, (includeSpec) => { if (isJsonFile && !endsWith(includeSpec, ".json" /* Json */)) return false; const pattern = getPatternFromSpec(includeSpec, basePath, "files"); - return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames).test(fileName); + return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames2).test(fileName); }); } function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) { @@ -124676,7 +124883,7 @@ ${lanes.join("\n")} return result; } function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost = host) { - const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); const compilerHost = { getSourceFile: createGetSourceFile( (fileName, encoding) => !encoding ? compilerHost.readFile(fileName) : host.readFile(fileName, encoding), @@ -124692,8 +124899,8 @@ ${lanes.join("\n")} (path) => host.directoryExists(path) ), getCurrentDirectory: memoize(() => host.getCurrentDirectory()), - useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, - getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames), + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2, + getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames2), getNewLine: () => getNewLineCharacter(getCompilerOptions()), fileExists: (f) => host.fileExists(f), readFile: (f) => host.readFile(f), @@ -124974,7 +125181,7 @@ ${lanes.join("\n")} const sourceFilesCache = /* @__PURE__ */ new Map(); let missingFilePathsRequestedForRelease; let hasChangedCompilerOptions = false; - const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); const currentDirectory = host.getCurrentDirectory(); const { configFileName, optionsToExtend: optionsToExtendForConfigFile = {}, watchOptionsToExtend, extraFileExtensions, createProgram: createProgram2 } = host; let { rootFiles: rootFileNames, options: compilerOptions, watchOptions, projectReferences } = host; @@ -124982,7 +125189,7 @@ ${lanes.join("\n")} let configFileParsingDiagnostics; let canConfigFileJsonReportNoInputFiles = false; let hasChangedConfigFileParsingErrors = false; - const cachedDirectoryStructureHost = configFileName === void 0 ? void 0 : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + const cachedDirectoryStructureHost = configFileName === void 0 ? void 0 : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames2); const directoryStructureHost = cachedDirectoryStructureHost || host; const parseConfigFileHost = parseConfigHostFromCompilerHostLike(host, directoryStructureHost); let newLine = updateNewLine(); @@ -125000,8 +125207,8 @@ ${lanes.join("\n")} Debug.assert(compilerOptions); Debug.assert(rootFileNames); const { watchFile: watchFile2, watchDirectory, writeLog } = createWatchFactory(host, compilerOptions); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); - writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames}`); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); + writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames2}`); let configFileWatcher; if (configFileName) { configFileWatcher = watchFile2(configFileName, scheduleProgramReload, 2e3 /* High */, watchOptions, WatchType.ConfigFile); @@ -125110,7 +125317,6 @@ ${lanes.join("\n")} if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { - debugger; resolutionCache.onChangesAffectModuleResolution(); } } @@ -125507,7 +125713,7 @@ ${lanes.join("\n")} options: compilerOptions, program: getCurrentBuilderProgram() || rootFileNames, currentDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 })) @@ -125597,7 +125803,7 @@ ${lanes.join("\n")} options: config.parsedCommandLine.options, program: config.parsedCommandLine.fileNames, currentDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 })) @@ -128375,6 +128581,8 @@ ${lanes.join("\n")} ScriptElementKind2["enumMemberElement"] = "enum member"; ScriptElementKind2["variableElement"] = "var"; ScriptElementKind2["localVariableElement"] = "local var"; + ScriptElementKind2["variableUsingElement"] = "using"; + ScriptElementKind2["variableAwaitUsingElement"] = "await using"; ScriptElementKind2["functionElement"] = "function"; ScriptElementKind2["localFunctionElement"] = "local function"; ScriptElementKind2["memberFunctionElement"] = "method"; @@ -131062,13 +131270,16 @@ ${lanes.join("\n")} return !(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */); } function getDefaultLikeExportNameFromDeclaration(symbol) { - return firstDefined( - symbol.declarations, - (d) => { - var _a, _b; - return isExportAssignment(d) ? (_a = tryCast(skipOuterExpressions(d.expression), isIdentifier)) == null ? void 0 : _a.text : (_b = tryCast(getNameOfDeclaration(d), isIdentifier)) == null ? void 0 : _b.text; + return firstDefined(symbol.declarations, (d) => { + var _a, _b, _c; + if (isExportAssignment(d)) { + return (_a = tryCast(skipOuterExpressions(d.expression), isIdentifier)) == null ? void 0 : _a.text; } - ); + if (isExportSpecifier(d) && d.symbol.flags === 2097152 /* Alias */) { + return (_b = tryCast(d.propertyName, isIdentifier)) == null ? void 0 : _b.text; + } + return (_c = tryCast(getNameOfDeclaration(d), isIdentifier)) == null ? void 0 : _c.text; + }); } function getSymbolParentOrFail(symbol) { var _a; @@ -131508,10 +131719,10 @@ ${lanes.join("\n")} } function forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, cb) { var _a, _b; - const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); + const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); const excludePatterns = preferences.autoImportFileExcludePatterns && mapDefined(preferences.autoImportFileExcludePatterns, (spec) => { const pattern = getPatternFromSpec(spec, "", "exclude"); - return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames) : void 0; + return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames2) : void 0; }); forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, (module2, file) => cb( module2, @@ -133007,12 +133218,12 @@ ${lanes.join("\n")} function isDocumentRegistryEntry(entry) { return !!entry.sourceFile; } - function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { - return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + function createDocumentRegistry(useCaseSensitiveFileNames2, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory); } - function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory = "", externalCache) { + function createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory = "", externalCache) { const buckets = /* @__PURE__ */ new Map(); - const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); + const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames2); function reportStats() { const bucketInfoArray = arrayFrom(buckets.keys()).filter((name) => name && name.charAt(0) === "_").map((name) => { const entries = buckets.get(name); @@ -133221,12 +133432,12 @@ ${lanes.join("\n")} // src/services/getEditsForFileRename.ts function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { - const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); const newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts_textChanges_exports.ChangeTracker.with({ host, formatContext, preferences }, (changeTracker) => { - updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames2); updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } @@ -133248,7 +133459,7 @@ ${lanes.join("\n")} const rel = getRelativePathFromFile(a0, b0, getCanonicalFileName); return combinePathsSafe(getDirectoryPath(a1), rel); } - function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { + function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames2) { const { configFile } = program.getCompilerOptions(); if (!configFile) return; @@ -133272,10 +133483,10 @@ ${lanes.join("\n")} /*excludes*/ [], includes, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, currentDirectory ); - if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(oldFileOrDirPath) && !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(newFileOrDirPath)) { changeTracker.insertNodeAfter(configFile, last(property.initializer.elements), factory.createStringLiteral(relativePath(newFileOrDirPath))); } return; @@ -133323,7 +133534,7 @@ ${lanes.join("\n")} configDir, path, /*ignoreCase*/ - !useCaseSensitiveFileNames + !useCaseSensitiveFileNames2 ); } } @@ -134275,7 +134486,7 @@ ${lanes.join("\n")} "src/services/sourcemaps.ts"() { "use strict"; init_ts4(); - base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+/=]+)$)?/; } }); @@ -134323,8 +134534,8 @@ ${lanes.join("\n")} diags.push(createDiagnosticForNode(init, Diagnostics.require_call_may_be_converted_to_an_import)); } } - const jsdocTypedefNode = ts_codefix_exports.getJSDocTypedefNode(node); - if (jsdocTypedefNode) { + const jsdocTypedefNodes = ts_codefix_exports.getJSDocTypedefNodes(node); + for (const jsdocTypedefNode of jsdocTypedefNodes) { diags.push(createDiagnosticForNode(jsdocTypedefNode, Diagnostics.JSDoc_typedef_may_be_converted_to_TypeScript_type)); } if (ts_codefix_exports.parameterShouldGetTypeFromJSDoc(node)) { @@ -136330,7 +136541,7 @@ ${lanes.join("\n")} if (!isIdentifier(token)) { return void 0; } - if (isInitializedVariable(parent2) && isVariableDeclarationInVariableStatement(parent2)) { + if (isInitializedVariable(parent2) && isVariableDeclarationInVariableStatement(parent2) && isIdentifier(parent2.name)) { if (((_a = checker.getMergedSymbol(parent2.symbol).declarations) == null ? void 0 : _a.length) !== 1) { return { error: getLocaleSpecificMessage(Diagnostics.Variables_with_multiple_declarations_cannot_be_inlined) }; } @@ -136637,7 +136848,7 @@ ${lanes.join("\n")} const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax); if (typeof targetFile !== "string") { if (targetFile.statements.length > 0) { - changes.insertNodesAfter(targetFile, targetFile.statements[targetFile.statements.length - 1], body); + moveStatementsToTargetFile(changes, program, body, targetFile, toMove); } else { changes.insertNodesAtEndOfFile( targetFile, @@ -136658,7 +136869,7 @@ ${lanes.join("\n")} } } if (importAdder) { - importAdder.writeFixes(changes); + importAdder.writeFixes(changes, quotePreference); } if (imports.length && body.length) { return [ @@ -137224,25 +137435,25 @@ ${lanes.join("\n")} const { file } = context; const range = createTextRangeFromSpan(getRefactorContextSpan(context)); const { statements } = file; - const startNodeIndex = findIndex(statements, (s) => s.end > range.pos); + let startNodeIndex = findIndex(statements, (s) => s.end > range.pos); if (startNodeIndex === -1) return void 0; const startStatement = statements[startNodeIndex]; - if (isNamedDeclaration(startStatement) && startStatement.name && rangeContainsRange(startStatement.name, range)) { - return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; - } const overloadRangeToMove = getOverloadRangeToMove(file, startStatement); if (overloadRangeToMove) { - return overloadRangeToMove; + startNodeIndex = overloadRangeToMove.start; + } + let endNodeIndex = findIndex(statements, (s) => s.end >= range.end, startNodeIndex); + if (endNodeIndex !== -1 && range.end <= statements[endNodeIndex].getStart()) { + endNodeIndex--; + } + const endingOverloadRangeToMove = getOverloadRangeToMove(file, statements[endNodeIndex]); + if (endingOverloadRangeToMove) { + endNodeIndex = endingOverloadRangeToMove.end; } - if (range.pos > startStatement.getStart(file)) - return void 0; - const afterEndNodeIndex = findIndex(statements, (s) => s.end > range.end, startNodeIndex); - if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) - return void 0; return { - toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), - afterLast: afterEndNodeIndex === -1 ? void 0 : statements[afterEndNodeIndex] + toMove: statements.slice(startNodeIndex, endNodeIndex === -1 ? statements.length : endNodeIndex + 1), + afterLast: endNodeIndex === -1 ? void 0 : statements[endNodeIndex + 1] }; } function getStatementsToMove(context) { @@ -137430,16 +137641,79 @@ ${lanes.join("\n")} return false; } } + function moveStatementsToTargetFile(changes, program, statements, targetFile, toMove) { + var _a; + const removedExports = /* @__PURE__ */ new Set(); + const targetExports = (_a = targetFile.symbol) == null ? void 0 : _a.exports; + if (targetExports) { + const checker = program.getTypeChecker(); + const targetToSourceExports = /* @__PURE__ */ new Map(); + for (const node of toMove.all) { + if (isTopLevelDeclarationStatement(node) && hasSyntacticModifier(node, 1 /* Export */)) { + forEachTopLevelDeclaration(node, (declaration) => { + var _a2; + const targetDeclarations = canHaveSymbol(declaration) ? (_a2 = targetExports.get(declaration.symbol.escapedName)) == null ? void 0 : _a2.declarations : void 0; + const exportDeclaration = firstDefined(targetDeclarations, (d) => isExportDeclaration(d) ? d : isExportSpecifier(d) ? tryCast(d.parent.parent, isExportDeclaration) : void 0); + if (exportDeclaration && exportDeclaration.moduleSpecifier) { + targetToSourceExports.set( + exportDeclaration, + (targetToSourceExports.get(exportDeclaration) || /* @__PURE__ */ new Set()).add(declaration) + ); + } + }); + } + } + for (const [exportDeclaration, topLevelDeclarations] of arrayFrom(targetToSourceExports)) { + if (exportDeclaration.exportClause && isNamedExports(exportDeclaration.exportClause) && length(exportDeclaration.exportClause.elements)) { + const elements = exportDeclaration.exportClause.elements; + const updatedElements = filter(elements, (elem) => find(skipAlias(elem.symbol, checker).declarations, (d) => isTopLevelDeclaration(d) && topLevelDeclarations.has(d)) === void 0); + if (length(updatedElements) === 0) { + changes.deleteNode(targetFile, exportDeclaration); + removedExports.add(exportDeclaration); + continue; + } + if (length(updatedElements) < length(elements)) { + changes.replaceNode( + targetFile, + exportDeclaration, + factory.updateExportDeclaration( + exportDeclaration, + exportDeclaration.modifiers, + exportDeclaration.isTypeOnly, + factory.updateNamedExports(exportDeclaration.exportClause, factory.createNodeArray(updatedElements, elements.hasTrailingComma)), + exportDeclaration.moduleSpecifier, + exportDeclaration.assertClause + ) + ); + } + } + } + } + const lastReExport = findLast(targetFile.statements, (n) => isExportDeclaration(n) && !!n.moduleSpecifier && !removedExports.has(n)); + if (lastReExport) { + changes.insertNodesBefore( + targetFile, + lastReExport, + statements, + /*blankLineBetween*/ + true + ); + } else { + changes.insertNodesAfter(targetFile, targetFile.statements[targetFile.statements.length - 1], statements); + } + } function getOverloadRangeToMove(sourceFile, statement) { if (isFunctionLikeDeclaration(statement)) { const declarations = statement.symbol.declarations; if (declarations === void 0 || length(declarations) <= 1 || !contains(declarations, statement)) { return void 0; } + const firstDecl = declarations[0]; const lastDecl = declarations[length(declarations) - 1]; const statementsToMove = mapDefined(declarations, (d) => getSourceFileOfNode(d) === sourceFile && isStatement(d) ? d : void 0); - const end = findLastIndex(sourceFile.statements, (s) => s.end > lastDecl.end); - return { toMove: statementsToMove, afterLast: end >= 0 ? sourceFile.statements[end] : void 0 }; + const end = findIndex(sourceFile.statements, (s) => s.end >= lastDecl.end); + const start = findIndex(sourceFile.statements, (s) => s.end >= firstDecl.end); + return { toMove: statementsToMove, start, end }; } return void 0; } @@ -137486,7 +137760,7 @@ ${lanes.join("\n")} if (host.fileExists(targetFile) && program.getSourceFile(targetFile) === void 0) { return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_statements_to_the_selected_file)); } - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context, context.file, interactiveRefactorArguments.targetFile, program, statements, t, context.host, context.preferences)); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context, context.file, interactiveRefactorArguments.targetFile, context.program, statements, t, context.host, context.preferences)); return { edits, renameFilename: void 0, renameLocation: void 0 }; } return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_to_file_selected_file_is_invalid)); @@ -141465,10 +141739,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} host.log(message); } } - const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); - const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const sourceMapper = getSourceMapper({ - useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2, getCurrentDirectory: () => currentDirectory, getProgram, fileExists: maybeBind(host, host.fileExists), @@ -141516,7 +141790,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} getSourceFileByPath: getOrCreateSourceFileByPath, getCancellationToken: () => cancellationToken, getCanonicalFileName, - useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2, getNewLine: () => getNewLineCharacter(newSettings), getDefaultLibFileName: (options2) => host.getDefaultLibFileName(options2), writeFile: noop, @@ -141560,9 +141834,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} compilerHost.getSourceFile = getSourceFileWithCache; (_c = host.setCompilerHost) == null ? void 0 : _c.call(host, compilerHost); const parseConfigHost = { - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, fileExists: (fileName) => compilerHost.fileExists(fileName), readFile: (fileName) => compilerHost.readFile(fileName), + directoryExists: (f) => compilerHost.directoryExists(f), + getDirectories: (f) => compilerHost.getDirectories(f), + realpath: compilerHost.realpath, readDirectory: (...args) => compilerHost.readDirectory(...args), trace: compilerHost.trace, getCurrentDirectory: compilerHost.getCurrentDirectory, @@ -142435,7 +142712,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return result; function escapeRegExp(str) { - return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); + return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&"); } function getTodoCommentsRegExp() { const singleLineCommentStart = /(?:\/\/+\s*)/.source; @@ -148188,23 +148465,60 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }); // src/services/codefixes/convertTypedefToType.ts - function doChange12(changes, node, sourceFile) { - if (isJSDocTypedefTag(node)) { - fixSingleTypeDef(changes, node, sourceFile); - } - } - function fixSingleTypeDef(changes, typeDefNode, sourceFile) { - if (!typeDefNode) + function doChange12(changes, node, sourceFile, newLine, fixAll = false) { + if (!isJSDocTypedefTag(node)) return; - const declaration = createDeclaration(typeDefNode); + const declaration = createDeclaration(node); if (!declaration) return; - const comment = typeDefNode.parent; - changes.replaceNode( - sourceFile, - comment, - declaration + const commentNode = node.parent; + const { leftSibling, rightSibling } = getLeftAndRightSiblings(node); + let pos = commentNode.getStart(); + let prefix = ""; + if (!leftSibling && commentNode.comment) { + pos = findEndOfTextBetween(commentNode, commentNode.getStart(), node.getStart()); + prefix = `${newLine} */${newLine}`; + } + if (leftSibling) { + if (fixAll && isJSDocTypedefTag(leftSibling)) { + pos = node.getStart(); + prefix = ""; + } else { + pos = findEndOfTextBetween(commentNode, leftSibling.getStart(), node.getStart()); + prefix = `${newLine} */${newLine}`; + } + } + let end = commentNode.getEnd(); + let suffix = ""; + if (rightSibling) { + if (fixAll && isJSDocTypedefTag(rightSibling)) { + end = rightSibling.getStart(); + suffix = `${newLine}${newLine}`; + } else { + end = rightSibling.getStart(); + suffix = `${newLine}/**${newLine} * `; + } + } + changes.replaceRange(sourceFile, { pos, end }, declaration, { prefix, suffix }); + } + function getLeftAndRightSiblings(typedefNode) { + const commentNode = typedefNode.parent; + const maxChildIndex = commentNode.getChildCount() - 1; + const currentNodeIndex = commentNode.getChildren().findIndex( + (n) => n.getStart() === typedefNode.getStart() && n.getEnd() === typedefNode.getEnd() ); + const leftSibling = currentNodeIndex > 0 ? commentNode.getChildAt(currentNodeIndex - 1) : void 0; + const rightSibling = currentNodeIndex < maxChildIndex ? commentNode.getChildAt(currentNodeIndex + 1) : void 0; + return { leftSibling, rightSibling }; + } + function findEndOfTextBetween(jsDocComment, from, to) { + const comment = jsDocComment.getText().substring(from - jsDocComment.getStart(), to - jsDocComment.getStart()); + for (let i = comment.length; i > 0; i--) { + if (!/[*/\s]/g.test(comment.substring(i - 1, i))) { + return from + i; + } + } + return to; } function createDeclaration(tag) { var _a; @@ -148225,7 +148539,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const propertySignatures = createSignatureFromTypeLiteral(typeLiteral); if (!some(propertySignatures)) return; - const interfaceDeclaration = factory.createInterfaceDeclaration( + return factory.createInterfaceDeclaration( /*modifiers*/ void 0, typeName, @@ -148235,13 +148549,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} void 0, propertySignatures ); - return interfaceDeclaration; } function createTypeAliasForTypeExpression(typeName, typeExpression) { const typeReference = getSynthesizedDeepClone(typeExpression.type); if (!typeReference) return; - const declaration = factory.createTypeAliasDeclaration( + return factory.createTypeAliasDeclaration( /*modifiers*/ void 0, factory.createIdentifier(typeName), @@ -148249,7 +148562,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} void 0, typeReference ); - return declaration; } function createSignatureFromTypeLiteral(typeLiteral) { const propertyTags = typeLiteral.jsDocPropertyTags; @@ -148269,30 +148581,28 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (typeReference && name) { const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0; - const prop = factory.createPropertySignature( + return factory.createPropertySignature( /*modifiers*/ void 0, name, questionToken, typeReference ); - return prop; } }; - const props = mapDefined(propertyTags, getSignature); - return props; + return mapDefined(propertyTags, getSignature); } function getPropertyName(tag) { return tag.name.kind === 80 /* Identifier */ ? tag.name.text : tag.name.right.text; } - function getJSDocTypedefNode(node) { + function getJSDocTypedefNodes(node) { if (hasJSDocNodes(node)) { - return forEach(node.jsDoc, (node2) => { + return flatMap(node.jsDoc, (doc) => { var _a; - return (_a = node2.tags) == null ? void 0 : _a.find(isJSDocTypedefTag); + return (_a = doc.tags) == null ? void 0 : _a.filter((tag) => isJSDocTypedefTag(tag)); }); } - return void 0; + return []; } var fixId14, errorCodes15; var init_convertTypedefToType = __esm({ @@ -148306,13 +148616,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} fixIds: [fixId14], errorCodes: errorCodes15, getCodeActions(context) { + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); const node = getTokenAtPosition( context.sourceFile, context.span.start ); if (!node) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, node, context.sourceFile)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, node, context.sourceFile, newLineCharacter)); if (changes.length > 0) { return [ createCodeFixAction( @@ -148325,11 +148636,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} ]; } }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes15, (changes, diag2) => { - const node = getTokenAtPosition(diag2.file, diag2.start); - if (node) - doChange12(changes, node, diag2.file); - }) + getAllCodeActions: (context) => codeFixAll( + context, + errorCodes15, + (changes, diag2) => { + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); + const node = getTokenAtPosition(diag2.file, diag2.start); + const fixAll = true; + if (node) + doChange12(changes, node, diag2.file, newLineCharacter, fixAll); + } + ) }); } }); @@ -148642,8 +148959,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return `${topLevelTypeOnly ? 1 : 0}|${moduleSpecifier}`; } } - function writeFixes(changeTracker) { - const quotePreference = getQuotePreference(sourceFile, preferences); + function writeFixes(changeTracker, oldFileQuotePreference) { + let quotePreference; + if (sourceFile.imports.length === 0 && oldFileQuotePreference !== void 0) { + quotePreference = oldFileQuotePreference; + } else { + quotePreference = getQuotePreference(sourceFile, preferences); + } for (const fix of addToNamespace) { addNamespaceQualifier(changeTracker, sourceFile, fix); } @@ -148946,6 +149268,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (compilerOptions.configFile) { return getEmitModuleKind(compilerOptions) < 5 /* ES2015 */; } + if (sourceFile.impliedNodeFormat === 1 /* CommonJS */) + return true; + if (sourceFile.impliedNodeFormat === 99 /* ESNext */) + return false; for (const otherFile of program.getSourceFiles()) { if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) continue; @@ -149418,6 +149744,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function promoteImportClause(importClause) { changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(importClause, sourceFile)); + if (!compilerOptions.allowImportingTsExtensions) { + const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(importClause.parent); + const resolvedModule = moduleSpecifier && getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation(sourceFile, moduleSpecifier)); + if (resolvedModule == null ? void 0 : resolvedModule.resolvedUsingTsExtension) { + const changedExtension = changeAnyExtension(moduleSpecifier.text, getOutputExtension(moduleSpecifier.text, compilerOptions)); + changes.replaceNode(sourceFile, moduleSpecifier, factory.createStringLiteral(changedExtension)); + } + } if (convertExistingToTypeOnly) { const namedImports = tryCast(importClause.namedBindings, isNamedImports); if (namedImports && namedImports.elements.length > 1) { @@ -150595,6 +150929,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!declaration || !isCallExpression(declaration.parent) || !declaration.body) return void 0; const pos = declaration.parent.arguments.indexOf(declaration); + if (pos === -1) + return void 0; const type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos); if (!type) return void 0; @@ -151691,7 +152027,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} ); } function getSuggestion(messageText) { - const [_, suggestion] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/\'(.*)\'/) || []; + const [_, suggestion] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/'(.*)'/) || []; return suggestion; } var fixId28, errorCodes34; @@ -154020,15 +154356,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement, body, preserveOptional = 3 /* All */, isAmbient = false) { const declarations = symbol.getDeclarations(); - const declaration = declarations == null ? void 0 : declarations[0]; + const declaration = firstOrUndefined(declarations); const checker = context.program.getTypeChecker(); const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); const kind = (declaration == null ? void 0 : declaration.kind) ?? 171 /* PropertySignature */; - const declarationName = getSynthesizedDeepClone( - getNameOfDeclaration(declaration), - /*includeTrivia*/ - false - ); + const declarationName = createDeclarationName(symbol, declaration); const effectiveModifierFlags = declaration ? getEffectiveModifierFlags(declaration) : 0 /* None */; let modifierFlags = effectiveModifierFlags & 32 /* Static */; modifierFlags |= effectiveModifierFlags & 4 /* Public */ ? 4 /* Public */ : effectiveModifierFlags & 16 /* Protected */ ? 16 /* Protected */ : 0 /* None */; @@ -154179,6 +154511,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} false ); } + function createDeclarationName(symbol2, declaration2) { + if (getCheckFlags(symbol2) & 262144 /* Mapped */) { + const nameType = symbol2.links.nameType; + if (nameType && isTypeUsableAsPropertyName(nameType)) { + return factory.createIdentifier(unescapeLeadingUnderscores(getPropertyNameFromType(nameType))); + } + } + return getSynthesizedDeepClone( + getNameOfDeclaration(declaration2), + /*includeTrivia*/ + false + ); + } } function createSignatureDeclarationFromSignature(kind, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder) { const program = context.program; @@ -155834,7 +156179,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} getFixes: () => getFixes, getImportCompletionAction: () => getImportCompletionAction, getImportKind: () => getImportKind, - getJSDocTypedefNode: () => getJSDocTypedefNode, + getJSDocTypedefNodes: () => getJSDocTypedefNodes, getNoopSymbolTrackerWithResolver: () => getNoopSymbolTrackerWithResolver, getPromoteTypeOnlyCompletionAction: () => getPromoteTypeOnlyCompletionAction, getSupportedErrorCodes: () => getSupportedErrorCodes, @@ -156897,6 +157242,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} data = originToCompletionEntryData(origin); hasAction = !importStatementCompletion; } + const parentNamedImportOrExport = findAncestor(location, isNamedImportsOrExports); + if ((parentNamedImportOrExport == null ? void 0 : parentNamedImportOrExport.kind) === 275 /* NamedImports */) { + const possibleToken = stringToToken(name); + if (parentNamedImportOrExport && possibleToken && (possibleToken === 135 /* AwaitKeyword */ || isNonContextualKeyword(possibleToken))) { + insertText = `${name} as ${name}_`; + } + } return { name, kind: ts_SymbolDisplay_exports.getSymbolKind(typeChecker, symbol, location), @@ -157677,7 +158029,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source, cancellationToken) { if (data == null ? void 0 : data.moduleSpecifier) { - if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken).replacementSpan) { + if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken, sourceFile).replacementSpan) { return { codeActions: void 0, sourceDisplay: [textPart(data.moduleSpecifier)] }; } } @@ -157844,7 +158196,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return { kind: 1 /* JsDocTagName */ }; } else { const lineStart = getLineStartPositionForPosition(position, sourceFile); - if (!/[^\*|\s(/)]/.test(sourceFile.text.substring(lineStart, position))) { + if (!/[^*|\s(/)]/.test(sourceFile.text.substring(lineStart, position))) { return { kind: 2 /* JsDocTag */ }; } } @@ -157890,7 +158242,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let isNewIdentifierLocation = false; let flags = 0 /* None */; if (contextToken) { - const importStatementCompletionInfo = getImportStatementCompletionInfo(contextToken); + const importStatementCompletionInfo = getImportStatementCompletionInfo(contextToken, sourceFile); if (importStatementCompletionInfo.keywordCompletion) { if (importStatementCompletionInfo.isKeywordOnlyCompletion) { return { @@ -158143,24 +158495,34 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } } - if (!isTypeLocation) { + if (!isTypeLocation || isInTypeQuery(node)) { typeChecker.tryGetThisTypeAt( node, /*includeGlobalThis*/ false ); let type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); - let insertQuestionDot = false; - if (type.isNullableType()) { - const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false; - if (canCorrectToQuestionDot || isRightOfQuestionDot) { - type = type.getNonNullableType(); - if (canCorrectToQuestionDot) { - insertQuestionDot = true; + if (!isTypeLocation) { + let insertQuestionDot = false; + if (type.isNullableType()) { + const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } } } + addTypeProperties(type, !!(node.flags & 65536 /* AwaitContext */), insertQuestionDot); + } else { + addTypeProperties( + type.getNonNullableType(), + /*insertAwait*/ + false, + /*insertQuestionDot*/ + false + ); } - addTypeProperties(type, !!(node.flags & 65536 /* AwaitContext */), insertQuestionDot); } } function addTypeProperties(type, insertAwait, insertQuestionDot) { @@ -158206,7 +158568,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const leftMostName = getLeftMostName(computedPropertyName.expression); const nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); const firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); - if (firstAccessibleSymbol && addToSeen(seenPropertySymbols, getSymbolId(firstAccessibleSymbol))) { + const firstAccessibleSymbolId = firstAccessibleSymbol && getSymbolId(firstAccessibleSymbol); + if (firstAccessibleSymbolId && addToSeen(seenPropertySymbols, firstAccessibleSymbolId)) { const index = symbols.length; symbols.push(firstAccessibleSymbol); const moduleSymbol = firstAccessibleSymbol.parent; @@ -158236,6 +158599,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } } else if (preferences.includeCompletionsWithInsertText) { + if (firstAccessibleSymbolId && seenPropertySymbols.has(firstAccessibleSymbolId)) { + return; + } addSymbolOriginInfo(symbol); addSymbolSortInfo(symbol); symbols.push(symbol); @@ -159365,6 +159731,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return cls; } break; + case 81 /* PrivateIdentifier */: + if (tryCast(location.parent, isPropertyDeclaration)) { + return findAncestor(location, isClassLike); + } + break; case 80 /* Identifier */: { const originalKeywordKind = identifierToKeywordKind(location); if (originalKeywordKind) { @@ -159521,7 +159892,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return void 0; } - function getImportStatementCompletionInfo(contextToken) { + function getImportStatementCompletionInfo(contextToken, sourceFile) { var _a, _b, _c; let keywordCompletion; let isKeywordOnlyCompletion = false; @@ -159537,6 +159908,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getCandidate() { const parent2 = contextToken.parent; if (isImportEqualsDeclaration(parent2)) { + const lastToken = parent2.getLastToken(sourceFile); + if (isIdentifier(contextToken) && lastToken !== contextToken) { + keywordCompletion = 161 /* FromKeyword */; + isKeywordOnlyCompletion = true; + return void 0; + } keywordCompletion = contextToken.kind === 156 /* TypeKeyword */ ? void 0 : 156 /* TypeKeyword */; return isModuleSpecifierMissingOrEmpty(parent2.moduleReference) ? parent2 : void 0; } @@ -160104,7 +160481,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} extensionOptions, host, /*moduleSpecifierIsRelative*/ - false, + true, scriptPath ).values()); } @@ -160436,16 +160813,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const fragmentDirectory = fragmentHasPath ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0; const expandedPrefixDirectory = fragmentHasPath ? combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; const normalizedSuffix = normalizePath(parsed.suffix); + const declarationExtension = normalizedSuffix && getDeclarationEmitExtensionForPath("_" + normalizedSuffix); + const matchingSuffixes = declarationExtension ? [changeExtension(normalizedSuffix, declarationExtension), normalizedSuffix] : [normalizedSuffix]; const baseDirectory = normalizePath(combinePaths(packageDirectory, expandedPrefixDirectory)); const completePrefix = fragmentHasPath ? baseDirectory : ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - const includeGlob = normalizedSuffix ? "**/*" + normalizedSuffix : "./*"; + const includeGlobs = normalizedSuffix ? matchingSuffixes.map((suffix) => "**/*" + suffix) : ["./*"]; const matches = mapDefined(tryReadDirectory( host, baseDirectory, extensionOptions.extensionsToSearch, /*exclude*/ void 0, - [includeGlob] + includeGlobs ), (match) => { const trimmedWithPattern = trimPrefixAndSuffix(match); if (trimmedWithPattern) { @@ -160459,8 +160838,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const directories = normalizedSuffix ? emptyArray : mapDefined(tryGetDirectories(host, baseDirectory), (dir) => dir === "node_modules" ? void 0 : directoryResult(dir)); return [...matches, ...directories]; function trimPrefixAndSuffix(path) { - const inner = withoutStartAndEnd(normalizePath(path), completePrefix, normalizedSuffix); - return inner === void 0 ? void 0 : removeLeadingDirectorySeparator(inner); + return firstDefined(matchingSuffixes, (suffix) => { + const inner = withoutStartAndEnd(normalizePath(path), completePrefix, suffix); + return inner === void 0 ? void 0 : removeLeadingDirectorySeparator(inner); + }); } } function withoutStartAndEnd(s, start, end) { @@ -163689,6 +164070,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function shouldShowLiteralParameterNameHintsOnly(preferences) { return preferences.includeInlayParameterNameHints === "literals"; } + function shouldUseInteractiveInlayHints(preferences) { + return preferences.interactiveInlayHints === true; + } function provideInlayHints(context) { const { file, program, span, cancellationToken, preferences } = context; const sourceFileText = file.text; @@ -163739,17 +164123,26 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function isSignatureSupportingReturnAnnotation(node) { return isArrowFunction(node) || isFunctionExpression(node) || isFunctionDeclaration(node) || isMethodDeclaration(node) || isGetAccessorDeclaration(node); } - function addParameterHints(text, position, isFirstVariadicArgument) { + function addParameterHints(text, parameter, position, isFirstVariadicArgument, sourceFile) { + let hintText = `${isFirstVariadicArgument ? "..." : ""}${text}`; + let displayParts; + if (shouldUseInteractiveInlayHints(preferences)) { + displayParts = [getNodeDisplayPart(hintText, parameter, sourceFile), { text: ":" }]; + hintText = ""; + } else { + hintText += ":"; + } result.push({ - text: `${isFirstVariadicArgument ? "..." : ""}${truncation(text, maxHintsLength)}:`, + text: hintText, position, kind: "Parameter" /* Parameter */, - whitespaceAfter: true + whitespaceAfter: true, + displayParts }); } function addTypeHints(text, position) { result.push({ - text: `: ${truncation(text, maxHintsLength)}`, + text: `: ${text.length > maxTypeHintLength ? text.substr(0, maxTypeHintLength - "...".length) + "..." : text}`, position, kind: "Type" /* Type */, whitespaceBefore: true @@ -163757,7 +164150,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function addEnumMemberValueHints(text, position) { result.push({ - text: `= ${truncation(text, maxHintsLength)}`, + text: `= ${text}`, position, kind: "Enum" /* Enum */, whitespaceBefore: true @@ -163807,6 +164200,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return; } let signatureParamPos = 0; + const sourceFile = shouldUseInteractiveInlayHints(preferences) ? expr.getSourceFile() : void 0; for (const originalArg of args) { const arg = skipParentheses(originalArg); if (shouldShowLiteralParameterNameHintsOnly(preferences) && !isHintableLiteral(arg)) { @@ -163827,10 +164221,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } } - const identifierNameInfo = checker.getParameterIdentifierNameAtPosition(signature, signatureParamPos); + const identifierInfo = checker.getParameterIdentifierInfoAtPosition(signature, signatureParamPos); signatureParamPos = signatureParamPos + (spreadArgs || 1); - if (identifierNameInfo) { - const [parameterName, isFirstVariadicArgument] = identifierNameInfo; + if (identifierInfo) { + const { parameter, parameterName, isRestParameter: isFirstVariadicArgument } = identifierInfo; const isParameterNameNotSameAsArgument = preferences.includeInlayParameterNameHintsWhenArgumentMatchesName || !identifierOrAccessExpressionPostfixMatchesParameterName(arg, parameterName); if (!isParameterNameNotSameAsArgument && !isFirstVariadicArgument) { continue; @@ -163839,7 +164233,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (leadingCommentsContainsParameterName(arg, name)) { continue; } - addParameterHints(name, originalArg.getStart(), isFirstVariadicArgument); + addParameterHints(name, parameter, originalArg.getStart(), isFirstVariadicArgument, sourceFile); } } } @@ -163945,12 +164339,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return printTypeInSingleLine(signatureParamType); } - function truncation(text, maxLength2) { - if (text.length > maxLength2) { - return text.substr(0, maxLength2 - "...".length) + "..."; - } - return text; - } function printTypeInSingleLine(type) { const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; const printer = createPrinterWithRemoveComments(); @@ -163981,13 +164369,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return true; } + function getNodeDisplayPart(text, node, sourceFile) { + return { + text, + span: createTextSpanFromNode(node, sourceFile), + file: sourceFile.fileName + }; + } } - var maxHintsLength, leadingParameterNameCommentRegexFactory; + var maxTypeHintLength, leadingParameterNameCommentRegexFactory; var init_inlayHints = __esm({ "src/services/inlayHints.ts"() { "use strict"; init_ts4(); - maxHintsLength = 30; + maxTypeHintLength = 30; leadingParameterNameCommentRegexFactory = (name) => { return new RegExp(`^\\s?/\\*\\*?\\s?${name}\\s?\\*\\/\\s?$`); }; @@ -166418,6 +166813,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return "parameter" /* parameterElement */; } else if (symbol.valueDeclaration && isVarConst(symbol.valueDeclaration)) { return "const" /* constElement */; + } else if (symbol.valueDeclaration && isVarUsing(symbol.valueDeclaration)) { + return "using" /* variableUsingElement */; + } else if (symbol.valueDeclaration && isVarAwaitUsing(symbol.valueDeclaration)) { + return "await using" /* variableAwaitUsingElement */; } else if (forEach(symbol.declarations, isLet)) { return "let" /* letElement */; } @@ -166485,7 +166884,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return modifiers.size > 0 ? arrayFrom(modifiers.values()).join(",") : "" /* none */; } - function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning = getMeaningFromLocation(location), alias) { + function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, symbol, sourceFile, enclosingDeclaration, location, type, semanticMeaning, alias) { var _a; const displayParts = []; let documentation = []; @@ -166494,7 +166893,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; let hasAddedSymbolInfo = false; const isThisExpression = location.kind === 110 /* ThisKeyword */ && isInExpressionContext(location) || isThisInTypeQuery(location); - let type; let documentationFromAlias; let tagsFromAlias; let hasMultipleSignatures = false; @@ -166523,7 +166921,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } let signature; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + type ?? (type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location)); if (location.parent && location.parent.kind === 211 /* PropertyAccessExpression */) { const right = location.parent.name; if (right === location || right && right.getFullWidth() === 0) { @@ -166738,12 +167136,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (declarationName && !hasAddedSymbolInfo) { const isExternalModuleDeclaration = isModuleWithStringLiteralName(resolvedNode) && hasSyntacticModifier(resolvedNode, 2 /* Ambient */); const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; - const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind( + const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKindWorker( typeChecker, resolvedSymbol, getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, + type, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol ); @@ -166811,7 +167210,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); } - if (symbolKind === "property" /* memberVariableElement */ || symbolKind === "accessor" /* memberAccessorVariableElement */ || symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */ || symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || symbolKind === "index" /* indexSignatureElement */ || isThisExpression) { + if (symbolKind === "property" /* memberVariableElement */ || symbolKind === "accessor" /* memberAccessorVariableElement */ || symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */ || symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || symbolKind === "index" /* indexSignatureElement */ || symbolKind === "using" /* variableUsingElement */ || symbolKind === "await using" /* variableAwaitUsingElement */ || isThisExpression) { displayParts.push(punctuationPart(59 /* ColonToken */)); displayParts.push(spacePart()); if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */ && symbolKind !== "index" /* indexSignatureElement */) { @@ -166961,6 +167360,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case "let" /* letElement */: case "const" /* constElement */: case "constructor" /* constructorImplementationElement */: + case "using" /* variableUsingElement */: + case "await using" /* variableAwaitUsingElement */: displayParts.push(textOrKeywordPart(symbolKind2)); return; default: @@ -166996,6 +167397,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} addRange(displayParts, typeParameterParts); } } + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning = getMeaningFromLocation(location), alias) { + return getSymbolDisplayPartsDocumentationAndSymbolKindWorker( + typeChecker, + symbol, + sourceFile, + enclosingDeclaration, + location, + /*type*/ + void 0, + semanticMeaning, + alias + ); + } function isLocalVariableOrFunction(symbol) { if (symbol.parent) { return false; @@ -167775,6 +168189,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} insertNodeBefore(sourceFile, before, newNode, blankLineBetween = false, options = {}) { this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNode, this.getOptionsForInsertNodeBefore(before, newNode, blankLineBetween)); } + insertNodesBefore(sourceFile, before, newNodes, blankLineBetween = false, options = {}) { + this.insertNodesAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNodes, this.getOptionsForInsertNodeBefore(before, first(newNodes), blankLineBetween)); + } insertModifierAt(sourceFile, pos, modifier, options = {}) { this.insertNodeAt(sourceFile, pos, factory.createToken(modifier), options); } @@ -172089,6 +172506,7 @@ ${options.prefix}` : "\n" : options.prefix getEmitModuleKind: () => getEmitModuleKind, getEmitModuleResolutionKind: () => getEmitModuleResolutionKind, getEmitScriptTarget: () => getEmitScriptTarget, + getEmitStandardClassFields: () => getEmitStandardClassFields, getEnclosingBlockScopeContainer: () => getEnclosingBlockScopeContainer, getEnclosingContainer: () => getEnclosingContainer, getEncodedSemanticClassifications: () => getEncodedSemanticClassifications, @@ -172308,6 +172726,7 @@ ${options.prefix}` : "\n" : options.prefix getPropertyAssignmentAliasLikeExpression: () => getPropertyAssignmentAliasLikeExpression, getPropertyNameForPropertyNameNode: () => getPropertyNameForPropertyNameNode, getPropertyNameForUniqueESSymbol: () => getPropertyNameForUniqueESSymbol, + getPropertyNameFromType: () => getPropertyNameFromType, getPropertyNameOfBindingOrAssignmentElement: () => getPropertyNameOfBindingOrAssignmentElement, getPropertySymbolFromBindingElement: () => getPropertySymbolFromBindingElement, getPropertySymbolsFromContextualType: () => getPropertySymbolsFromContextualType, @@ -172763,6 +173182,7 @@ ${options.prefix}` : "\n" : options.prefix isInString: () => isInString, isInTemplateString: () => isInTemplateString, isInTopLevelContext: () => isInTopLevelContext, + isInTypeQuery: () => isInTypeQuery, isIncrementalCompilation: () => isIncrementalCompilation, isIndexSignatureDeclaration: () => isIndexSignatureDeclaration, isIndexedAccessTypeNode: () => isIndexedAccessTypeNode, @@ -173140,6 +173560,7 @@ ${options.prefix}` : "\n" : options.prefix isTypeQueryNode: () => isTypeQueryNode, isTypeReferenceNode: () => isTypeReferenceNode, isTypeReferenceType: () => isTypeReferenceType, + isTypeUsableAsPropertyName: () => isTypeUsableAsPropertyName, isUMDExportSymbol: () => isUMDExportSymbol, isUnaryExpression: () => isUnaryExpression, isUnaryExpressionWithWrite: () => isUnaryExpressionWithWrite, diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index cb9c80467f4d5..b106df24d82bd 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -507,7 +507,7 @@ function identity(x) { function toLowerCase(x) { return x.toLowerCase(); } -var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g; +var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_. ]+/g; function toFileNameLowerCase(x) { return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x; } @@ -759,8 +759,8 @@ function unorderedRemoveFirstItemWhere(array, predicate) { } return false; } -function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames ? identity : toFileNameLowerCase; +function createGetCanonicalFileName(useCaseSensitiveFileNames2) { + return useCaseSensitiveFileNames2 ? identity : toFileNameLowerCase; } function patternText({ prefix, suffix }) { return `${prefix}*${suffix}`; @@ -1067,7 +1067,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, return func.name; } else { const text = Function.prototype.toString.call(func); - const match = /^function\s+([\w\$]+)\s*\(/.exec(text); + const match = /^function\s+([\w$]+)\s*\(/.exec(text); return match ? match[1] : ""; } } @@ -1850,7 +1850,7 @@ ${lanes.join("\n")} })(Debug || (Debug = {})); // src/compiler/semver.ts -var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; +var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; var prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; @@ -3193,7 +3193,8 @@ var SignatureFlags = /* @__PURE__ */ ((SignatureFlags4) => { SignatureFlags4[SignatureFlags4["IsOuterCallChain"] = 16] = "IsOuterCallChain"; SignatureFlags4[SignatureFlags4["IsUntypedSignatureInJSFile"] = 32] = "IsUntypedSignatureInJSFile"; SignatureFlags4[SignatureFlags4["IsNonInferrable"] = 64] = "IsNonInferrable"; - SignatureFlags4[SignatureFlags4["PropagatingFlags"] = 39] = "PropagatingFlags"; + SignatureFlags4[SignatureFlags4["IsSignatureCandidateForOverloadFailure"] = 128] = "IsSignatureCandidateForOverloadFailure"; + SignatureFlags4[SignatureFlags4["PropagatingFlags"] = 167] = "PropagatingFlags"; SignatureFlags4[SignatureFlags4["CallChainFlags"] = 24] = "CallChainFlags"; return SignatureFlags4; })(SignatureFlags || {}); @@ -3586,10 +3587,10 @@ function createDynamicPriorityPollingWatchFile(host) { pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === 250 /* Low */ ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingInterval === 250 /* Low */ ? "pollLowPollingIntervalQueue" : "pollPollingIntervalQueue", pollingIntervalQueue(pollingInterval)); } } -function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) { +function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2) { const fileWatcherCallbacks = createMultiMap(); const dirWatchers = /* @__PURE__ */ new Map(); - const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames); + const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames2); return nonPollingWatchFile; function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) { const filePath = toCanonicalName(fileName); @@ -3665,8 +3666,8 @@ function createFixedChunkSizePollingWatchFile(host) { pollScheduled = host.setTimeout(pollQueue, 2e3 /* High */, "pollQueue"); } } -function createSingleWatcherPerName(cache, useCaseSensitiveFileNames, name, callback, createWatcher) { - const toCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); +function createSingleWatcherPerName(cache, useCaseSensitiveFileNames2, name, callback, createWatcher) { + const toCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const path2 = toCanonicalFileName(name); const existing = cache.get(path2); if (existing) { @@ -3715,7 +3716,7 @@ function sysLog(s) { } function createDirectoryWatcherSupportingRecursive({ watchDirectory, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, getAccessibleSortedChildDirectories, fileSystemEntryExists, @@ -3727,8 +3728,8 @@ function createDirectoryWatcherSupportingRecursive({ const callbackCache = createMultiMap(); const cacheToUpdateChildWatches = /* @__PURE__ */ new Map(); let timerToUpdateChildWatches; - const filePathComparer = getStringComparer(!useCaseSensitiveFileNames); - const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames); + const filePathComparer = getStringComparer(!useCaseSensitiveFileNames2); + const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames2); return (dirName, callback, recursive, options) => recursive ? createDirectoryWatcher(dirName, options, callback) : watchDirectory(dirName, callback, recursive, options); function createDirectoryWatcher(dirName, options, callback) { const dirPath = toCanonicalFilePath(dirName); @@ -3895,12 +3896,12 @@ function createDirectoryWatcherSupportingRecursive({ } } function isIgnoredPath(path2, options) { - return some(ignoredPaths, (searchPath) => isInPath(path2, searchPath)) || isIgnoredByWatchOptions(path2, options, useCaseSensitiveFileNames, getCurrentDirectory); + return some(ignoredPaths, (searchPath) => isInPath(path2, searchPath)) || isIgnoredByWatchOptions(path2, options, useCaseSensitiveFileNames2, getCurrentDirectory); } function isInPath(path2, searchPath) { if (stringContains(path2, searchPath)) return true; - if (useCaseSensitiveFileNames) + if (useCaseSensitiveFileNames2) return false; return stringContains(toCanonicalFilePath(path2), searchPath); } @@ -3918,14 +3919,14 @@ function createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModi } }; } -function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames, getCurrentDirectory) { - return ((options == null ? void 0 : options.excludeDirectories) || (options == null ? void 0 : options.excludeFiles)) && (matchesExclude(pathToCheck, options == null ? void 0 : options.excludeFiles, useCaseSensitiveFileNames, getCurrentDirectory()) || matchesExclude(pathToCheck, options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames, getCurrentDirectory())); +function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames2, getCurrentDirectory) { + return ((options == null ? void 0 : options.excludeDirectories) || (options == null ? void 0 : options.excludeFiles)) && (matchesExclude(pathToCheck, options == null ? void 0 : options.excludeFiles, useCaseSensitiveFileNames2, getCurrentDirectory()) || matchesExclude(pathToCheck, options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2, getCurrentDirectory())); } -function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory) { +function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory) { return (eventName, relativeFileName) => { if (eventName === "rename") { const fileName = !relativeFileName ? directoryName : normalizePath(combinePaths(directoryName, relativeFileName)); - if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames, getCurrentDirectory)) { + if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames2, getCurrentDirectory)) { callback(fileName); } } @@ -3938,7 +3939,7 @@ function createSystemWatchFunctions({ clearTimeout: clearTimeout2, fsWatchWorker, fileSystemEntryExists, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories, @@ -4010,7 +4011,7 @@ function createSystemWatchFunctions({ ); case 5 /* UseFsEventsOnParentDirectory */: if (!nonPollingWatchFile) { - nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames); + nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2); } return nonPollingWatchFile(fileName, callback, pollingInterval, getFallbackOptions(options)); default: @@ -4059,7 +4060,7 @@ function createSystemWatchFunctions({ return fsWatch( directoryName, 1 /* Directory */, - createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), + createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */, getFallbackOptions(options) @@ -4067,7 +4068,7 @@ function createSystemWatchFunctions({ } if (!hostRecursiveDirectoryWatcher) { hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fileSystemEntryExists, getAccessibleSortedChildDirectories, @@ -4113,7 +4114,7 @@ function createSystemWatchFunctions({ return fsWatch( directoryName, 1 /* Directory */, - createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), + createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */, getFallbackOptions(watchDirectoryOptions) @@ -4141,7 +4142,7 @@ function createSystemWatchFunctions({ function pollingWatchFile(fileName, callback, pollingInterval, options) { return createSingleWatcherPerName( pollingWatches, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, fileName, callback, (cb) => pollingWatchFileWorker(fileName, cb, pollingInterval, options) @@ -4150,7 +4151,7 @@ function createSystemWatchFunctions({ function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { return createSingleWatcherPerName( recursive ? fsWatchesRecursive : fsWatches, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, fileOrDirectory, callback, (cb) => fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, cb, recursive, fallbackPollingInterval, fallbackOptions) @@ -4278,7 +4279,7 @@ var sys = (() => { const Buffer2 = require("buffer").Buffer; const isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; const platform = _os.platform(); - const useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + const useCaseSensitiveFileNames2 = isFileSystemCaseSensitive(); const fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; const executingFilePath = __filename.endsWith("sys.js") ? _path.join(_path.dirname(__dirname), "__fake__.js") : __filename; const fsSupportsRecursiveFsWatch = process.platform === "win32" || process.platform === "darwin"; @@ -4289,7 +4290,7 @@ var sys = (() => { setTimeout, clearTimeout, fsWatchWorker, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, getCurrentDirectory, fileSystemEntryExists, // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows @@ -4306,7 +4307,7 @@ var sys = (() => { const nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, - useCaseSensitiveFileNames, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, write(s) { process.stdout.write(s); }, @@ -4435,12 +4436,12 @@ var sys = (() => { for (const node of profile.nodes) { if (node.callFrame.url) { const url = normalizeSlashes(node.callFrame.url); - if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) { + if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames2)) { node.callFrame.url = getRelativePathToDirectoryOrUrl( fileUrlRoot, url, fileUrlRoot, - createGetCanonicalFileName(useCaseSensitiveFileNames), + createGetCanonicalFileName(useCaseSensitiveFileNames2), /*isAbsolutePathAnUrl*/ true ); @@ -4620,7 +4621,7 @@ var sys = (() => { } } function readDirectory(path2, extensions, excludes, includes, depth) { - return matchFiles(path2, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); + return matchFiles(path2, extensions, excludes, includes, useCaseSensitiveFileNames2, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path2, entryKind) { const originalStackTraceLimit = Error.stackTraceLimit; @@ -5137,6 +5138,7 @@ var Diagnostics = { Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, 1 /* Error */, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, 1 /* Error */, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, 1 /* Error */, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1065, 1 /* Error */, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065", "The return type of an async function or method must be the global Promise type."), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, 1 /* Error */, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, 1 /* Error */, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, 1 /* Error */, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), @@ -6839,6 +6841,7 @@ var Diagnostics = { Parameter_modifiers_can_only_be_used_in_TypeScript_files: diag(8012, 1 /* Error */, "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012", "Parameter modifiers can only be used in TypeScript files."), Non_null_assertions_can_only_be_used_in_TypeScript_files: diag(8013, 1 /* Error */, "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013", "Non-null assertions can only be used in TypeScript files."), Type_assertion_expressions_can_only_be_used_in_TypeScript_files: diag(8016, 1 /* Error */, "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016", "Type assertion expressions can only be used in TypeScript files."), + Signature_declarations_can_only_be_used_in_TypeScript_files: diag(8017, 1 /* Error */, "Signature_declarations_can_only_be_used_in_TypeScript_files_8017", "Signature declarations can only be used in TypeScript files."), Report_errors_in_js_files: diag(8019, 3 /* Message */, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, 1 /* Error */, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, 1 /* Error */, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), @@ -7889,7 +7892,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (withMinus) start2--; error(Diagnostics.Octal_literals_are_not_allowed_Use_the_syntax_0, start2, pos - start2, literal); - return { type: 9 /* NumericLiteral */, value: tokenValue }; + return 9 /* NumericLiteral */; } } else { mainFragment = scanNumberFragment(); @@ -7929,20 +7932,18 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } if (tokenFlags & 8192 /* ContainsLeadingZero */) { error(Diagnostics.Decimals_with_leading_zeros_are_not_allowed, start2, end2 - start2); - return { type: 9 /* NumericLiteral */, value: "" + +result }; + tokenValue = "" + +result; + return 9 /* NumericLiteral */; } if (decimalFragment !== void 0 || tokenFlags & 16 /* Scientific */) { checkForIdentifierStartAfterNumericLiteral(start2, decimalFragment === void 0 && !!(tokenFlags & 16 /* Scientific */)); - return { - type: 9 /* NumericLiteral */, - value: "" + +result - // if value is not an integer, it can be safely coerced to a number - }; + tokenValue = "" + +result; + return 9 /* NumericLiteral */; } else { tokenValue = result; const type = checkBigIntSuffix(); checkForIdentifierStartAfterNumericLiteral(start2); - return { type, value: tokenValue }; + return type; } } function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { @@ -8551,7 +8552,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return token = 41 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber().value; + scanNumber(); return token = 9 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { @@ -8669,8 +8670,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan case 55 /* _7 */: case 56 /* _8 */: case 57 /* _9 */: - ({ type: token, value: tokenValue } = scanNumber()); - return token; + return token = scanNumber(); case 58 /* colon */: pos++; return token = 59 /* ColonToken */; @@ -11302,7 +11302,10 @@ function getResolveJsonModule(compilerOptions) { } return getEmitModuleResolutionKind(compilerOptions) === 100 /* Bundler */; } -var reservedCharacterPattern = /[^\w\s\/]/g; +function getAllowJSCompilerOption(compilerOptions) { + return compilerOptions.allowJs === void 0 ? !!compilerOptions.checkJs : compilerOptions.allowJs; +} +var reservedCharacterPattern = /[^\w\s/]/g; var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; var commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = `(?!(${commonPackageFolders.join("|")})(/|$))`; @@ -11411,7 +11414,7 @@ function getSubPatternFromSpec(spec, basePath, usage, { singleAsteriskRegexFragm function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } -function getFileMatcherPatterns(path2, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { +function getFileMatcherPatterns(path2, excludes, includes, useCaseSensitiveFileNames2, currentDirectory) { path2 = normalizePath(path2); currentDirectory = normalizePath(currentDirectory); const absolutePath = combinePaths(currentDirectory, path2); @@ -11420,22 +11423,22 @@ function getFileMatcherPatterns(path2, excludes, includes, useCaseSensitiveFileN includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), - basePaths: getBasePaths(path2, includes, useCaseSensitiveFileNames) + basePaths: getBasePaths(path2, includes, useCaseSensitiveFileNames2) }; } -function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { - return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); +function getRegexFromPattern(pattern, useCaseSensitiveFileNames2) { + return new RegExp(pattern, useCaseSensitiveFileNames2 ? "" : "i"); } -function matchFiles(path2, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) { +function matchFiles(path2, extensions, excludes, includes, useCaseSensitiveFileNames2, currentDirectory, depth, getFileSystemEntries, realpath) { path2 = normalizePath(path2); currentDirectory = normalizePath(currentDirectory); - const patterns = getFileMatcherPatterns(path2, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, useCaseSensitiveFileNames)); - const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); - const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + const patterns = getFileMatcherPatterns(path2, excludes, includes, useCaseSensitiveFileNames2, currentDirectory); + const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, useCaseSensitiveFileNames2)); + const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames2); + const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames2); const results = includeFileRegexes ? includeFileRegexes.map(() => []) : [[]]; const visited = /* @__PURE__ */ new Map(); - const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames); + const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames2); for (const basePath of patterns.basePaths) { visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); } @@ -11477,7 +11480,7 @@ function matchFiles(path2, extensions, excludes, includes, useCaseSensitiveFileN } } } -function getBasePaths(path2, includes, useCaseSensitiveFileNames) { +function getBasePaths(path2, includes, useCaseSensitiveFileNames2) { const basePaths = [path2]; if (includes) { const includeBasePaths = []; @@ -11485,9 +11488,9 @@ function getBasePaths(path2, includes, useCaseSensitiveFileNames) { const absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path2, include)); includeBasePaths.push(getIncludeBasePath(absolute)); } - includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames)); + includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames2)); for (const includeBasePath of includeBasePaths) { - if (every(basePaths, (basePath) => !containsPath(basePath, includeBasePath, path2, !useCaseSensitiveFileNames))) { + if (every(basePaths, (basePath) => !containsPath(basePath, includeBasePath, path2, !useCaseSensitiveFileNames2))) { basePaths.push(includeBasePath); } } @@ -18498,7 +18501,8 @@ var Parser; nextToken(); const statements = parseList(0 /* SourceElements */, parseStatement); Debug.assert(token() === 1 /* EndOfFileToken */); - const endOfFileToken = addJSDocComment(parseTokenNode()); + const endHasJSDoc = hasPrecedingJSDocComment(); + const endOfFileToken = withJSDoc(parseTokenNode(), endHasJSDoc); const sourceFile = createSourceFile2(fileName, languageVersion2, scriptKind2, isDeclarationFile, statements, endOfFileToken, sourceFlags, setExternalModuleIndicator2); processCommentPragmas(sourceFile, sourceText); processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); @@ -18518,11 +18522,11 @@ var Parser; parseDiagnostics.push(createDetachedDiagnostic(fileName, pos, end, diagnostic)); } } - function withJSDoc(node, hasJSDoc) { - return hasJSDoc ? addJSDocComment(node) : node; - } let hasDeprecatedTag = false; - function addJSDocComment(node) { + function withJSDoc(node, hasJSDoc) { + if (!hasJSDoc) { + return node; + } Debug.assert(!node.jsDoc); const jsDoc = mapDefined(getJSDocCommentRanges(node, sourceText), (comment) => JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); if (jsDoc.length) @@ -19316,6 +19320,9 @@ var Parser; case 22 /* HeritageClauses */: return isHeritageClause2(); case 23 /* ImportOrExportSpecifiers */: + if (token() === 161 /* FromKeyword */ && lookAhead(nextTokenIsStringLiteral)) { + return false; + } return tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */; @@ -19674,6 +19681,9 @@ var Parser; case 22 /* HeritageClauses */: return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_expected); case 23 /* ImportOrExportSpecifiers */: + if (token() === 161 /* FromKeyword */) { + return parseErrorAtCurrentToken(Diagnostics._0_expected, "}"); + } return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 13 /* JsxAttributes */: return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); @@ -21031,12 +21041,14 @@ var Parser; return arrowExpression; } const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); if (expr.kind === 80 /* Identifier */ && token() === 39 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression( pos, expr, allowReturnTypeInArrowFunction, + hasJSDoc, /*asyncModifier*/ void 0 ); @@ -21082,7 +21094,7 @@ var Parser; ), pos); } } - function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, asyncModifier) { + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier) { Debug.assert(token() === 39 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); const parameter = factory2.createParameterDeclaration( /*modifiers*/ @@ -21115,7 +21127,7 @@ var Parser; equalsGreaterThanToken, body ); - return addJSDocComment(finishNode(node, pos)); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { const triState = isParenthesizedArrowFunctionExpression(); @@ -21243,9 +21255,10 @@ var Parser; if (token() === 134 /* AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const asyncModifier = parseModifiersForArrowFunction(); const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); - return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier); } } return void 0; @@ -22606,10 +22619,14 @@ var Parser; case 124 /* ProtectedKeyword */: case 125 /* PublicKeyword */: case 148 /* ReadonlyKeyword */: + const previousToken = token(); nextToken(); if (scanner.hasPrecedingLineBreak()) { return false; } + if (previousToken === 138 /* DeclareKeyword */ && token() === 156 /* TypeKeyword */) { + return true; + } continue; case 162 /* GlobalKeyword */: nextToken(); @@ -22919,6 +22936,9 @@ var Parser; return void 0; } } + function nextTokenIsStringLiteral() { + return nextToken() === 11 /* StringLiteral */; + } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); return !scanner.hasPrecedingLineBreak() && (isIdentifier2() || token() === 11 /* StringLiteral */); @@ -22971,14 +22991,14 @@ var Parser; function parseObjectBindingPattern() { const pos = getNodePos(); parseExpected(19 /* OpenBraceToken */); - const elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + const elements = allowInAnd(() => parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement)); parseExpected(20 /* CloseBraceToken */); return finishNode(factory2.createObjectBindingPattern(elements), pos); } function parseArrayBindingPattern() { const pos = getNodePos(); parseExpected(23 /* OpenBracketToken */); - const elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + const elements = allowInAnd(() => parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement)); parseExpected(24 /* CloseBracketToken */); return finishNode(factory2.createArrayBindingPattern(elements), pos); } @@ -23496,6 +23516,9 @@ var Parser; } function parseTypeAliasDeclaration(pos, hasJSDoc, modifiers) { parseExpected(156 /* TypeKeyword */); + if (scanner.hasPrecedingLineBreak()) { + parseErrorAtCurrentToken(Diagnostics.Line_break_not_permitted_here); + } const name = parseIdentifier(); const typeParameters = parseTypeParameters(); parseExpected(64 /* EqualsToken */); @@ -24478,7 +24501,7 @@ var Parser; typeExpression = tryParseTypeExpression(); } const comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText); - const nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent2); + const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target, indent2); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -24764,7 +24787,7 @@ var Parser; case 60 /* AtToken */: if (canParseTag) { const child = tryParseChildTag(target, indent2); - if (child && (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + if (child && (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */) && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } return child; @@ -25397,7 +25420,7 @@ function getNamedArgRegEx(name) { return result; } var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; -var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; +var singleLinePragmaRegEx = /^\/\/\/?\s*@([^\s:]+)(.*)\s*$/im; function extractPragmas(pragmas, range, text) { const tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text); if (tripleSlash) { @@ -25992,6 +26015,7 @@ var commandOptionsWithoutBuild = [ { name: "checkJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: Diagnostics.JavaScript_Support, description: Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files, @@ -26218,7 +26242,7 @@ var commandOptionsWithoutBuild = [ strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, - defaultValueDescription: false + defaultValueDescription: Diagnostics.false_unless_strict_is_set }, { name: "alwaysStrict", @@ -27211,17 +27235,17 @@ function invalidDotDotAfterRecursiveWildcard(s) { const lastDotIndex = endsWith(s, "/..") ? s.length : s.lastIndexOf("/../"); return lastDotIndex > wildcardIndex; } -function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory) { +function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory) { return matchesExcludeWorker( pathToCheck, filter(excludeSpecs, (spec) => !invalidDotDotAfterRecursiveWildcard(spec)), - useCaseSensitiveFileNames, + useCaseSensitiveFileNames2, currentDirectory ); } -function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath) { +function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath) { const excludePattern = getRegularExpressionForWildcard(excludeSpecs, combinePaths(normalizePath(currentDirectory), basePath), "exclude"); - const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames); + const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames2); if (!excludeRegex) return false; if (excludeRegex.test(pathToCheck)) @@ -27428,8 +27452,8 @@ function getPackageJsonTypesVersionsPaths(typesVersions) { } var nodeModulesAtTypes = combinePaths("node_modules", "@types"); function arePathsEqual(path1, path2, host) { - const useCaseSensitiveFileNames = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; - return comparePaths(path1, path2, !useCaseSensitiveFileNames) === 0 /* EqualTo */; + const useCaseSensitiveFileNames2 = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; + return comparePaths(path1, path2, !useCaseSensitiveFileNames2) === 0 /* EqualTo */; } function getOriginalAndResolvedFileName(fileName, host, traceEnabled) { const resolvedFileName = realPath(fileName, host, traceEnabled); @@ -28237,6 +28261,9 @@ function loadModuleFromSelfNameReference(extensions, moduleName, directory, stat } const trailingParts = parts.slice(nameParts.length); const subpath = !length(trailingParts) ? "." : `.${directorySeparator}${trailingParts.join(directorySeparator)}`; + if (getAllowJSCompilerOption(state.compilerOptions) && !pathContainsNodeModules(directory)) { + return loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference); + } const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */); const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */); return loadModuleFromExports(scope, priorityExtensions, subpath, state, cache, redirectedReference) || loadModuleFromExports(scope, secondaryExtensions, subpath, state, cache, redirectedReference); @@ -28584,13 +28611,10 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec function combineDirectoryPath(root, dir) { return ensureTrailingDirectorySeparator(combinePaths(root, dir)); } - function useCaseSensitiveFileNames() { - return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); - } function tryLoadInputFileForPath(finalPath, entry, packagePath, isImports2) { var _a, _b, _c, _d; - if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames()) : true)) { - const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames }); + if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true)) { + const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames: () => useCaseSensitiveFileNames(state) }); const commonSourceDirGuesses = []; if (state.compilerOptions.rootDir || state.compilerOptions.composite && state.compilerOptions.configFilePath) { const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, () => [], ((_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)) || "", getCanonicalFileName)); @@ -28619,7 +28643,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec for (const commonSourceDirGuess of commonSourceDirGuesses) { const candidateDirectories = getOutputDirectoriesForBaseDirectory(commonSourceDirGuess); for (const candidateDir of candidateDirectories) { - if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames())) { + if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames(state))) { const pathFragment = finalPath.slice(candidateDir.length + 1); const possibleInputBase = combinePaths(commonSourceDirGuess, pathFragment); const jsAndDtsExtensions = [".mjs" /* Mjs */, ".cjs" /* Cjs */, ".js" /* Js */, ".json" /* Json */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */, ".d.ts" /* Dts */]; @@ -28629,7 +28653,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec for (const possibleExt of inputExts) { if (!extensionIsOk(extensions, possibleExt)) continue; - const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames()); + const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames(state)); if (state.host.fileExists(possibleInputWithInputExtension)) { return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( extensions, @@ -28986,6 +29010,9 @@ function traceIfEnabled(state, diagnostic, ...args) { trace(state.host, diagnostic, ...args); } } +function useCaseSensitiveFileNames(state) { + return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); +} // src/compiler/checker.ts var nextNodeId = 1;