From 68d356eed91731cd0c13eb946f296aa90ef4d5ac Mon Sep 17 00:00:00 2001 From: David Sherret Date: Wed, 6 Dec 2023 18:49:34 -0500 Subject: [PATCH] feat: TypeScript 5.3 (#21480) https://github.com/denoland/TypeScript/pull/9 --- cli/build.rs | 2 +- cli/tests/integration/lsp_tests.rs | 4 +- cli/tests/unit/version_test.ts | 2 +- cli/tsc/00_typescript.js | 25552 +++++++++++++---- cli/tsc/99_main_compiler.js | 11 +- cli/tsc/dts/lib.decorators.d.ts | 9 +- cli/tsc/dts/lib.dom.d.ts | 8 +- cli/tsc/dts/lib.es2015.collection.d.ts | 3 +- cli/tsc/dts/lib.es2015.core.d.ts | 2 +- cli/tsc/dts/lib.es2015.iterable.d.ts | 9 +- cli/tsc/dts/lib.es2015.promise.d.ts | 2 +- cli/tsc/dts/lib.es2015.symbol.d.ts | 2 +- cli/tsc/dts/lib.es2016.array.include.d.ts | 2 +- cli/tsc/dts/lib.es2016.d.ts | 2 +- cli/tsc/dts/lib.es2016.full.d.ts | 2 +- cli/tsc/dts/lib.es2017.full.d.ts | 2 +- cli/tsc/dts/lib.es2017.intl.d.ts | 23 +- cli/tsc/dts/lib.es2017.object.d.ts | 6 +- cli/tsc/dts/lib.es2018.asynciterable.d.ts | 2 +- cli/tsc/dts/lib.es2018.full.d.ts | 2 +- cli/tsc/dts/lib.es2018.intl.d.ts | 3 +- cli/tsc/dts/lib.es2018.promise.d.ts | 2 +- cli/tsc/dts/lib.es2018.regexp.d.ts | 10 +- cli/tsc/dts/lib.es2019.array.d.ts | 32 +- cli/tsc/dts/lib.es2019.intl.d.ts | 2 +- cli/tsc/dts/lib.es2019.object.d.ts | 2 +- cli/tsc/dts/lib.es2020.bigint.d.ts | 14 +- cli/tsc/dts/lib.es2020.date.d.ts | 2 +- cli/tsc/dts/lib.es2020.intl.d.ts | 24 +- cli/tsc/dts/lib.es2020.promise.d.ts | 2 +- cli/tsc/dts/lib.es2021.intl.d.ts | 11 +- cli/tsc/dts/lib.es2021.promise.d.ts | 6 +- cli/tsc/dts/lib.es2021.weakref.d.ts | 4 +- cli/tsc/dts/lib.es2022.error.d.ts | 4 +- cli/tsc/dts/lib.es2022.intl.d.ts | 3 +- cli/tsc/dts/lib.es2022.sharedmemory.d.ts | 4 +- cli/tsc/dts/lib.es2023.array.d.ts | 144 +- cli/tsc/dts/lib.es5.d.ts | 173 +- cli/tsc/dts/lib.esnext.array.d.ts | 277 - cli/tsc/dts/lib.esnext.disposable.d.ts | 20 +- cli/tsc/dts/lib.esnext.full.d.ts | 2 +- cli/tsc/dts/lib.esnext.intl.d.ts | 14 +- cli/tsc/dts/lib.scripthost.d.ts | 5 +- cli/tsc/dts/lib.webworker.d.ts | 8 +- cli/tsc/dts/lib.webworker.importscripts.d.ts | 1 - cli/tsc/dts/typescript.d.ts | 4837 +++- 46 files changed, 24822 insertions(+), 6431 deletions(-) diff --git a/cli/build.rs b/cli/build.rs index 4400e3e8b3..d7f373b99d 100644 --- a/cli/build.rs +++ b/cli/build.rs @@ -428,7 +428,7 @@ fn main() { ); let ts_version = ts::version(); - debug_assert_eq!(ts_version, "5.2.2"); // bump this assertion when it changes + debug_assert_eq!(ts_version, "5.3.3"); // bump this assertion when it changes println!("cargo:rustc-env=TS_VERSION={}", ts_version); println!("cargo:rerun-if-env-changed=TS_VERSION"); diff --git a/cli/tests/integration/lsp_tests.rs b/cli/tests/integration/lsp_tests.rs index da3d6d6e5b..6dfb0a29a4 100644 --- a/cli/tests/integration/lsp_tests.rs +++ b/cli/tests/integration/lsp_tests.rs @@ -9109,11 +9109,11 @@ fn lsp_workspace_symbol() { "uri": "deno:/asset/lib.decorators.d.ts", "range": { "start": { - "line": 346, + "line": 343, "character": 0, }, "end": { - "line": 388, + "line": 385, "character": 1, }, }, diff --git a/cli/tests/unit/version_test.ts b/cli/tests/unit/version_test.ts index 86e7d0f865..b58f02c826 100644 --- a/cli/tests/unit/version_test.ts +++ b/cli/tests/unit/version_test.ts @@ -6,5 +6,5 @@ Deno.test(function version() { const pattern = /^\d+\.\d+\.\d+/; assert(pattern.test(Deno.version.deno)); assert(pattern.test(Deno.version.v8)); - assertEquals(Deno.version.typescript, "5.2.2"); + assertEquals(Deno.version.typescript, "5.3.3"); }); diff --git a/cli/tsc/00_typescript.js b/cli/tsc/00_typescript.js index a593dca426..64b453b34b 100644 --- a/cli/tsc/00_typescript.js +++ b/cli/tsc/00_typescript.js @@ -34,8 +34,8 @@ var ts = (() => { var init_corePublic = __esm({ "src/compiler/corePublic.ts"() { "use strict"; - versionMajorMinor = "5.2"; - version = "5.2.2"; + versionMajorMinor = "5.3"; + version = "5.3.3"; Comparison = /* @__PURE__ */ ((Comparison3) => { Comparison3[Comparison3["LessThan"] = -1] = "LessThan"; Comparison3[Comparison3["EqualTo"] = 0] = "EqualTo"; @@ -1398,9 +1398,6 @@ var ts = (() => { function tryRemoveSuffix(str, suffix) { return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : void 0; } - function stringContains(str, substring) { - return str.indexOf(substring) !== -1; - } function removeMinAndVersionNumbers(fileName) { let end = fileName.length; for (let pos = end - 1; pos > 0; pos--) { @@ -1583,12 +1580,6 @@ var ts = (() => { } } } - function padLeft(s, length2, padString = " ") { - return length2 <= s.length ? s : padString.repeat(length2 - s.length) + s; - } - function padRight(s, length2, padString = " ") { - return length2 <= s.length ? s : s + padString.repeat(length2 - s.length); - } function takeWhile(array, predicate) { if (array) { const len = array.length; @@ -1609,19 +1600,10 @@ var ts = (() => { return array.slice(index); } } - function trimEndImpl(s) { - let end = s.length - 1; - while (end >= 0) { - if (!isWhiteSpaceLike(s.charCodeAt(end))) - break; - end--; - } - return s.slice(0, end + 1); - } function isNodeLikeSystem() { return typeof process !== "undefined" && !!process.nextTick && !process.browser && typeof module === "object"; } - var emptyArray, emptyMap, emptySet, SortKind, elementAt, hasOwnProperty, fileNameLowerCaseRegExp, AssertionLevel, createUIStringComparer, uiComparerCaseSensitive, uiLocale, trimString, trimStringEnd, trimStringStart; + var emptyArray, emptyMap, emptySet, SortKind, elementAt, hasOwnProperty, fileNameLowerCaseRegExp, AssertionLevel, createUIStringComparer, uiComparerCaseSensitive, uiLocale; var init_core = __esm({ "src/compiler/core.ts"() { "use strict"; @@ -1655,10 +1637,7 @@ var ts = (() => { return AssertionLevel2; })(AssertionLevel || {}); createUIStringComparer = (() => { - let defaultComparer; - let enUSComparer; - const stringComparerFactory = getStringComparerFactory(); - return createStringComparer; + return createIntlCollatorStringComparer; function compareWithCallback(a, b, comparer) { if (a === b) return 0 /* EqualTo */; @@ -1673,45 +1652,7 @@ var ts = (() => { const comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; return (a, b) => compareWithCallback(a, b, comparer); } - function createLocaleCompareStringComparer(locale) { - if (locale !== void 0) - return createFallbackStringComparer(); - return (a, b) => compareWithCallback(a, b, compareStrings); - function compareStrings(a, b) { - return a.localeCompare(b); - } - } - function createFallbackStringComparer() { - return (a, b) => compareWithCallback(a, b, compareDictionaryOrder); - function compareDictionaryOrder(a, b) { - return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); - } - function compareStrings(a, b) { - return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; - } - } - function getStringComparerFactory() { - if (typeof Intl === "object" && typeof Intl.Collator === "function") { - return createIntlCollatorStringComparer; - } - if (typeof String.prototype.localeCompare === "function" && typeof String.prototype.toLocaleUpperCase === "function" && "a".localeCompare("B") < 0) { - return createLocaleCompareStringComparer; - } - return createFallbackStringComparer; - } - function createStringComparer(locale) { - if (locale === void 0) { - return defaultComparer || (defaultComparer = stringComparerFactory(locale)); - } else if (locale === "en-US") { - return enUSComparer || (enUSComparer = stringComparerFactory(locale)); - } else { - return stringComparerFactory(locale); - } - } })(); - trimString = !!String.prototype.trim ? (s) => s.trim() : (s) => trimStringEnd(trimStringStart(s)); - trimStringEnd = !!String.prototype.trimEnd ? (s) => s.trimEnd() : trimEndImpl; - trimStringStart = !!String.prototype.trimStart ? (s) => s.trimStart() : (s) => s.replace(/^\s+/g, ""); } }); @@ -1722,13 +1663,13 @@ var ts = (() => { "use strict"; init_ts2(); init_ts2(); - LogLevel = /* @__PURE__ */ ((LogLevel2) => { - LogLevel2[LogLevel2["Off"] = 0] = "Off"; - LogLevel2[LogLevel2["Error"] = 1] = "Error"; - LogLevel2[LogLevel2["Warning"] = 2] = "Warning"; - LogLevel2[LogLevel2["Info"] = 3] = "Info"; - LogLevel2[LogLevel2["Verbose"] = 4] = "Verbose"; - return LogLevel2; + LogLevel = /* @__PURE__ */ ((LogLevel3) => { + LogLevel3[LogLevel3["Off"] = 0] = "Off"; + LogLevel3[LogLevel3["Error"] = 1] = "Error"; + LogLevel3[LogLevel3["Warning"] = 2] = "Warning"; + LogLevel3[LogLevel3["Info"] = 3] = "Info"; + LogLevel3[LogLevel3["Verbose"] = 4] = "Verbose"; + return LogLevel3; })(LogLevel || {}); ((Debug2) => { let currentAssertionLevel = 0 /* None */; @@ -2164,17 +2105,21 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, return `${flowHeader}${remainingFlags ? ` (${formatFlowFlags(remainingFlags)})` : ""}`; } }, - __debugFlowFlags: { get() { - return formatEnum( - this.flags, - FlowFlags, - /*isFlags*/ - true - ); - } }, - __debugToString: { value() { - return formatControlFlowGraph(this); - } } + __debugFlowFlags: { + get() { + return formatEnum( + this.flags, + FlowFlags, + /*isFlags*/ + true + ); + } + }, + __debugToString: { + value() { + return formatControlFlowGraph(this); + } + } }); } } @@ -2233,25 +2178,31 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, return `${symbolHeader} '${symbolName(this)}'${remainingSymbolFlags ? ` (${formatSymbolFlags(remainingSymbolFlags)})` : ""}`; } }, - __debugFlags: { get() { - return formatSymbolFlags(this.flags); - } } + __debugFlags: { + get() { + return formatSymbolFlags(this.flags); + } + } }); Object.defineProperties(objectAllocator.getTypeConstructor().prototype, { // for use with vscode-js-debug's new customDescriptionGenerator in launch.json __tsDebuggerDisplay: { value() { - const typeHeader = this.flags & 98304 /* Nullable */ ? "NullableType" : this.flags & 384 /* StringOrNumberLiteral */ ? `LiteralType ${JSON.stringify(this.value)}` : this.flags & 2048 /* BigIntLiteral */ ? `LiteralType ${this.value.negative ? "-" : ""}${this.value.base10Value}n` : this.flags & 8192 /* UniqueESSymbol */ ? "UniqueESSymbolType" : this.flags & 32 /* Enum */ ? "EnumType" : this.flags & 67359327 /* Intrinsic */ ? `IntrinsicType ${this.intrinsicName}` : this.flags & 1048576 /* Union */ ? "UnionType" : this.flags & 2097152 /* Intersection */ ? "IntersectionType" : this.flags & 4194304 /* Index */ ? "IndexType" : this.flags & 8388608 /* IndexedAccess */ ? "IndexedAccessType" : this.flags & 16777216 /* Conditional */ ? "ConditionalType" : this.flags & 33554432 /* Substitution */ ? "SubstitutionType" : this.flags & 262144 /* TypeParameter */ ? "TypeParameter" : this.flags & 524288 /* Object */ ? this.objectFlags & 3 /* ClassOrInterface */ ? "InterfaceType" : this.objectFlags & 4 /* Reference */ ? "TypeReference" : this.objectFlags & 8 /* Tuple */ ? "TupleType" : this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" : this.objectFlags & 32 /* Mapped */ ? "MappedType" : this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" : this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" : "ObjectType" : "Type"; + const typeHeader = this.flags & 67359327 /* Intrinsic */ ? `IntrinsicType ${this.intrinsicName}${this.debugIntrinsicName ? ` (${this.debugIntrinsicName})` : ""}` : this.flags & 98304 /* Nullable */ ? "NullableType" : this.flags & 384 /* StringOrNumberLiteral */ ? `LiteralType ${JSON.stringify(this.value)}` : this.flags & 2048 /* BigIntLiteral */ ? `LiteralType ${this.value.negative ? "-" : ""}${this.value.base10Value}n` : this.flags & 8192 /* UniqueESSymbol */ ? "UniqueESSymbolType" : this.flags & 32 /* Enum */ ? "EnumType" : this.flags & 1048576 /* Union */ ? "UnionType" : this.flags & 2097152 /* Intersection */ ? "IntersectionType" : this.flags & 4194304 /* Index */ ? "IndexType" : this.flags & 8388608 /* IndexedAccess */ ? "IndexedAccessType" : this.flags & 16777216 /* Conditional */ ? "ConditionalType" : this.flags & 33554432 /* Substitution */ ? "SubstitutionType" : this.flags & 262144 /* TypeParameter */ ? "TypeParameter" : this.flags & 524288 /* Object */ ? this.objectFlags & 3 /* ClassOrInterface */ ? "InterfaceType" : this.objectFlags & 4 /* Reference */ ? "TypeReference" : this.objectFlags & 8 /* Tuple */ ? "TupleType" : this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" : this.objectFlags & 32 /* Mapped */ ? "MappedType" : this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" : this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" : "ObjectType" : "Type"; const remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0; return `${typeHeader}${this.symbol ? ` '${symbolName(this.symbol)}'` : ""}${remainingObjectFlags ? ` (${formatObjectFlags(remainingObjectFlags)})` : ""}`; } }, - __debugFlags: { get() { - return formatTypeFlags(this.flags); - } }, - __debugObjectFlags: { get() { - return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; - } }, + __debugFlags: { + get() { + return formatTypeFlags(this.flags); + } + }, + __debugObjectFlags: { + get() { + return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; + } + }, __debugTypeToString: { value() { let text = weakTypeTextMap.get(this); @@ -2264,13 +2215,17 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, } }); Object.defineProperties(objectAllocator.getSignatureConstructor().prototype, { - __debugFlags: { get() { - return formatSignatureFlags(this.flags); - } }, - __debugSignatureToString: { value() { - var _a; - return (_a = this.checker) == null ? void 0 : _a.signatureToString(this); - } } + __debugFlags: { + get() { + return formatSignatureFlags(this.flags); + } + }, + __debugSignatureToString: { + value() { + var _a; + return (_a = this.checker) == null ? void 0 : _a.signatureToString(this); + } + } }); const nodeConstructors = [ objectAllocator.getNodeConstructor(), @@ -2288,24 +2243,36 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, return `${nodeHeader}${this.flags ? ` (${formatNodeFlags(this.flags)})` : ""}`; } }, - __debugKind: { get() { - return formatSyntaxKind(this.kind); - } }, - __debugNodeFlags: { get() { - return formatNodeFlags(this.flags); - } }, - __debugModifierFlags: { get() { - return formatModifierFlags(getEffectiveModifierFlagsNoCache(this)); - } }, - __debugTransformFlags: { get() { - return formatTransformFlags(this.transformFlags); - } }, - __debugIsParseTreeNode: { get() { - return isParseTreeNode(this); - } }, - __debugEmitFlags: { get() { - return formatEmitFlags(getEmitFlags(this)); - } }, + __debugKind: { + get() { + return formatSyntaxKind(this.kind); + } + }, + __debugNodeFlags: { + get() { + return formatNodeFlags(this.flags); + } + }, + __debugModifierFlags: { + get() { + return formatModifierFlags(getEffectiveModifierFlagsNoCache(this)); + } + }, + __debugTransformFlags: { + get() { + return formatTransformFlags(this.transformFlags); + } + }, + __debugIsParseTreeNode: { + get() { + return isParseTreeNode(this); + } + }, + __debugEmitFlags: { + get() { + return formatEmitFlags(getEmitFlags(this)); + } + }, __debugGetText: { value(includeTrivia) { if (nodeIsSynthesized(this)) @@ -2784,18 +2751,18 @@ ${lanes.join("\n")} } function parseRange(text) { const alternatives = []; - for (let range of trimString(text).split(logicalOrRegExp)) { + for (let range of text.trim().split(logicalOrRegExp)) { if (!range) continue; const comparators = []; - range = trimString(range); + range = range.trim(); const match = hyphenRegExp.exec(range); if (match) { if (!parseHyphen(match[1], match[2], comparators)) return void 0; } else { for (const simple of range.split(whitespaceRegExp)) { - const match2 = rangeRegExp.exec(trimString(simple)); + const match2 = rangeRegExp.exec(simple.trim()); if (!match2 || !parseComparator(match2[1], match2[2], comparators)) return void 0; } @@ -2844,15 +2811,21 @@ ${lanes.join("\n")} switch (operator) { case "~": comparators.push(createComparator(">=", version2)); - comparators.push(createComparator("<", version2.increment( - isWildcard(minor) ? "major" : "minor" - ))); + comparators.push(createComparator( + "<", + version2.increment( + isWildcard(minor) ? "major" : "minor" + ) + )); break; case "^": comparators.push(createComparator(">=", version2)); - comparators.push(createComparator("<", version2.increment( - version2.major > 0 || isWildcard(minor) ? "major" : version2.minor > 0 || isWildcard(patch) ? "minor" : "patch" - ))); + comparators.push(createComparator( + "<", + version2.increment( + version2.major > 0 || isWildcard(minor) ? "major" : version2.minor > 0 || isWildcard(patch) ? "minor" : "patch" + ) + )); break; case "<": case ">=": @@ -3287,11 +3260,7 @@ ${lanes.join("\n")} const meta = { cat: "__metadata", ph: "M", ts: 1e3 * timestamp(), pid: 1, tid: 1 }; fs.writeSync( traceFd, - "[\n" + [ - { name: "process_name", args: { name: "tsc" }, ...meta }, - { name: "thread_name", args: { name: "Main" }, ...meta }, - { name: "TracingStartedInBrowser", ...meta, cat: "disabled-by-default-devtools.timeline" } - ].map((v) => JSON.stringify(v)).join(",\n") + "[\n" + [{ name: "process_name", args: { name: "tsc" }, ...meta }, { name: "thread_name", args: { name: "Main" }, ...meta }, { name: "TracingStartedInBrowser", ...meta, cat: "disabled-by-default-devtools.timeline" }].map((v) => JSON.stringify(v)).join(",\n") ); } tracingEnabled2.startTracing = startTracing2; @@ -3528,7 +3497,7 @@ ${lanes.join("\n")} const name = DiagnosticCategory[d.category]; return lowerCase ? name.toLowerCase() : name; } - var SyntaxKind, NodeFlags, ModifierFlags, JsxFlags, RelationComparisonResult, GeneratedIdentifierFlags, TokenFlags, FlowFlags, CommentDirectiveType, OperationCanceledException, FileIncludeKind, FilePreprocessingDiagnosticsKind, EmitOnly, StructureIsReused, ExitStatus, MemberOverrideStatus, UnionReduction, ContextFlags, NodeBuilderFlags, TypeFormatFlags, SymbolFormatFlags, SymbolAccessibility, SyntheticSymbolKind, TypePredicateKind, TypeReferenceSerializationKind, SymbolFlags, EnumKind, CheckFlags, InternalSymbolName, NodeCheckFlags, TypeFlags, ObjectFlags, VarianceFlags, ElementFlags, AccessFlags, IndexFlags, JsxReferenceKind, SignatureKind, SignatureFlags, IndexKind, TypeMapKind, InferencePriority, InferenceFlags, Ternary, AssignmentDeclarationKind, DiagnosticCategory, ModuleResolutionKind, ModuleDetectionKind, WatchFileKind, WatchDirectoryKind, PollingWatchKind, ModuleKind, JsxEmit, ImportsNotUsedAsValues, NewLineKind, ScriptKind, ScriptTarget, LanguageVariant, WatchDirectoryFlags, CharacterCodes, Extension, TransformFlags, SnippetKind, EmitFlags, InternalEmitFlags, ExternalEmitHelpers, EmitHint, OuterExpressionKinds, LexicalEnvironmentFlags, BundleFileSectionKind, ListFormat, PragmaKindFlags, commentPragmas; + var SyntaxKind, NodeFlags, ModifierFlags, JsxFlags, RelationComparisonResult, GeneratedIdentifierFlags, TokenFlags, FlowFlags, CommentDirectiveType, OperationCanceledException, FileIncludeKind, FilePreprocessingDiagnosticsKind, EmitOnly, StructureIsReused, ExitStatus, MemberOverrideStatus, UnionReduction, ContextFlags, NodeBuilderFlags, TypeFormatFlags, SymbolFormatFlags, SymbolAccessibility, SyntheticSymbolKind, TypePredicateKind, TypeReferenceSerializationKind, SymbolFlags, EnumKind, CheckFlags, InternalSymbolName, NodeCheckFlags, TypeFlags, ObjectFlags, VarianceFlags, ElementFlags, AccessFlags, IndexFlags, JsxReferenceKind, SignatureKind, SignatureFlags, IndexKind, TypeMapKind, InferencePriority, InferenceFlags, Ternary, AssignmentDeclarationKind, DiagnosticCategory, ModuleResolutionKind, ModuleDetectionKind, WatchFileKind, WatchDirectoryKind, PollingWatchKind, ModuleKind, JsxEmit, ImportsNotUsedAsValues, NewLineKind, ScriptKind, ScriptTarget, LanguageVariant, WatchDirectoryFlags, CharacterCodes, Extension, TransformFlags, SnippetKind, EmitFlags, InternalEmitFlags, ExternalEmitHelpers, EmitHint, OuterExpressionKinds, LexicalEnvironmentFlags, BundleFileSectionKind, ListFormat, PragmaKindFlags, commentPragmas, JSDocParsingMode; var init_types = __esm({ "src/compiler/types.ts"() { "use strict"; @@ -3833,8 +3802,10 @@ ${lanes.join("\n")} SyntaxKind5[SyntaxKind5["DefaultClause"] = 297] = "DefaultClause"; SyntaxKind5[SyntaxKind5["HeritageClause"] = 298] = "HeritageClause"; SyntaxKind5[SyntaxKind5["CatchClause"] = 299] = "CatchClause"; - SyntaxKind5[SyntaxKind5["AssertClause"] = 300] = "AssertClause"; - SyntaxKind5[SyntaxKind5["AssertEntry"] = 301] = "AssertEntry"; + SyntaxKind5[SyntaxKind5["ImportAttributes"] = 300] = "ImportAttributes"; + SyntaxKind5[SyntaxKind5["ImportAttribute"] = 301] = "ImportAttribute"; + SyntaxKind5[SyntaxKind5["AssertClause"] = 300 /* ImportAttributes */] = "AssertClause"; + SyntaxKind5[SyntaxKind5["AssertEntry"] = 301 /* ImportAttribute */] = "AssertEntry"; SyntaxKind5[SyntaxKind5["ImportTypeAssertionContainer"] = 302] = "ImportTypeAssertionContainer"; SyntaxKind5[SyntaxKind5["PropertyAssignment"] = 303] = "PropertyAssignment"; SyntaxKind5[SyntaxKind5["ShorthandPropertyAssignment"] = 304] = "ShorthandPropertyAssignment"; @@ -3979,32 +3950,43 @@ ${lanes.join("\n")} })(NodeFlags || {}); ModifierFlags = /* @__PURE__ */ ((ModifierFlags3) => { ModifierFlags3[ModifierFlags3["None"] = 0] = "None"; - ModifierFlags3[ModifierFlags3["Export"] = 1] = "Export"; - ModifierFlags3[ModifierFlags3["Ambient"] = 2] = "Ambient"; - ModifierFlags3[ModifierFlags3["Public"] = 4] = "Public"; - ModifierFlags3[ModifierFlags3["Private"] = 8] = "Private"; - ModifierFlags3[ModifierFlags3["Protected"] = 16] = "Protected"; - ModifierFlags3[ModifierFlags3["Static"] = 32] = "Static"; - ModifierFlags3[ModifierFlags3["Readonly"] = 64] = "Readonly"; - ModifierFlags3[ModifierFlags3["Accessor"] = 128] = "Accessor"; - ModifierFlags3[ModifierFlags3["Abstract"] = 256] = "Abstract"; - ModifierFlags3[ModifierFlags3["Async"] = 512] = "Async"; - ModifierFlags3[ModifierFlags3["Default"] = 1024] = "Default"; - ModifierFlags3[ModifierFlags3["Const"] = 2048] = "Const"; - ModifierFlags3[ModifierFlags3["HasComputedJSDocModifiers"] = 4096] = "HasComputedJSDocModifiers"; - ModifierFlags3[ModifierFlags3["Deprecated"] = 8192] = "Deprecated"; - ModifierFlags3[ModifierFlags3["Override"] = 16384] = "Override"; - ModifierFlags3[ModifierFlags3["In"] = 32768] = "In"; - ModifierFlags3[ModifierFlags3["Out"] = 65536] = "Out"; - ModifierFlags3[ModifierFlags3["Decorator"] = 131072] = "Decorator"; + ModifierFlags3[ModifierFlags3["Public"] = 1] = "Public"; + ModifierFlags3[ModifierFlags3["Private"] = 2] = "Private"; + ModifierFlags3[ModifierFlags3["Protected"] = 4] = "Protected"; + ModifierFlags3[ModifierFlags3["Readonly"] = 8] = "Readonly"; + ModifierFlags3[ModifierFlags3["Override"] = 16] = "Override"; + ModifierFlags3[ModifierFlags3["Export"] = 32] = "Export"; + ModifierFlags3[ModifierFlags3["Abstract"] = 64] = "Abstract"; + ModifierFlags3[ModifierFlags3["Ambient"] = 128] = "Ambient"; + ModifierFlags3[ModifierFlags3["Static"] = 256] = "Static"; + ModifierFlags3[ModifierFlags3["Accessor"] = 512] = "Accessor"; + ModifierFlags3[ModifierFlags3["Async"] = 1024] = "Async"; + ModifierFlags3[ModifierFlags3["Default"] = 2048] = "Default"; + ModifierFlags3[ModifierFlags3["Const"] = 4096] = "Const"; + ModifierFlags3[ModifierFlags3["In"] = 8192] = "In"; + ModifierFlags3[ModifierFlags3["Out"] = 16384] = "Out"; + ModifierFlags3[ModifierFlags3["Decorator"] = 32768] = "Decorator"; + ModifierFlags3[ModifierFlags3["Deprecated"] = 65536] = "Deprecated"; + ModifierFlags3[ModifierFlags3["JSDocPublic"] = 8388608] = "JSDocPublic"; + ModifierFlags3[ModifierFlags3["JSDocPrivate"] = 16777216] = "JSDocPrivate"; + ModifierFlags3[ModifierFlags3["JSDocProtected"] = 33554432] = "JSDocProtected"; + ModifierFlags3[ModifierFlags3["JSDocReadonly"] = 67108864] = "JSDocReadonly"; + ModifierFlags3[ModifierFlags3["JSDocOverride"] = 134217728] = "JSDocOverride"; + ModifierFlags3[ModifierFlags3["SyntacticOrJSDocModifiers"] = 31] = "SyntacticOrJSDocModifiers"; + ModifierFlags3[ModifierFlags3["SyntacticOnlyModifiers"] = 65504] = "SyntacticOnlyModifiers"; + ModifierFlags3[ModifierFlags3["SyntacticModifiers"] = 65535] = "SyntacticModifiers"; + ModifierFlags3[ModifierFlags3["JSDocCacheOnlyModifiers"] = 260046848] = "JSDocCacheOnlyModifiers"; + ModifierFlags3[ModifierFlags3["JSDocOnlyModifiers"] = 65536 /* Deprecated */] = "JSDocOnlyModifiers"; + ModifierFlags3[ModifierFlags3["NonCacheOnlyModifiers"] = 131071] = "NonCacheOnlyModifiers"; + ModifierFlags3[ModifierFlags3["HasComputedJSDocModifiers"] = 268435456] = "HasComputedJSDocModifiers"; ModifierFlags3[ModifierFlags3["HasComputedFlags"] = 536870912] = "HasComputedFlags"; - ModifierFlags3[ModifierFlags3["AccessibilityModifier"] = 28] = "AccessibilityModifier"; - ModifierFlags3[ModifierFlags3["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier"; - ModifierFlags3[ModifierFlags3["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; - ModifierFlags3[ModifierFlags3["TypeScriptModifier"] = 117086] = "TypeScriptModifier"; - ModifierFlags3[ModifierFlags3["ExportDefault"] = 1025] = "ExportDefault"; - ModifierFlags3[ModifierFlags3["All"] = 258047] = "All"; - ModifierFlags3[ModifierFlags3["Modifier"] = 126975] = "Modifier"; + ModifierFlags3[ModifierFlags3["AccessibilityModifier"] = 7] = "AccessibilityModifier"; + ModifierFlags3[ModifierFlags3["ParameterPropertyModifier"] = 31] = "ParameterPropertyModifier"; + ModifierFlags3[ModifierFlags3["NonPublicAccessibilityModifier"] = 6] = "NonPublicAccessibilityModifier"; + ModifierFlags3[ModifierFlags3["TypeScriptModifier"] = 28895] = "TypeScriptModifier"; + ModifierFlags3[ModifierFlags3["ExportDefault"] = 2080] = "ExportDefault"; + ModifierFlags3[ModifierFlags3["All"] = 131071] = "All"; + ModifierFlags3[ModifierFlags3["Modifier"] = 98303] = "Modifier"; return ModifierFlags3; })(ModifierFlags || {}); JsxFlags = /* @__PURE__ */ ((JsxFlags2) => { @@ -4453,7 +4435,7 @@ ${lanes.join("\n")} TypeFlags2[TypeFlags2["InstantiablePrimitive"] = 406847488] = "InstantiablePrimitive"; TypeFlags2[TypeFlags2["Instantiable"] = 465829888] = "Instantiable"; TypeFlags2[TypeFlags2["StructuredOrInstantiable"] = 469499904] = "StructuredOrInstantiable"; - TypeFlags2[TypeFlags2["ObjectFlagsType"] = 138117121] = "ObjectFlagsType"; + TypeFlags2[TypeFlags2["ObjectFlagsType"] = 3899393] = "ObjectFlagsType"; TypeFlags2[TypeFlags2["Simplifiable"] = 25165824] = "Simplifiable"; TypeFlags2[TypeFlags2["Singleton"] = 67358815] = "Singleton"; TypeFlags2[TypeFlags2["Narrowable"] = 536624127] = "Narrowable"; @@ -4492,6 +4474,7 @@ ${lanes.join("\n")} ObjectFlags3[ObjectFlags3["ClassOrInterface"] = 3] = "ClassOrInterface"; ObjectFlags3[ObjectFlags3["RequiresWidening"] = 196608] = "RequiresWidening"; ObjectFlags3[ObjectFlags3["PropagatingFlags"] = 458752] = "PropagatingFlags"; + ObjectFlags3[ObjectFlags3["InstantiatedMapped"] = 96] = "InstantiatedMapped"; ObjectFlags3[ObjectFlags3["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask"; ObjectFlags3[ObjectFlags3["ContainsSpread"] = 2097152] = "ContainsSpread"; ObjectFlags3[ObjectFlags3["ObjectRestType"] = 4194304] = "ObjectRestType"; @@ -4645,14 +4628,14 @@ ${lanes.join("\n")} DiagnosticCategory2[DiagnosticCategory2["Message"] = 3] = "Message"; return DiagnosticCategory2; })(DiagnosticCategory || {}); - ModuleResolutionKind = /* @__PURE__ */ ((ModuleResolutionKind2) => { - ModuleResolutionKind2[ModuleResolutionKind2["Classic"] = 1] = "Classic"; - ModuleResolutionKind2[ModuleResolutionKind2["NodeJs"] = 2] = "NodeJs"; - ModuleResolutionKind2[ModuleResolutionKind2["Node10"] = 2] = "Node10"; - ModuleResolutionKind2[ModuleResolutionKind2["Node16"] = 3] = "Node16"; - ModuleResolutionKind2[ModuleResolutionKind2["NodeNext"] = 99] = "NodeNext"; - ModuleResolutionKind2[ModuleResolutionKind2["Bundler"] = 100] = "Bundler"; - return ModuleResolutionKind2; + ModuleResolutionKind = /* @__PURE__ */ ((ModuleResolutionKind3) => { + ModuleResolutionKind3[ModuleResolutionKind3["Classic"] = 1] = "Classic"; + ModuleResolutionKind3[ModuleResolutionKind3["NodeJs"] = 2] = "NodeJs"; + ModuleResolutionKind3[ModuleResolutionKind3["Node10"] = 2] = "Node10"; + ModuleResolutionKind3[ModuleResolutionKind3["Node16"] = 3] = "Node16"; + ModuleResolutionKind3[ModuleResolutionKind3["NodeNext"] = 99] = "NodeNext"; + ModuleResolutionKind3[ModuleResolutionKind3["Bundler"] = 100] = "Bundler"; + return ModuleResolutionKind3; })(ModuleResolutionKind || {}); ModuleDetectionKind = /* @__PURE__ */ ((ModuleDetectionKind2) => { ModuleDetectionKind2[ModuleDetectionKind2["Legacy"] = 1] = "Legacy"; @@ -4660,51 +4643,51 @@ ${lanes.join("\n")} ModuleDetectionKind2[ModuleDetectionKind2["Force"] = 3] = "Force"; return ModuleDetectionKind2; })(ModuleDetectionKind || {}); - WatchFileKind = /* @__PURE__ */ ((WatchFileKind2) => { - WatchFileKind2[WatchFileKind2["FixedPollingInterval"] = 0] = "FixedPollingInterval"; - WatchFileKind2[WatchFileKind2["PriorityPollingInterval"] = 1] = "PriorityPollingInterval"; - WatchFileKind2[WatchFileKind2["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; - WatchFileKind2[WatchFileKind2["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; - WatchFileKind2[WatchFileKind2["UseFsEvents"] = 4] = "UseFsEvents"; - WatchFileKind2[WatchFileKind2["UseFsEventsOnParentDirectory"] = 5] = "UseFsEventsOnParentDirectory"; - return WatchFileKind2; + WatchFileKind = /* @__PURE__ */ ((WatchFileKind3) => { + WatchFileKind3[WatchFileKind3["FixedPollingInterval"] = 0] = "FixedPollingInterval"; + WatchFileKind3[WatchFileKind3["PriorityPollingInterval"] = 1] = "PriorityPollingInterval"; + WatchFileKind3[WatchFileKind3["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; + WatchFileKind3[WatchFileKind3["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; + WatchFileKind3[WatchFileKind3["UseFsEvents"] = 4] = "UseFsEvents"; + WatchFileKind3[WatchFileKind3["UseFsEventsOnParentDirectory"] = 5] = "UseFsEventsOnParentDirectory"; + return WatchFileKind3; })(WatchFileKind || {}); - WatchDirectoryKind = /* @__PURE__ */ ((WatchDirectoryKind2) => { - WatchDirectoryKind2[WatchDirectoryKind2["UseFsEvents"] = 0] = "UseFsEvents"; - WatchDirectoryKind2[WatchDirectoryKind2["FixedPollingInterval"] = 1] = "FixedPollingInterval"; - WatchDirectoryKind2[WatchDirectoryKind2["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; - WatchDirectoryKind2[WatchDirectoryKind2["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; - return WatchDirectoryKind2; + WatchDirectoryKind = /* @__PURE__ */ ((WatchDirectoryKind3) => { + WatchDirectoryKind3[WatchDirectoryKind3["UseFsEvents"] = 0] = "UseFsEvents"; + WatchDirectoryKind3[WatchDirectoryKind3["FixedPollingInterval"] = 1] = "FixedPollingInterval"; + WatchDirectoryKind3[WatchDirectoryKind3["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; + WatchDirectoryKind3[WatchDirectoryKind3["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; + return WatchDirectoryKind3; })(WatchDirectoryKind || {}); - PollingWatchKind = /* @__PURE__ */ ((PollingWatchKind2) => { - PollingWatchKind2[PollingWatchKind2["FixedInterval"] = 0] = "FixedInterval"; - PollingWatchKind2[PollingWatchKind2["PriorityInterval"] = 1] = "PriorityInterval"; - PollingWatchKind2[PollingWatchKind2["DynamicPriority"] = 2] = "DynamicPriority"; - PollingWatchKind2[PollingWatchKind2["FixedChunkSize"] = 3] = "FixedChunkSize"; - return PollingWatchKind2; + PollingWatchKind = /* @__PURE__ */ ((PollingWatchKind3) => { + PollingWatchKind3[PollingWatchKind3["FixedInterval"] = 0] = "FixedInterval"; + PollingWatchKind3[PollingWatchKind3["PriorityInterval"] = 1] = "PriorityInterval"; + PollingWatchKind3[PollingWatchKind3["DynamicPriority"] = 2] = "DynamicPriority"; + PollingWatchKind3[PollingWatchKind3["FixedChunkSize"] = 3] = "FixedChunkSize"; + return PollingWatchKind3; })(PollingWatchKind || {}); - ModuleKind = /* @__PURE__ */ ((ModuleKind2) => { - ModuleKind2[ModuleKind2["None"] = 0] = "None"; - ModuleKind2[ModuleKind2["CommonJS"] = 1] = "CommonJS"; - ModuleKind2[ModuleKind2["AMD"] = 2] = "AMD"; - ModuleKind2[ModuleKind2["UMD"] = 3] = "UMD"; - ModuleKind2[ModuleKind2["System"] = 4] = "System"; - ModuleKind2[ModuleKind2["ES2015"] = 5] = "ES2015"; - ModuleKind2[ModuleKind2["ES2020"] = 6] = "ES2020"; - ModuleKind2[ModuleKind2["ES2022"] = 7] = "ES2022"; - ModuleKind2[ModuleKind2["ESNext"] = 99] = "ESNext"; - ModuleKind2[ModuleKind2["Node16"] = 100] = "Node16"; - ModuleKind2[ModuleKind2["NodeNext"] = 199] = "NodeNext"; - return ModuleKind2; + ModuleKind = /* @__PURE__ */ ((ModuleKind3) => { + ModuleKind3[ModuleKind3["None"] = 0] = "None"; + ModuleKind3[ModuleKind3["CommonJS"] = 1] = "CommonJS"; + ModuleKind3[ModuleKind3["AMD"] = 2] = "AMD"; + ModuleKind3[ModuleKind3["UMD"] = 3] = "UMD"; + ModuleKind3[ModuleKind3["System"] = 4] = "System"; + ModuleKind3[ModuleKind3["ES2015"] = 5] = "ES2015"; + ModuleKind3[ModuleKind3["ES2020"] = 6] = "ES2020"; + ModuleKind3[ModuleKind3["ES2022"] = 7] = "ES2022"; + ModuleKind3[ModuleKind3["ESNext"] = 99] = "ESNext"; + ModuleKind3[ModuleKind3["Node16"] = 100] = "Node16"; + ModuleKind3[ModuleKind3["NodeNext"] = 199] = "NodeNext"; + return ModuleKind3; })(ModuleKind || {}); - JsxEmit = /* @__PURE__ */ ((JsxEmit2) => { - JsxEmit2[JsxEmit2["None"] = 0] = "None"; - JsxEmit2[JsxEmit2["Preserve"] = 1] = "Preserve"; - JsxEmit2[JsxEmit2["React"] = 2] = "React"; - JsxEmit2[JsxEmit2["ReactNative"] = 3] = "ReactNative"; - JsxEmit2[JsxEmit2["ReactJSX"] = 4] = "ReactJSX"; - JsxEmit2[JsxEmit2["ReactJSXDev"] = 5] = "ReactJSXDev"; - return JsxEmit2; + JsxEmit = /* @__PURE__ */ ((JsxEmit3) => { + JsxEmit3[JsxEmit3["None"] = 0] = "None"; + JsxEmit3[JsxEmit3["Preserve"] = 1] = "Preserve"; + JsxEmit3[JsxEmit3["React"] = 2] = "React"; + JsxEmit3[JsxEmit3["ReactNative"] = 3] = "ReactNative"; + JsxEmit3[JsxEmit3["ReactJSX"] = 4] = "ReactJSX"; + JsxEmit3[JsxEmit3["ReactJSXDev"] = 5] = "ReactJSXDev"; + return JsxEmit3; })(JsxEmit || {}); ImportsNotUsedAsValues = /* @__PURE__ */ ((ImportsNotUsedAsValues2) => { ImportsNotUsedAsValues2[ImportsNotUsedAsValues2["Remove"] = 0] = "Remove"; @@ -4712,37 +4695,37 @@ ${lanes.join("\n")} ImportsNotUsedAsValues2[ImportsNotUsedAsValues2["Error"] = 2] = "Error"; return ImportsNotUsedAsValues2; })(ImportsNotUsedAsValues || {}); - NewLineKind = /* @__PURE__ */ ((NewLineKind2) => { - NewLineKind2[NewLineKind2["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; - NewLineKind2[NewLineKind2["LineFeed"] = 1] = "LineFeed"; - return NewLineKind2; + NewLineKind = /* @__PURE__ */ ((NewLineKind3) => { + NewLineKind3[NewLineKind3["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind3[NewLineKind3["LineFeed"] = 1] = "LineFeed"; + return NewLineKind3; })(NewLineKind || {}); - ScriptKind = /* @__PURE__ */ ((ScriptKind6) => { - ScriptKind6[ScriptKind6["Unknown"] = 0] = "Unknown"; - ScriptKind6[ScriptKind6["JS"] = 1] = "JS"; - ScriptKind6[ScriptKind6["JSX"] = 2] = "JSX"; - ScriptKind6[ScriptKind6["TS"] = 3] = "TS"; - ScriptKind6[ScriptKind6["TSX"] = 4] = "TSX"; - ScriptKind6[ScriptKind6["External"] = 5] = "External"; - ScriptKind6[ScriptKind6["JSON"] = 6] = "JSON"; - ScriptKind6[ScriptKind6["Deferred"] = 7] = "Deferred"; - return ScriptKind6; + ScriptKind = /* @__PURE__ */ ((ScriptKind7) => { + ScriptKind7[ScriptKind7["Unknown"] = 0] = "Unknown"; + ScriptKind7[ScriptKind7["JS"] = 1] = "JS"; + ScriptKind7[ScriptKind7["JSX"] = 2] = "JSX"; + ScriptKind7[ScriptKind7["TS"] = 3] = "TS"; + ScriptKind7[ScriptKind7["TSX"] = 4] = "TSX"; + ScriptKind7[ScriptKind7["External"] = 5] = "External"; + ScriptKind7[ScriptKind7["JSON"] = 6] = "JSON"; + ScriptKind7[ScriptKind7["Deferred"] = 7] = "Deferred"; + return ScriptKind7; })(ScriptKind || {}); - ScriptTarget = /* @__PURE__ */ ((ScriptTarget10) => { - ScriptTarget10[ScriptTarget10["ES3"] = 0] = "ES3"; - ScriptTarget10[ScriptTarget10["ES5"] = 1] = "ES5"; - ScriptTarget10[ScriptTarget10["ES2015"] = 2] = "ES2015"; - ScriptTarget10[ScriptTarget10["ES2016"] = 3] = "ES2016"; - ScriptTarget10[ScriptTarget10["ES2017"] = 4] = "ES2017"; - ScriptTarget10[ScriptTarget10["ES2018"] = 5] = "ES2018"; - ScriptTarget10[ScriptTarget10["ES2019"] = 6] = "ES2019"; - ScriptTarget10[ScriptTarget10["ES2020"] = 7] = "ES2020"; - ScriptTarget10[ScriptTarget10["ES2021"] = 8] = "ES2021"; - ScriptTarget10[ScriptTarget10["ES2022"] = 9] = "ES2022"; - ScriptTarget10[ScriptTarget10["ESNext"] = 99] = "ESNext"; - ScriptTarget10[ScriptTarget10["JSON"] = 100] = "JSON"; - ScriptTarget10[ScriptTarget10["Latest"] = 99 /* ESNext */] = "Latest"; - return ScriptTarget10; + ScriptTarget = /* @__PURE__ */ ((ScriptTarget11) => { + ScriptTarget11[ScriptTarget11["ES3"] = 0] = "ES3"; + ScriptTarget11[ScriptTarget11["ES5"] = 1] = "ES5"; + ScriptTarget11[ScriptTarget11["ES2015"] = 2] = "ES2015"; + ScriptTarget11[ScriptTarget11["ES2016"] = 3] = "ES2016"; + ScriptTarget11[ScriptTarget11["ES2017"] = 4] = "ES2017"; + ScriptTarget11[ScriptTarget11["ES2018"] = 5] = "ES2018"; + ScriptTarget11[ScriptTarget11["ES2019"] = 6] = "ES2019"; + ScriptTarget11[ScriptTarget11["ES2020"] = 7] = "ES2020"; + ScriptTarget11[ScriptTarget11["ES2021"] = 8] = "ES2021"; + ScriptTarget11[ScriptTarget11["ES2022"] = 9] = "ES2022"; + ScriptTarget11[ScriptTarget11["ESNext"] = 99] = "ESNext"; + ScriptTarget11[ScriptTarget11["JSON"] = 100] = "JSON"; + ScriptTarget11[ScriptTarget11["Latest"] = 99 /* ESNext */] = "Latest"; + return ScriptTarget11; })(ScriptTarget || {}); LanguageVariant = /* @__PURE__ */ ((LanguageVariant4) => { LanguageVariant4[LanguageVariant4["Standard"] = 0] = "Standard"; @@ -5132,7 +5115,8 @@ ${lanes.join("\n")} ListFormat2[ListFormat2["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements"; ListFormat2[ListFormat2["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements"; ListFormat2[ListFormat2["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties"; - ListFormat2[ListFormat2["ImportClauseEntries"] = 526226] = "ImportClauseEntries"; + ListFormat2[ListFormat2["ImportAttributes"] = 526226] = "ImportAttributes"; + ListFormat2[ListFormat2["ImportClauseEntries"] = 526226 /* ImportAttributes */] = "ImportClauseEntries"; ListFormat2[ListFormat2["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements"; ListFormat2[ListFormat2["CommaListElements"] = 528] = "CommaListElements"; ListFormat2[ListFormat2["CallExpressionArguments"] = 2576] = "CallExpressionArguments"; @@ -5213,6 +5197,13 @@ ${lanes.join("\n")} kind: 4 /* MultiLine */ } }; + JSDocParsingMode = /* @__PURE__ */ ((JSDocParsingMode6) => { + JSDocParsingMode6[JSDocParsingMode6["ParseAll"] = 0] = "ParseAll"; + JSDocParsingMode6[JSDocParsingMode6["ParseNone"] = 1] = "ParseNone"; + JSDocParsingMode6[JSDocParsingMode6["ParseForTypeErrors"] = 2] = "ParseForTypeErrors"; + JSDocParsingMode6[JSDocParsingMode6["ParseForTypeInfo"] = 3] = "ParseForTypeInfo"; + return JSDocParsingMode6; + })(JSDocParsingMode || {}); } }); @@ -5737,11 +5728,11 @@ ${lanes.join("\n")} return some(ignoredPaths, (searchPath) => isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames2, getCurrentDirectory); } function isInPath(path, searchPath) { - if (stringContains(path, searchPath)) + if (path.includes(searchPath)) return true; if (useCaseSensitiveFileNames2) return false; - return stringContains(toCanonicalFilePath(path), searchPath); + return toCanonicalFilePath(path).includes(searchPath); } } function createFileWatcherCallback(callback) { @@ -6576,7 +6567,9 @@ ${lanes.join("\n")} })(); if (sys && sys.getEnvironmentVariable) { setCustomPollingValues(sys); - Debug.setAssertionLevel(/^development$/i.test(sys.getEnvironmentVariable("NODE_ENV")) ? 1 /* Normal */ : 0 /* None */); + Debug.setAssertionLevel( + /^development$/i.test(sys.getEnvironmentVariable("NODE_ENV")) ? 1 /* Normal */ : 0 /* None */ + ); } if (sys && sys.debugMode) { Debug.isDebugging = true; @@ -6608,7 +6601,7 @@ ${lanes.join("\n")} return !pathIsAbsolute(path) && !pathIsRelative(path); } function hasExtension(fileName) { - return stringContains(getBaseFileName(fileName), "."); + return getBaseFileName(fileName).includes("."); } function fileExtensionIs(path, extension) { return path.length > extension.length && endsWith(path, extension); @@ -6756,7 +6749,7 @@ ${lanes.join("\n")} return root + pathComponents2.slice(1, length2).join(directorySeparator); } function normalizeSlashes(path) { - return path.indexOf("\\") !== -1 ? path.replace(backslashRegExp, directorySeparator) : path; + return path.includes("\\") ? path.replace(backslashRegExp, directorySeparator) : path; } function reducePathComponents(components) { if (!some(components)) @@ -7390,9 +7383,8 @@ ${lanes.join("\n")} _0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled: diag(1446, 1 /* Error */, "_0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_preserveVa_1446", "'{0}' resolves to a type-only declaration and must be imported using a type-only import when 'preserveValueImports' and 'isolatedModules' are both enabled."), _0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_enabled: diag(1448, 1 /* Error */, "_0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_1448", "'{0}' resolves to a type-only declaration and must be re-exported using a type-only re-export when '{1}' is enabled."), Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed: diag(1449, 3 /* Message */, "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449", "Preserve unused imported values in the JavaScript output that would otherwise be removed."), - Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments: diag(1450, 3 /* Message */, "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450", "Dynamic imports can only accept a module specifier and an optional assertion as arguments"), + Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments: diag(1450, 3 /* Message */, "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments_1450", "Dynamic imports can only accept a module specifier and an optional set of attributes as arguments"), Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression: diag(1451, 1 /* Error */, "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451", "Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression"), - resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext: diag(1452, 1 /* Error */, "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452", "'resolution-mode' assertions are only supported when `moduleResolution` is `node16` or `nodenext`."), resolution_mode_should_be_either_require_or_import: diag(1453, 1 /* Error */, "resolution_mode_should_be_either_require_or_import_1453", "`resolution-mode` should be either `require` or `import`."), resolution_mode_can_only_be_set_for_type_only_imports: diag(1454, 1 /* Error */, "resolution_mode_can_only_be_set_for_type_only_imports_1454", "`resolution-mode` can only be set for type-only imports."), resolution_mode_is_the_only_valid_key_for_type_import_assertions: diag(1455, 1 /* Error */, "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455", "`resolution-mode` is the only valid key for type import assertions."), @@ -7402,6 +7394,8 @@ ${lanes.join("\n")} File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module: diag(1459, 3 /* Message */, "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459", `File is CommonJS module because '{0}' has field "type" whose value is not "module"`), File_is_CommonJS_module_because_0_does_not_have_field_type: diag(1460, 3 /* Message */, "File_is_CommonJS_module_because_0_does_not_have_field_type_1460", `File is CommonJS module because '{0}' does not have field "type"`), File_is_CommonJS_module_because_package_json_was_not_found: diag(1461, 3 /* Message */, "File_is_CommonJS_module_because_package_json_was_not_found_1461", "File is CommonJS module because 'package.json' was not found"), + resolution_mode_is_the_only_valid_key_for_type_import_attributes: diag(1463, 1 /* Error */, "resolution_mode_is_the_only_valid_key_for_type_import_attributes_1463", "'resolution-mode' is the only valid key for type import attributes."), + Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require: diag(1464, 1 /* Error */, "Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1464", "Type import attributes should have exactly one key - 'resolution-mode' - with value 'import' or 'require'."), The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, 1 /* Error */, "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470", "The 'import.meta' meta-property is not allowed in files which will build into CommonJS output."), 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: diag(1471, 1 /* Error */, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "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."), catch_or_finally_expected: diag(1472, 1 /* Error */, "catch_or_finally_expected_1472", "'catch' or 'finally' expected."), @@ -7428,6 +7422,7 @@ ${lanes.join("\n")} The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration: diag(1493, 1 /* Error */, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration_1493", "The left-hand side of a 'for...in' statement cannot be a 'using' declaration."), The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration: diag(1494, 1 /* Error */, "The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration_1494", "The left-hand side of a 'for...in' statement cannot be an 'await using' declaration."), _0_modifier_cannot_appear_on_an_await_using_declaration: diag(1495, 1 /* Error */, "_0_modifier_cannot_appear_on_an_await_using_declaration_1495", "'{0}' modifier cannot appear on an 'await using' declaration."), + Identifier_string_literal_or_number_literal_expected: diag(1496, 1 /* Error */, "Identifier_string_literal_or_number_literal_expected_1496", "Identifier, string literal, or number literal expected."), The_types_of_0_are_incompatible_between_these_types: diag(2200, 1 /* Error */, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, 1 /* Error */, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag( @@ -7534,7 +7529,7 @@ ${lanes.join("\n")} An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, 1 /* Error */, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, 1 /* Error */, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, 1 /* Error */, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), - The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, 1 /* Error */, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), + The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_type_assignable_to_the_Function_interface_type_or_an_object_type_with_a_Symbol_hasInstance_method: diag(2359, 1 /* Error */, "The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_2359", "The right-hand side of an 'instanceof' expression must be either of type 'any', a class, function, or other type assignable to the 'Function' interface type, or an object type with a 'Symbol.hasInstance' method."), The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, 1 /* Error */, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, 1 /* Error */, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, 1 /* Error */, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), @@ -7957,15 +7952,15 @@ ${lanes.join("\n")} Type_0_is_not_assignable_to_type_1_Did_you_mean_2: diag(2820, 1 /* Error */, "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820", "Type '{0}' is not assignable to type '{1}'. Did you mean '{2}'?"), Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext: diag(2821, 1 /* Error */, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext_2821", "Import assertions are only supported when the '--module' option is set to 'esnext' or 'nodenext'."), Import_assertions_cannot_be_used_with_type_only_imports_or_exports: diag(2822, 1 /* Error */, "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822", "Import assertions cannot be used with type-only imports or exports."), + Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext: diag(2823, 1 /* Error */, "Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext_2823", "Import attributes are only supported when the '--module' option is set to 'esnext' or 'nodenext'."), Cannot_find_namespace_0_Did_you_mean_1: diag(2833, 1 /* Error */, "Cannot_find_namespace_0_Did_you_mean_1_2833", "Cannot find namespace '{0}'. Did you mean '{1}'?"), - Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node16_or_nodenext_Consider_adding_an_extension_to_the_import_path: diag(2834, 1 /* Error */, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2834", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Consider adding an extension to the import path."), - Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node16_or_nodenext_Did_you_mean_0: diag(2835, 1 /* Error */, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2835", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean '{0}'?"), - Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls: diag(2836, 1 /* Error */, "Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls_2836", "Import assertions are not allowed on statements that transpile to commonjs 'require' calls."), + Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Consider_adding_an_extension_to_the_import_path: diag(2834, 1 /* Error */, "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2834", "Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Consider adding an extension to the import path."), + Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Did_you_mean_0: diag(2835, 1 /* Error */, "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2835", "Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean '{0}'?"), + Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls: diag(2836, 1 /* Error */, "Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2836", "Import assertions are not allowed on statements that compile to CommonJS 'require' calls."), Import_assertion_values_must_be_string_literal_expressions: diag(2837, 1 /* Error */, "Import_assertion_values_must_be_string_literal_expressions_2837", "Import assertion values must be string literal expressions."), All_declarations_of_0_must_have_identical_constraints: diag(2838, 1 /* Error */, "All_declarations_of_0_must_have_identical_constraints_2838", "All declarations of '{0}' must have identical constraints."), This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value: diag(2839, 1 /* Error */, "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839", "This condition will always return '{0}' since JavaScript compares objects by reference, not value."), - An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes: diag(2840, 1 /* Error */, "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840", "An interface cannot extend a primitive type like '{0}'; an interface can only extend named types and classes"), - The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(2841, 1 /* Error */, "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841", "The type of this expression cannot be named without a 'resolution-mode' assertion, which is an unstable feature. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types: diag(2840, 1 /* Error */, "An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types_2840", "An interface cannot extend a primitive type like '{0}'. It can only extend other named object types."), _0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation: diag(2842, 1 /* Error */, "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842", "'{0}' is an unused renaming of '{1}'. Did you intend to use it as a type annotation?"), We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here: diag(2843, 1 /* Error */, "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843", "We can only write a type for '{0}' by adding a type for the entire parameter here."), Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2844, 1 /* Error */, "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844", "Type of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), @@ -7978,6 +7973,16 @@ ${lanes.join("\n")} await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(2852, 1 /* Error */, "await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_2852", "'await using' statements are only allowed within async functions and at the top levels of modules."), await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(2853, 1 /* Error */, "await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_th_2853", "'await using' statements are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher: diag(2854, 1 /* Error */, "Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_sys_2854", "Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher."), + Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super: diag(2855, 1 /* Error */, "Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super_2855", "Class field '{0}' defined by the parent class is not accessible in the child class via super."), + Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls: diag(2856, 1 /* Error */, "Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2856", "Import attributes are not allowed on statements that compile to CommonJS 'require' calls."), + Import_attributes_cannot_be_used_with_type_only_imports_or_exports: diag(2857, 1 /* Error */, "Import_attributes_cannot_be_used_with_type_only_imports_or_exports_2857", "Import attributes cannot be used with type-only imports or exports."), + Import_attribute_values_must_be_string_literal_expressions: diag(2858, 1 /* Error */, "Import_attribute_values_must_be_string_literal_expressions_2858", "Import attribute values must be string literal expressions."), + Excessive_complexity_comparing_types_0_and_1: diag(2859, 1 /* Error */, "Excessive_complexity_comparing_types_0_and_1_2859", "Excessive complexity comparing types '{0}' and '{1}'."), + The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_hand_side_s_Symbol_hasInstance_method: diag(2860, 1 /* Error */, "The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_2860", "The left-hand side of an 'instanceof' expression must be assignable to the first argument of the right-hand side's '[Symbol.hasInstance]' method."), + An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_hand_side_of_an_instanceof_expression: diag(2861, 1 /* Error */, "An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_han_2861", "An object's '[Symbol.hasInstance]' method must return a boolean value for it to be used on the right-hand side of an 'instanceof' expression."), + Type_0_is_generic_and_can_only_be_indexed_for_reading: diag(2862, 1 /* Error */, "Type_0_is_generic_and_can_only_be_indexed_for_reading_2862", "Type '{0}' is generic and can only be indexed for reading."), + A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values: diag(2863, 1 /* Error */, "A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values_2863", "A class cannot extend a primitive type like '{0}'. Classes can only extend constructable values."), + A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types: diag(2864, 1 /* Error */, "A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types_2864", "A class cannot implement a primitive type like '{0}'. It can only implement other named object types."), Import_declaration_0_is_using_private_name_1: diag(4e3, 1 /* Error */, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, 1 /* Error */, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, 1 /* Error */, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -8086,7 +8091,6 @@ ${lanes.join("\n")} This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, 1 /* Error */, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, 1 /* Error */, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, 1 /* Error */, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), - resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4125, 1 /* Error */, "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125", "'resolution-mode' assertions are unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), The_current_host_does_not_support_the_0_option: diag(5001, 1 /* Error */, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, 1 /* Error */, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, 1 /* Error */, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -8819,6 +8823,7 @@ ${lanes.join("\n")} Unknown_type_acquisition_option_0_Did_you_mean_1: diag(17018, 1 /* Error */, "Unknown_type_acquisition_option_0_Did_you_mean_1_17018", "Unknown type acquisition option '{0}'. Did you mean '{1}'?"), _0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1: diag(17019, 1 /* Error */, "_0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17019", "'{0}' at the end of a type is not valid TypeScript syntax. Did you mean to write '{1}'?"), _0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1: diag(17020, 1 /* Error */, "_0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17020", "'{0}' at the start of a type is not valid TypeScript syntax. Did you mean to write '{1}'?"), + Unicode_escape_sequence_cannot_appear_here: diag(17021, 1 /* Error */, "Unicode_escape_sequence_cannot_appear_here_17021", "Unicode escape sequence cannot appear here."), Circularity_detected_while_resolving_configuration_Colon_0: diag(18e3, 1 /* Error */, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), The_files_list_in_config_file_0_is_empty: diag(18002, 1 /* Error */, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, 1 /* Error */, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), @@ -9024,7 +9029,7 @@ ${lanes.join("\n")} Could_not_convert_to_arrow_function: diag(95151, 3 /* Message */, "Could_not_convert_to_arrow_function_95151", "Could not convert to arrow function"), Could_not_convert_to_named_function: diag(95152, 3 /* Message */, "Could_not_convert_to_named_function_95152", "Could not convert to named function"), Could_not_convert_to_anonymous_function: diag(95153, 3 /* Message */, "Could_not_convert_to_anonymous_function_95153", "Could not convert to anonymous function"), - Can_only_convert_string_concatenation: diag(95154, 3 /* Message */, "Can_only_convert_string_concatenation_95154", "Can only convert string concatenation"), + Can_only_convert_string_concatenations_and_string_literals: diag(95154, 3 /* Message */, "Can_only_convert_string_concatenations_and_string_literals_95154", "Can only convert string concatenations and string literals"), Selection_is_not_a_valid_statement_or_statements: diag(95155, 3 /* Message */, "Selection_is_not_a_valid_statement_or_statements_95155", "Selection is not a valid statement or statements"), Add_missing_function_declaration_0: diag(95156, 3 /* Message */, "Add_missing_function_declaration_0_95156", "Add missing function declaration '{0}'"), Add_all_missing_function_declarations: diag(95157, 3 /* Message */, "Add_all_missing_function_declarations_95157", "Add all missing function declarations"), @@ -9615,6 +9620,8 @@ ${lanes.join("\n")} var tokenFlags; var commentDirectives; var inJSDocType = 0; + var scriptKind = 0 /* Unknown */; + var jsDocParsingMode = 0 /* ParseAll */; setText(text, start, length2); var scanner2 = { getTokenFullStart: () => fullStartPos, @@ -9658,6 +9665,8 @@ ${lanes.join("\n")} setText, setScriptTarget, setLanguageVariant, + setScriptKind, + setJSDocParsingMode, setOnError, resetTokenState, setTextPos: resetTokenState, @@ -9911,7 +9920,7 @@ ${lanes.join("\n")} start2 = pos; continue; } - if (isLineBreak(ch) && !jsxAttributeString) { + if ((ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */) && !jsxAttributeString) { result += text.substring(start2, pos); tokenFlags |= 4 /* Unterminated */; error2(Diagnostics.Unterminated_string_literal); @@ -10000,7 +10009,7 @@ ${lanes.join("\n")} tokenFlags |= 2048 /* ContainsInvalidEscape */; if (shouldEmitInvalidEscapeError) { const code = parseInt(text.substring(start2 + 1, pos), 8); - error2(Diagnostics.Octal_escape_sequences_are_not_allowed_Use_the_syntax_0, start2, pos - start2, "\\x" + padLeft(code.toString(16), 2, "0")); + error2(Diagnostics.Octal_escape_sequences_are_not_allowed_Use_the_syntax_0, start2, pos - start2, "\\x" + code.toString(16).padStart(2, "0")); return String.fromCharCode(code); } return text.substring(start2, pos); @@ -10436,9 +10445,7 @@ ${lanes.join("\n")} } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { pos += 2; - if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) { - tokenFlags |= 2 /* PrecedingJSDocComment */; - } + const isJSDoc2 = text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */; let commentClosed = false; let lastLineStart = tokenStart; while (pos < end) { @@ -10454,6 +10461,9 @@ ${lanes.join("\n")} tokenFlags |= 1 /* PrecedingLineBreak */; } } + if (isJSDoc2 && shouldParseJSDoc()) { + tokenFlags |= 2 /* PrecedingJSDocComment */; + } commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart); if (!commentClosed) { error2(Diagnostics.Asterisk_Slash_expected); @@ -10710,6 +10720,21 @@ ${lanes.join("\n")} } } } + function shouldParseJSDoc() { + switch (jsDocParsingMode) { + case 0 /* ParseAll */: + return true; + case 1 /* ParseNone */: + return false; + } + if (scriptKind !== 3 /* TS */ && scriptKind !== 4 /* TSX */) { + return true; + } + if (jsDocParsingMode === 3 /* ParseForTypeInfo */) { + return false; + } + return jsDocSeeOrLink.test(text.slice(fullStartPos, pos)); + } function reScanInvalidIdentifier() { Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); pos = tokenStart = fullStartPos; @@ -10803,7 +10828,7 @@ ${lanes.join("\n")} return token; } function appendIfCommentDirective(commentDirectives2, text2, commentDirectiveRegEx, lineStart) { - const type = getDirectiveFromComment(trimStringStart(text2), commentDirectiveRegEx); + const type = getDirectiveFromComment(text2.trimStart(), commentDirectiveRegEx); if (type === void 0) { return commentDirectives2; } @@ -11124,6 +11149,12 @@ ${lanes.join("\n")} function setLanguageVariant(variant) { languageVariant = variant; } + function setScriptKind(kind) { + scriptKind = kind; + } + function setJSDocParsingMode(kind) { + jsDocParsingMode = kind; + } function resetTokenState(position) { Debug.assert(position >= 0); pos = position; @@ -11137,6 +11168,9 @@ ${lanes.join("\n")} inJSDocType += inType ? 1 : -1; } } + function codePointAt(s, i) { + return s.codePointAt(i); + } function charSize(ch) { if (ch >= 65536) { return 2; @@ -11155,7 +11189,7 @@ ${lanes.join("\n")} function utf16EncodeAsString(codePoint) { return utf16EncodeAsStringWorker(codePoint); } - var textToKeywordObj, textToKeyword, textToToken, unicodeES3IdentifierStart, unicodeES3IdentifierPart, unicodeES5IdentifierStart, unicodeES5IdentifierPart, unicodeESNextIdentifierStart, unicodeESNextIdentifierPart, commentDirectiveRegExSingleLine, commentDirectiveRegExMultiLine, tokenStrings, mergeConflictMarkerLength, shebangTriviaRegex, codePointAt, utf16EncodeAsStringWorker; + var textToKeywordObj, textToKeyword, textToToken, unicodeES3IdentifierStart, unicodeES3IdentifierPart, unicodeES5IdentifierStart, unicodeES5IdentifierPart, unicodeESNextIdentifierStart, unicodeESNextIdentifierPart, commentDirectiveRegExSingleLine, commentDirectiveRegExMultiLine, jsDocSeeOrLink, tokenStrings, mergeConflictMarkerLength, shebangTriviaRegex, utf16EncodeAsStringWorker; var init_scanner = __esm({ "src/compiler/scanner.ts"() { "use strict"; @@ -11318,23 +11352,10 @@ ${lanes.join("\n")} unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6e3, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999]; commentDirectiveRegExSingleLine = /^\/\/\/?\s*@(ts-expect-error|ts-ignore)/; commentDirectiveRegExMultiLine = /^(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/; + jsDocSeeOrLink = /@(?:see|link)/i; tokenStrings = makeReverseMap(textToToken); mergeConflictMarkerLength = "<<<<<<<".length; shebangTriviaRegex = /^#!.*/; - codePointAt = String.prototype.codePointAt ? (s, i) => s.codePointAt(i) : function codePointAt2(str, i) { - const size = str.length; - if (i < 0 || i >= size) { - return void 0; - } - const first2 = str.charCodeAt(i); - if (first2 >= 55296 && first2 <= 56319 && size > i + 1) { - const second = str.charCodeAt(i + 1); - if (second >= 56320 && second <= 57343) { - return (first2 - 55296) * 1024 + second - 56320 + 65536; - } - } - return first2; - }; utf16EncodeAsStringWorker = String.fromCodePoint ? (codePoint) => String.fromCodePoint(codePoint) : utf16EncodeAsStringFallback; } }); @@ -11474,7 +11495,7 @@ ${lanes.join("\n")} } } function isParameterPropertyDeclaration(node, parent2) { - return isParameter(node) && hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) && parent2.kind === 176 /* Constructor */; + return isParameter(node) && hasSyntacticModifier(node, 31 /* ParameterPropertyModifier */) && parent2.kind === 176 /* Constructor */; } function isEmptyBindingPattern(node) { if (isBindingPattern(node)) { @@ -11763,7 +11784,7 @@ ${lanes.join("\n")} } } function getModifiers(node) { - if (hasSyntacticModifier(node, 126975 /* Modifier */)) { + if (hasSyntacticModifier(node, 98303 /* Modifier */)) { return filter(node.modifiers, isModifier); } } @@ -12151,12 +12172,12 @@ ${lanes.join("\n")} function isTypeOnlyImportOrExportDeclaration(node) { return isTypeOnlyImportDeclaration(node) || isTypeOnlyExportDeclaration(node); } - function isAssertionKey(node) { - return isStringLiteral(node) || isIdentifier(node); - } function isStringTextContainingNode(node) { return node.kind === 11 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } + function isImportAttributeName(node) { + return isStringLiteral(node) || isIdentifier(node); + } function isGeneratedIdentifier(node) { var _a; return isIdentifier(node) && ((_a = node.emitNode) == null ? void 0 : _a.autoGenerate) !== void 0; @@ -12197,7 +12218,7 @@ ${lanes.join("\n")} return false; } function isParameterPropertyModifier(kind) { - return !!(modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */); + return !!(modifierToFlag(kind) & 31 /* ParameterPropertyModifier */); } function isClassMemberModifier(idToken) { return isParameterPropertyModifier(idToken) || idToken === 126 /* StaticKeyword */ || idToken === 164 /* OverrideKeyword */ || idToken === 129 /* AccessorKeyword */; @@ -12274,6 +12295,16 @@ ${lanes.join("\n")} function isAutoAccessorPropertyDeclaration(node) { return isPropertyDeclaration(node) && hasAccessorModifier(node); } + function isClassInstanceProperty(node) { + if (isInJSFile(node) && isExpandoPropertyDeclaration(node)) { + return (!isBindableStaticAccessExpression(node) || !isPrototypeAccess(node.expression)) && !isBindableStaticNameExpression( + node, + /*excludeThisKeyword*/ + true + ); + } + return node.parent && isClassLike(node.parent) && isPropertyDeclaration(node) && !hasAccessorModifier(node); + } function isMethodOrAccessor(node) { switch (node.kind) { case 174 /* MethodDeclaration */: @@ -12402,6 +12433,9 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 211 /* PropertyAccessExpression */ || kind === 166 /* QualifiedName */; } + function isCallLikeOrFunctionLikeExpression(node) { + return isCallLikeExpression(node) || isFunctionExpressionOrArrowFunction(node); + } function isCallLikeExpression(node) { switch (node.kind) { case 286 /* JsxOpeningElement */: @@ -12548,10 +12582,10 @@ ${lanes.join("\n")} return some(statements, isScopeMarker); } function needsScopeMarker(result) { - return !isAnyImportOrReExport(result) && !isExportAssignment(result) && !hasSyntacticModifier(result, 1 /* Export */) && !isAmbientModule(result); + return !isAnyImportOrReExport(result) && !isExportAssignment(result) && !hasSyntacticModifier(result, 32 /* Export */) && !isAmbientModule(result); } function isExternalModuleIndicator(result) { - return isAnyImportOrReExport(result) || isExportAssignment(result) || hasSyntacticModifier(result, 1 /* Export */); + return isAnyImportOrReExport(result) || isExportAssignment(result) || hasSyntacticModifier(result, 32 /* Export */); } function isForInOrOfStatement(node) { return node.kind === 249 /* ForInStatement */ || node.kind === 250 /* ForOfStatement */; @@ -12973,26 +13007,6 @@ ${lanes.join("\n")} function getFullWidth(node) { return node.end - node.pos; } - function getResolvedModule(sourceFile, moduleNameText, mode) { - var _a, _b; - return (_b = (_a = sourceFile == null ? void 0 : sourceFile.resolvedModules) == null ? void 0 : _a.get(moduleNameText, mode)) == null ? void 0 : _b.resolvedModule; - } - function setResolvedModule(sourceFile, moduleNameText, resolvedModule, mode) { - if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = createModeAwareCache(); - } - sourceFile.resolvedModules.set(moduleNameText, mode, resolvedModule); - } - function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective, mode) { - if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = createModeAwareCache(); - } - sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, mode, resolvedTypeReferenceDirective); - } - function getResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, mode) { - var _a, _b; - return (_b = (_a = sourceFile == null ? void 0 : sourceFile.resolvedTypeReferenceDirectiveNames) == null ? void 0 : _a.get(typeReferenceDirectiveName, mode)) == null ? void 0 : _b.resolvedTypeReferenceDirective; - } function projectReferenceIsEqualTo(oldRef, newRef) { return oldRef.path === newRef.path && !oldRef.prepend === !newRef.prepend && !oldRef.circular === !newRef.circular; } @@ -13000,14 +13014,14 @@ ${lanes.join("\n")} return oldResolution === newResolution || oldResolution.resolvedModule === newResolution.resolvedModule || !!oldResolution.resolvedModule && !!newResolution.resolvedModule && oldResolution.resolvedModule.isExternalLibraryImport === newResolution.resolvedModule.isExternalLibraryImport && oldResolution.resolvedModule.extension === newResolution.resolvedModule.extension && oldResolution.resolvedModule.resolvedFileName === newResolution.resolvedModule.resolvedFileName && oldResolution.resolvedModule.originalPath === newResolution.resolvedModule.originalPath && packageIdIsEqual(oldResolution.resolvedModule.packageId, newResolution.resolvedModule.packageId) && oldResolution.node10Result === newResolution.node10Result; } function createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageName) { - var _a, _b; - const node10Result = (_b = (_a = sourceFile.resolvedModules) == null ? void 0 : _a.get(moduleReference, mode)) == null ? void 0 : _b.node10Result; + var _a; + const node10Result = (_a = host.getResolvedModule(sourceFile, moduleReference, mode)) == null ? void 0 : _a.node10Result; const result = node10Result ? chainDiagnosticMessages( /*details*/ void 0, Diagnostics.There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The_1_library_may_need_to_update_its_package_json_or_typings, node10Result, - node10Result.indexOf(nodeModulesPathPart + "@types/") > -1 ? `@types/${mangleScopedPackageName(packageName)}` : packageName + node10Result.includes(nodeModulesPathPart + "@types/") ? `@types/${mangleScopedPackageName(packageName)}` : packageName ) : host.typesPackageExists(packageName) ? chainDiagnosticMessages( /*details*/ void 0, @@ -13043,14 +13057,14 @@ ${lanes.join("\n")} function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution === newResolution || oldResolution.resolvedTypeReferenceDirective === newResolution.resolvedTypeReferenceDirective || !!oldResolution.resolvedTypeReferenceDirective && !!newResolution.resolvedTypeReferenceDirective && oldResolution.resolvedTypeReferenceDirective.resolvedFileName === newResolution.resolvedTypeReferenceDirective.resolvedFileName && !!oldResolution.resolvedTypeReferenceDirective.primary === !!newResolution.resolvedTypeReferenceDirective.primary && oldResolution.resolvedTypeReferenceDirective.originalPath === newResolution.resolvedTypeReferenceDirective.originalPath; } - function hasChangesInResolutions(names, newSourceFile, newResolutions, oldResolutions, comparer, nameAndModeGetter) { + function hasChangesInResolutions(names, newSourceFile, newResolutions, getOldResolution, comparer, nameAndModeGetter) { Debug.assert(names.length === newResolutions.length); for (let i = 0; i < names.length; i++) { const newResolution = newResolutions[i]; const entry = names[i]; const name = nameAndModeGetter.getName(entry); const mode = nameAndModeGetter.getMode(entry, newSourceFile); - const oldResolution = oldResolutions && oldResolutions.get(name, mode); + const oldResolution = getOldResolution(name, mode); const changed = oldResolution ? !newResolution || !comparer(oldResolution, newResolution) : newResolution; if (changed) { return true; @@ -13283,7 +13297,7 @@ ${lanes.join("\n")} } let text = sourceText.substring(includeTrivia ? node.pos : skipTrivia(sourceText, node.pos), node.end); if (isJSDocTypeExpressionOrChild(node)) { - text = text.split(/\r\n|\n|\r/).map((line) => trimStringStart(line.replace(/^\s*\*/, ""))).join("\n"); + text = text.split(/\r\n|\n|\r/).map((line) => line.replace(/^\s*\*/, "").trimStart()).join("\n"); } return text; } @@ -13304,402 +13318,6 @@ ${lanes.join("\n")} const emitNode = node.emitNode; return emitNode && emitNode.internalFlags || 0; } - function getScriptTargetFeatures() { - return new Map(Object.entries({ - Array: new Map(Object.entries({ - es2015: [ - "find", - "findIndex", - "fill", - "copyWithin", - "entries", - "keys", - "values" - ], - es2016: [ - "includes" - ], - es2019: [ - "flat", - "flatMap" - ], - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Iterator: new Map(Object.entries({ - es2015: emptyArray - })), - AsyncIterator: new Map(Object.entries({ - es2015: emptyArray - })), - Atomics: new Map(Object.entries({ - es2017: emptyArray - })), - SharedArrayBuffer: new Map(Object.entries({ - es2017: emptyArray - })), - AsyncIterable: new Map(Object.entries({ - es2018: emptyArray - })), - AsyncIterableIterator: new Map(Object.entries({ - es2018: emptyArray - })), - AsyncGenerator: new Map(Object.entries({ - es2018: emptyArray - })), - AsyncGeneratorFunction: new Map(Object.entries({ - es2018: emptyArray - })), - RegExp: new Map(Object.entries({ - es2015: [ - "flags", - "sticky", - "unicode" - ], - es2018: [ - "dotAll" - ] - })), - Reflect: new Map(Object.entries({ - es2015: [ - "apply", - "construct", - "defineProperty", - "deleteProperty", - "get", - " getOwnPropertyDescriptor", - "getPrototypeOf", - "has", - "isExtensible", - "ownKeys", - "preventExtensions", - "set", - "setPrototypeOf" - ] - })), - ArrayConstructor: new Map(Object.entries({ - es2015: [ - "from", - "of" - ] - })), - ObjectConstructor: new Map(Object.entries({ - es2015: [ - "assign", - "getOwnPropertySymbols", - "keys", - "is", - "setPrototypeOf" - ], - es2017: [ - "values", - "entries", - "getOwnPropertyDescriptors" - ], - es2019: [ - "fromEntries" - ], - es2022: [ - "hasOwn" - ] - })), - NumberConstructor: new Map(Object.entries({ - es2015: [ - "isFinite", - "isInteger", - "isNaN", - "isSafeInteger", - "parseFloat", - "parseInt" - ] - })), - Math: new Map(Object.entries({ - es2015: [ - "clz32", - "imul", - "sign", - "log10", - "log2", - "log1p", - "expm1", - "cosh", - "sinh", - "tanh", - "acosh", - "asinh", - "atanh", - "hypot", - "trunc", - "fround", - "cbrt" - ] - })), - Map: new Map(Object.entries({ - es2015: [ - "entries", - "keys", - "values" - ] - })), - Set: new Map(Object.entries({ - es2015: [ - "entries", - "keys", - "values" - ] - })), - PromiseConstructor: new Map(Object.entries({ - es2015: [ - "all", - "race", - "reject", - "resolve" - ], - es2020: [ - "allSettled" - ], - es2021: [ - "any" - ] - })), - Symbol: new Map(Object.entries({ - es2015: [ - "for", - "keyFor" - ], - es2019: [ - "description" - ] - })), - WeakMap: new Map(Object.entries({ - es2015: [ - "entries", - "keys", - "values" - ] - })), - WeakSet: new Map(Object.entries({ - es2015: [ - "entries", - "keys", - "values" - ] - })), - String: new Map(Object.entries({ - es2015: [ - "codePointAt", - "includes", - "endsWith", - "normalize", - "repeat", - "startsWith", - "anchor", - "big", - "blink", - "bold", - "fixed", - "fontcolor", - "fontsize", - "italics", - "link", - "small", - "strike", - "sub", - "sup" - ], - es2017: [ - "padStart", - "padEnd" - ], - es2019: [ - "trimStart", - "trimEnd", - "trimLeft", - "trimRight" - ], - es2020: [ - "matchAll" - ], - es2021: [ - "replaceAll" - ], - es2022: [ - "at" - ] - })), - StringConstructor: new Map(Object.entries({ - es2015: [ - "fromCodePoint", - "raw" - ] - })), - DateTimeFormat: new Map(Object.entries({ - es2017: [ - "formatToParts" - ] - })), - Promise: new Map(Object.entries({ - es2015: emptyArray, - es2018: [ - "finally" - ] - })), - RegExpMatchArray: new Map(Object.entries({ - es2018: [ - "groups" - ] - })), - RegExpExecArray: new Map(Object.entries({ - es2018: [ - "groups" - ] - })), - Intl: new Map(Object.entries({ - es2018: [ - "PluralRules" - ] - })), - NumberFormat: new Map(Object.entries({ - es2018: [ - "formatToParts" - ] - })), - SymbolConstructor: new Map(Object.entries({ - es2020: [ - "matchAll" - ] - })), - DataView: new Map(Object.entries({ - es2020: [ - "setBigInt64", - "setBigUint64", - "getBigInt64", - "getBigUint64" - ] - })), - BigInt: new Map(Object.entries({ - es2020: emptyArray - })), - RelativeTimeFormat: new Map(Object.entries({ - es2020: [ - "format", - "formatToParts", - "resolvedOptions" - ] - })), - Int8Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Uint8Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Uint8ClampedArray: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Int16Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Uint16Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Int32Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Uint32Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Float32Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Float64Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - BigInt64Array: new Map(Object.entries({ - es2020: emptyArray, - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - BigUint64Array: new Map(Object.entries({ - es2020: emptyArray, - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Error: new Map(Object.entries({ - es2022: [ - "cause" - ] - })) - })); - } function getLiteralText(node, sourceFile, flags) { if (sourceFile && canUseOriginalText(node, flags)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); @@ -13843,7 +13461,7 @@ ${lanes.join("\n")} return false; } function isAmbientPropertyDeclaration(node) { - return !!(node.flags & 33554432 /* Ambient */) || hasSyntacticModifier(node, 2 /* Ambient */); + return !!(node.flags & 33554432 /* Ambient */) || hasSyntacticModifier(node, 128 /* Ambient */); } function isBlockScope(node, parentNode) { switch (node.kind) { @@ -14031,16 +13649,14 @@ ${lanes.join("\n")} const start = skipTrivia(sourceFile.text, nodes.pos); return createFileDiagnosticFromMessageChain(sourceFile, start, nodes.end - start, messageChain, relatedInformation); } - function assertDiagnosticLocation(file, start, length2) { + function assertDiagnosticLocation(sourceText, start, length2) { Debug.assertGreaterThanOrEqual(start, 0); Debug.assertGreaterThanOrEqual(length2, 0); - if (file) { - Debug.assertLessThanOrEqual(start, file.text.length); - Debug.assertLessThanOrEqual(start + length2, file.text.length); - } + Debug.assertLessThanOrEqual(start, sourceText.length); + Debug.assertLessThanOrEqual(start + length2, sourceText.length); } function createFileDiagnosticFromMessageChain(file, start, length2, messageChain, relatedInformation) { - assertDiagnosticLocation(file, start, length2); + assertDiagnosticLocation(file.text, start, length2); return { file, start, @@ -14198,10 +13814,10 @@ ${lanes.join("\n")} return file.scriptKind === 6 /* JSON */; } function isEnumConst(node) { - return !!(getCombinedModifierFlags(node) & 2048 /* Const */); + return !!(getCombinedModifierFlags(node) & 4096 /* Const */); } function isDeclarationReadonly(declaration) { - return !!(getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !isParameterPropertyDeclaration(declaration, declaration.parent)); + return !!(getCombinedModifierFlags(declaration) & 8 /* Readonly */ && !isParameterPropertyDeclaration(declaration, declaration.parent)); } function isVarAwaitUsing(node) { return (getCombinedNodeFlags(node) & 7 /* BlockScoped */) === 6 /* AwaitUsing */; @@ -14278,10 +13894,7 @@ ${lanes.join("\n")} } else if (node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } - Debug.assert( - node.kind === 80 /* Identifier */ || node.kind === 166 /* QualifiedName */ || node.kind === 211 /* PropertyAccessExpression */, - "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'." - ); + Debug.assert(node.kind === 80 /* Identifier */ || node.kind === 166 /* QualifiedName */ || node.kind === 211 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); case 166 /* QualifiedName */: case 211 /* PropertyAccessExpression */: case 110 /* ThisKeyword */: { @@ -14496,11 +14109,7 @@ ${lanes.join("\n")} }); } function getPropertyArrayElementValue(objectLiteral, propKey, elementValue) { - return forEachPropertyAssignment( - objectLiteral, - propKey, - (property) => isArrayLiteralExpression(property.initializer) ? find(property.initializer.elements, (element) => isStringLiteral(element) && element.text === elementValue) : void 0 - ); + return forEachPropertyAssignment(objectLiteral, propKey, (property) => isArrayLiteralExpression(property.initializer) ? find(property.initializer.elements, (element) => isStringLiteral(element) && element.text === elementValue) : void 0); } function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { @@ -14720,6 +14329,8 @@ ${lanes.join("\n")} case 286 /* JsxOpeningElement */: case 285 /* JsxSelfClosingElement */: return node.tagName; + case 226 /* BinaryExpression */: + return node.right; default: return node.expression; } @@ -14909,8 +14520,8 @@ ${lanes.join("\n")} return forStatement.initializer === node && forStatement.initializer.kind !== 261 /* VariableDeclarationList */ || forStatement.condition === node || forStatement.incrementor === node; case 249 /* ForInStatement */: case 250 /* ForOfStatement */: - const forInStatement = parent2; - return forInStatement.initializer === node && forInStatement.initializer.kind !== 261 /* VariableDeclarationList */ || forInStatement.expression === node; + const forInOrOfStatement = parent2; + return forInOrOfStatement.initializer === node && forInOrOfStatement.initializer.kind !== 261 /* VariableDeclarationList */ || forInOrOfStatement.expression === node; case 216 /* TypeAssertionExpression */: case 234 /* AsExpression */: return node === parent2.expression; @@ -15273,6 +14884,7 @@ ${lanes.join("\n")} true ))) == null ? void 0 : _a.arguments[0]; case 272 /* ImportDeclaration */: + case 278 /* ExportDeclaration */: return tryCast(node.moduleSpecifier, isStringLiteralLike); case 271 /* ImportEqualsDeclaration */: return tryCast((_b = tryCast(node.moduleReference, isExternalModuleReference)) == null ? void 0 : _b.expression, isStringLiteralLike); @@ -15284,6 +14896,8 @@ ${lanes.join("\n")} return tryCast(node.parent.parent.moduleSpecifier, isStringLiteralLike); case 276 /* ImportSpecifier */: return tryCast(node.parent.parent.parent.moduleSpecifier, isStringLiteralLike); + case 205 /* ImportType */: + return isLiteralImportTypeNode(node) ? node.argument.literal : void 0; default: Debug.assertNever(node); } @@ -15534,9 +15148,9 @@ ${lanes.join("\n")} } function getNextJSDocCommentLocation(node) { const parent2 = node.parent; - if (parent2.kind === 303 /* PropertyAssignment */ || parent2.kind === 277 /* ExportAssignment */ || parent2.kind === 172 /* PropertyDeclaration */ || parent2.kind === 244 /* ExpressionStatement */ && node.kind === 211 /* PropertyAccessExpression */ || parent2.kind === 253 /* ReturnStatement */ || getNestedModuleDeclaration(parent2) || isBinaryExpression(node) && node.operatorToken.kind === 64 /* EqualsToken */) { + if (parent2.kind === 303 /* PropertyAssignment */ || parent2.kind === 277 /* ExportAssignment */ || parent2.kind === 172 /* PropertyDeclaration */ || parent2.kind === 244 /* ExpressionStatement */ && node.kind === 211 /* PropertyAccessExpression */ || parent2.kind === 253 /* ReturnStatement */ || getNestedModuleDeclaration(parent2) || isAssignmentExpression(node)) { return parent2; - } else if (parent2.parent && (getSingleVariableOfVariableStatement(parent2.parent) === node || isBinaryExpression(parent2) && parent2.operatorToken.kind === 64 /* EqualsToken */)) { + } else if (parent2.parent && (getSingleVariableOfVariableStatement(parent2.parent) === node || isAssignmentExpression(parent2))) { return parent2.parent; } else if (parent2.parent && parent2.parent.parent && (getSingleVariableOfVariableStatement(parent2.parent.parent) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent2.parent.parent) === node || getSourceOfDefaultedAssignment(parent2.parent.parent))) { return parent2.parent.parent; @@ -15600,20 +15214,23 @@ ${lanes.join("\n")} function hasTypeArguments(node) { return !!node.typeArguments; } - function getAssignmentTargetKind(node) { + function getAssignmentTarget(node) { let parent2 = node.parent; while (true) { switch (parent2.kind) { case 226 /* BinaryExpression */: - const binaryOperator = parent2.operatorToken.kind; - return isAssignmentOperator(binaryOperator) && parent2.left === node ? binaryOperator === 64 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; + const binaryExpression = parent2; + const binaryOperator = binaryExpression.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && binaryExpression.left === node ? binaryExpression : void 0; case 224 /* PrefixUnaryExpression */: case 225 /* PostfixUnaryExpression */: - const unaryOperator = parent2.operator; - return unaryOperator === 46 /* PlusPlusToken */ || unaryOperator === 47 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + const unaryExpression = parent2; + const unaryOperator = unaryExpression.operator; + return unaryOperator === 46 /* PlusPlusToken */ || unaryOperator === 47 /* MinusMinusToken */ ? unaryExpression : void 0; case 249 /* ForInStatement */: case 250 /* ForOfStatement */: - return parent2.initializer === node ? 1 /* Definite */ : 0 /* None */; + const forInOrOfStatement = parent2; + return forInOrOfStatement.initializer === node ? forInOrOfStatement : void 0; case 217 /* ParenthesizedExpression */: case 209 /* ArrayLiteralExpression */: case 230 /* SpreadElement */: @@ -15625,24 +15242,53 @@ ${lanes.join("\n")} break; case 304 /* ShorthandPropertyAssignment */: if (parent2.name !== node) { - return 0 /* None */; + return void 0; } node = parent2.parent; break; case 303 /* PropertyAssignment */: if (parent2.name === node) { - return 0 /* None */; + return void 0; } node = parent2.parent; break; default: - return 0 /* None */; + return void 0; } parent2 = node.parent; } } + function getAssignmentTargetKind(node) { + const target = getAssignmentTarget(node); + if (!target) { + return 0 /* None */; + } + switch (target.kind) { + case 226 /* BinaryExpression */: + const binaryOperator = target.operatorToken.kind; + return binaryOperator === 64 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */; + case 224 /* PrefixUnaryExpression */: + case 225 /* PostfixUnaryExpression */: + return 2 /* Compound */; + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + return 1 /* Definite */; + } + } function isAssignmentTarget(node) { - return getAssignmentTargetKind(node) !== 0 /* None */; + return !!getAssignmentTarget(node); + } + function isCompoundLikeAssignment(assignment) { + const right = skipParentheses(assignment.right); + return right.kind === 226 /* BinaryExpression */ && isShiftOperatorOrHigher(right.operatorToken.kind); + } + function isInCompoundLikeAssignment(node) { + const target = getAssignmentTarget(node); + return !!target && isAssignmentExpression( + target, + /*excludeCompoundAssignment*/ + true + ) && isCompoundLikeAssignment(target); } function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { @@ -15900,7 +15546,7 @@ ${lanes.join("\n")} flags |= 1 /* Generator */; } case 219 /* ArrowFunction */: - if (hasSyntacticModifier(node, 512 /* Async */)) { + if (hasSyntacticModifier(node, 1024 /* Async */)) { flags |= 2 /* Async */; } break; @@ -15916,7 +15562,7 @@ ${lanes.join("\n")} case 218 /* FunctionExpression */: case 219 /* ArrowFunction */: case 174 /* MethodDeclaration */: - return node.body !== void 0 && node.asteriskToken === void 0 && hasSyntacticModifier(node, 512 /* Async */); + return node.body !== void 0 && node.asteriskToken === void 0 && hasSyntacticModifier(node, 1024 /* Async */); } return false; } @@ -15943,6 +15589,7 @@ ${lanes.join("\n")} case 81 /* PrivateIdentifier */: return name.escapedText; case 11 /* StringLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: case 9 /* NumericLiteral */: return escapeLeadingUnderscores(name.text); case 167 /* ComputedPropertyName */: @@ -16346,8 +15993,11 @@ ${lanes.join("\n")} function escapeTemplateSubstitution(str) { return str.replace(templateSubstitutionRegExp, "\\${"); } + function containsInvalidEscapeFlag(node) { + return !!((node.templateFlags || 0) & 2048 /* ContainsInvalidEscape */); + } function hasInvalidEscape(template) { - return template && !!(isNoSubstitutionTemplateLiteral(template) ? template.templateFlags : template.head.templateFlags || some(template.templateSpans, (span) => !!span.literal.templateFlags)); + return template && !!(isNoSubstitutionTemplateLiteral(template) ? containsInvalidEscapeFlag(template) : containsInvalidEscapeFlag(template.head) || some(template.templateSpans, (span) => containsInvalidEscapeFlag(span.literal))); } function encodeUtf16EscapeSequence(charCode) { const hexCharCode = charCode.toString(16).toUpperCase(); @@ -16398,7 +16048,7 @@ ${lanes.join("\n")} } function isIntrinsicJsxName(name) { const ch = name.charCodeAt(0); - return ch >= 97 /* a */ && ch <= 122 /* z */ || stringContains(name, "-"); + return ch >= 97 /* a */ && ch <= 122 /* z */ || name.includes("-"); } function getIndentString(level) { const singleLevel = indentStrings[1]; @@ -16410,12 +16060,9 @@ ${lanes.join("\n")} function getIndentSize() { return indentStrings[1].length; } - function isNightly() { - return stringContains(version, "-dev") || stringContains(version, "-insiders"); - } function createTextWriter(newLine) { var output; - var indent2; + var indent3; var lineStart; var lineCount; var linePos; @@ -16433,7 +16080,7 @@ ${lanes.join("\n")} function writeText(s) { if (s && s.length) { if (lineStart) { - s = getIndentString(indent2) + s; + s = getIndentString(indent3) + s; lineStart = false; } output += s; @@ -16452,7 +16099,7 @@ ${lanes.join("\n")} } function reset2() { output = ""; - indent2 = 0; + indent3 = 0; lineStart = true; lineCount = 0; linePos = 0; @@ -16489,15 +16136,15 @@ ${lanes.join("\n")} writeLiteral, writeLine, increaseIndent: () => { - indent2++; + indent3++; }, decreaseIndent: () => { - indent2--; + indent3--; }, - getIndent: () => indent2, + getIndent: () => indent3, getTextPos: () => output.length, getLine: () => lineCount, - getColumn: () => lineStart ? indent2 * getIndentSize() : output.length - linePos, + getColumn: () => lineStart ? indent3 * getIndentSize() : output.length - linePos, getText: () => output, isAtStartOfLine: () => lineStart, hasTrailingComment: () => hasTrailingComment, @@ -16601,7 +16248,7 @@ ${lanes.join("\n")} return void 0; } const specifier = getExternalModuleName(declaration); - if (specifier && isStringLiteralLike(specifier) && !pathIsRelative(specifier.text) && getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + if (specifier && isStringLiteralLike(specifier) && !pathIsRelative(specifier.text) && !getCanonicalAbsolutePath(host, file.path).includes(getCanonicalAbsolutePath(host, ensureTrailingDirectorySeparator(host.getCommonSourceDirectory())))) { return void 0; } return getResolvedExternalModuleName(host, file); @@ -16677,7 +16324,31 @@ ${lanes.join("\n")} } function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) { const options = host.getCompilerOptions(); - return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !host.isSourceFileFromExternalLibrary(sourceFile) && (forceDtsEmit || !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)); + if (options.noEmitForJsFiles && isSourceFileJS(sourceFile)) + return false; + if (sourceFile.isDeclarationFile) + return false; + if (host.isSourceFileFromExternalLibrary(sourceFile)) + return false; + if (forceDtsEmit) + return true; + if (host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)) + return false; + if (!isJsonSourceFile(sourceFile)) + return true; + if (host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) + return false; + if (outFile(options)) + return true; + if (!options.outDir) + return false; + if (options.rootDir || options.composite && options.configFilePath) { + const commonDir = getNormalizedAbsolutePath(getCommonSourceDirectory(options, () => [], host.getCurrentDirectory(), host.getCanonicalFileName), host.getCurrentDirectory()); + const outputPath = getSourceFilePathInNewDirWorker(sourceFile.fileName, options.outDir, host.getCurrentDirectory(), commonDir, host.getCanonicalFileName); + if (comparePaths(sourceFile.fileName, outputPath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */) + return false; + } + return true; } function getSourceFilePathInNewDir(fileName, host, newDirPath) { return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), (f) => host.getCanonicalFileName(f)); @@ -16689,9 +16360,16 @@ ${lanes.join("\n")} return combinePaths(newDirPath, sourceFilePath); } function writeFile(host, diagnostics, fileName, text, writeByteOrderMark, sourceFiles, data) { - host.writeFile(fileName, text, writeByteOrderMark, (hostErrorMessage) => { - diagnostics.add(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); - }, sourceFiles, data); + host.writeFile( + fileName, + text, + writeByteOrderMark, + (hostErrorMessage) => { + diagnostics.add(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }, + sourceFiles, + data + ); } function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) { if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { @@ -16946,7 +16624,7 @@ ${lanes.join("\n")} } function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { const end = Math.min(commentEnd, nextLineStart - 1); - const currentLineText = trimString(text.substring(pos, end)); + const currentLineText = text.substring(pos, end).trim(); if (currentLineText) { writer.writeComment(currentLineText); if (end !== commentEnd) { @@ -16983,25 +16661,25 @@ ${lanes.join("\n")} return isClassElement(node) && hasStaticModifier(node) || isClassStaticBlockDeclaration(node); } function hasStaticModifier(node) { - return hasSyntacticModifier(node, 32 /* Static */); + return hasSyntacticModifier(node, 256 /* Static */); } function hasOverrideModifier(node) { - return hasEffectiveModifier(node, 16384 /* Override */); + return hasEffectiveModifier(node, 16 /* Override */); } function hasAbstractModifier(node) { - return hasSyntacticModifier(node, 256 /* Abstract */); + return hasSyntacticModifier(node, 64 /* Abstract */); } function hasAmbientModifier(node) { - return hasSyntacticModifier(node, 2 /* Ambient */); + return hasSyntacticModifier(node, 128 /* Ambient */); } function hasAccessorModifier(node) { - return hasSyntacticModifier(node, 128 /* Accessor */); + return hasSyntacticModifier(node, 512 /* Accessor */); } function hasEffectiveReadonlyModifier(node) { - return hasEffectiveModifier(node, 64 /* Readonly */); + return hasEffectiveModifier(node, 8 /* Readonly */); } function hasDecorators(node) { - return hasSyntacticModifier(node, 131072 /* Decorator */); + return hasSyntacticModifier(node, 32768 /* Decorator */); } function getSelectedEffectiveModifierFlags(node, flags) { return getEffectiveModifierFlags(node) & flags; @@ -17016,10 +16694,13 @@ ${lanes.join("\n")} if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) { node.modifierFlagsCache = getSyntacticModifierFlagsNoCache(node) | 536870912 /* HasComputedFlags */; } - if (includeJSDoc && !(node.modifierFlagsCache & 4096 /* HasComputedJSDocModifiers */) && (alwaysIncludeJSDoc || isInJSFile(node)) && node.parent) { - node.modifierFlagsCache |= getJSDocModifierFlagsNoCache(node) | 4096 /* HasComputedJSDocModifiers */; + if (alwaysIncludeJSDoc || includeJSDoc && isInJSFile(node)) { + if (!(node.modifierFlagsCache & 268435456 /* HasComputedJSDocModifiers */) && node.parent) { + node.modifierFlagsCache |= getRawJSDocModifierFlagsNoCache(node) | 268435456 /* HasComputedJSDocModifiers */; + } + return selectEffectiveModifierFlags(node.modifierFlagsCache); } - return node.modifierFlagsCache & ~(536870912 /* HasComputedFlags */ | 4096 /* HasComputedJSDocModifiers */); + return selectSyntacticModifierFlags(node.modifierFlagsCache); } function getEffectiveModifierFlags(node) { return getModifierFlagsWorker( @@ -17044,33 +16725,42 @@ ${lanes.join("\n")} false ); } - function getJSDocModifierFlagsNoCache(node) { + function getRawJSDocModifierFlagsNoCache(node) { let flags = 0 /* None */; if (!!node.parent && !isParameter(node)) { if (isInJSFile(node)) { if (getJSDocPublicTagNoCache(node)) - flags |= 4 /* Public */; + flags |= 8388608 /* JSDocPublic */; if (getJSDocPrivateTagNoCache(node)) - flags |= 8 /* Private */; + flags |= 16777216 /* JSDocPrivate */; if (getJSDocProtectedTagNoCache(node)) - flags |= 16 /* Protected */; + flags |= 33554432 /* JSDocProtected */; if (getJSDocReadonlyTagNoCache(node)) - flags |= 64 /* Readonly */; + flags |= 67108864 /* JSDocReadonly */; if (getJSDocOverrideTagNoCache(node)) - flags |= 16384 /* Override */; + flags |= 134217728 /* JSDocOverride */; } if (getJSDocDeprecatedTagNoCache(node)) - flags |= 8192 /* Deprecated */; + flags |= 65536 /* Deprecated */; } return flags; } + function selectSyntacticModifierFlags(flags) { + return flags & 65535 /* SyntacticModifiers */; + } + function selectEffectiveModifierFlags(flags) { + return flags & 131071 /* NonCacheOnlyModifiers */ | (flags & 260046848 /* JSDocCacheOnlyModifiers */) >>> 23; + } + function getJSDocModifierFlagsNoCache(node) { + return selectEffectiveModifierFlags(getRawJSDocModifierFlagsNoCache(node)); + } function getEffectiveModifierFlagsNoCache(node) { return getSyntacticModifierFlagsNoCache(node) | getJSDocModifierFlagsNoCache(node); } function getSyntacticModifierFlagsNoCache(node) { let flags = canHaveModifiers(node) ? modifiersToFlags(node.modifiers) : 0 /* None */; if (node.flags & 8 /* NestedNamespace */ || node.kind === 80 /* Identifier */ && node.flags & 4096 /* IdentifierIsInJSDocNamespace */) { - flags |= 1 /* Export */; + flags |= 32 /* Export */; } return flags; } @@ -17086,37 +16776,37 @@ ${lanes.join("\n")} function modifierToFlag(token) { switch (token) { case 126 /* StaticKeyword */: - return 32 /* Static */; + return 256 /* Static */; case 125 /* PublicKeyword */: - return 4 /* Public */; + return 1 /* Public */; case 124 /* ProtectedKeyword */: - return 16 /* Protected */; + return 4 /* Protected */; case 123 /* PrivateKeyword */: - return 8 /* Private */; + return 2 /* Private */; case 128 /* AbstractKeyword */: - return 256 /* Abstract */; + return 64 /* Abstract */; case 129 /* AccessorKeyword */: - return 128 /* Accessor */; + return 512 /* Accessor */; case 95 /* ExportKeyword */: - return 1 /* Export */; + return 32 /* Export */; case 138 /* DeclareKeyword */: - return 2 /* Ambient */; + return 128 /* Ambient */; case 87 /* ConstKeyword */: - return 2048 /* Const */; + return 4096 /* Const */; case 90 /* DefaultKeyword */: - return 1024 /* Default */; + return 2048 /* Default */; case 134 /* AsyncKeyword */: - return 512 /* Async */; + return 1024 /* Async */; case 148 /* ReadonlyKeyword */: - return 64 /* Readonly */; + return 8 /* Readonly */; case 164 /* OverrideKeyword */: - return 16384 /* Override */; + return 16 /* Override */; case 103 /* InKeyword */: - return 32768 /* In */; + return 8192 /* In */; case 147 /* OutKeyword */: - return 65536 /* Out */; + return 16384 /* Out */; case 170 /* Decorator */: - return 131072 /* Decorator */; + return 32768 /* Decorator */; } return 0 /* None */; } @@ -17229,11 +16919,17 @@ ${lanes.join("\n")} 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; + return !!node.parent && (isPropertyAccessExpression(node.parent) && node.parent.name === node || isElementAccessExpression(node.parent) && node.parent.argumentExpression === 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; } + function isInstanceOfExpression(node) { + return isBinaryExpression(node) && node.operatorToken.kind === 104 /* InstanceOfKeyword */; + } + function isRightSideOfInstanceofExpression(node) { + return isInstanceOfExpression(node.parent) && node === node.parent.right; + } function isEmptyObjectLiteral(expression) { return expression.kind === 210 /* ObjectLiteralExpression */ && expression.properties.length === 0; } @@ -17250,7 +16946,7 @@ ${lanes.join("\n")} return void 0; } function isExportDefaultSymbol(symbol) { - return symbol && length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], 1024 /* Default */); + return symbol && length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], 2048 /* Default */); } function tryExtractTSExtension(fileName) { return find(supportedTSExtensionsForExtractExtension, (extension) => fileExtensionIs(fileName, extension)); @@ -17530,16 +17226,16 @@ ${lanes.join("\n")} if (s.valueDeclaration) { const declaration = isWrite && s.declarations && find(s.declarations, isSetAccessorDeclaration) || s.flags & 32768 /* GetAccessor */ && find(s.declarations, isGetAccessorDeclaration) || s.valueDeclaration; const flags = getCombinedModifierFlags(declaration); - return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~7 /* AccessibilityModifier */; } if (getCheckFlags(s) & 6 /* Synthetic */) { const checkFlags = s.links.checkFlags; - const accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ : checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ : 16 /* Protected */; - const staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0; + const accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 2 /* Private */ : checkFlags & 256 /* ContainsPublic */ ? 1 /* Public */ : 4 /* Protected */; + const staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 256 /* Static */ : 0; return accessModifier | staticModifier; } if (s.flags & 4194304 /* Prototype */) { - return 4 /* Public */ | 32 /* Static */; + return 1 /* Public */ | 256 /* Static */; } return 0; } @@ -17638,7 +17334,7 @@ ${lanes.join("\n")} function isAbstractConstructorSymbol(symbol) { if (symbol.flags & 32 /* Class */) { const declaration = getClassLikeDeclarationOfSymbol(symbol); - return !!declaration && hasSyntacticModifier(declaration, 256 /* Abstract */); + return !!declaration && hasSyntacticModifier(declaration, 64 /* Abstract */); } return false; } @@ -17647,7 +17343,7 @@ ${lanes.join("\n")} return (_a = symbol.declarations) == null ? void 0 : _a.find(isClassLike); } function getObjectFlags(type) { - return type.flags & 138117121 /* ObjectFlagsType */ ? type.objectFlags : 0; + return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0; } function forSomeAncestorDirectory(directory, callback) { return !!forEachAncestorDirectory(directory, (d) => callback(d) ? true : void 0); @@ -17660,21 +17356,17 @@ ${lanes.join("\n")} } function getLastChild(node) { let lastChild; - forEachChild( - node, - (child) => { - if (nodeIsPresent(child)) - lastChild = child; - }, - (children) => { - for (let i = children.length - 1; i >= 0; i--) { - if (nodeIsPresent(children[i])) { - lastChild = children[i]; - break; - } + forEachChild(node, (child) => { + if (nodeIsPresent(child)) + lastChild = child; + }, (children) => { + for (let i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; } } - ); + }); return lastChild; } function addToSeen(seen, key, value = true) { @@ -17852,8 +17544,8 @@ ${lanes.join("\n")} Object.assign(objectAllocator, alloc); forEach(objectAllocatorPatchers, (fn) => fn(objectAllocator)); } - function formatStringFromArgs(text, args, baseIndex = 0) { - return text.replace(/{(\d+)}/g, (_match, index) => "" + Debug.checkDefined(args[+index + baseIndex])); + function formatStringFromArgs(text, args) { + return text.replace(/{(\d+)}/g, (_match, index) => "" + Debug.checkDefined(args[+index])); } function setLocalizedDiagnosticMessages(messages) { localizedDiagnosticMessages = messages; @@ -17866,16 +17558,14 @@ ${lanes.join("\n")} function getLocaleSpecificMessage(message) { return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message; } - function createDetachedDiagnostic(fileName, start, length2, message) { - assertDiagnosticLocation( - /*file*/ - void 0, - start, - length2 - ); + function createDetachedDiagnostic(fileName, sourceText, start, length2, message, ...args) { + if (start + length2 > sourceText.length) { + length2 = sourceText.length - start; + } + assertDiagnosticLocation(sourceText, start, length2); let text = getLocaleSpecificMessage(message); - if (arguments.length > 4) { - text = formatStringFromArgs(text, arguments, 4); + if (some(args)) { + text = formatStringFromArgs(text, args); } return { file: void 0, @@ -17927,11 +17617,11 @@ ${lanes.join("\n")} } return diagnosticsWithLocation; } - function createFileDiagnostic(file, start, length2, message) { - assertDiagnosticLocation(file, start, length2); + function createFileDiagnostic(file, start, length2, message, ...args) { + assertDiagnosticLocation(file.text, start, length2); let text = getLocaleSpecificMessage(message); - if (arguments.length > 4) { - text = formatStringFromArgs(text, arguments, 4); + if (some(args)) { + text = formatStringFromArgs(text, args); } return { file, @@ -17944,17 +17634,17 @@ ${lanes.join("\n")} reportsDeprecated: message.reportsDeprecated }; } - function formatMessage(_dummy, message) { + function formatMessage(message, ...args) { let text = getLocaleSpecificMessage(message); - if (arguments.length > 2) { - text = formatStringFromArgs(text, arguments, 2); + if (some(args)) { + text = formatStringFromArgs(text, args); } return text; } - function createCompilerDiagnostic(message) { + function createCompilerDiagnostic(message, ...args) { let text = getLocaleSpecificMessage(message); - if (arguments.length > 1) { - text = formatStringFromArgs(text, arguments, 1); + if (some(args)) { + text = formatStringFromArgs(text, args); } return { file: void 0, @@ -17978,10 +17668,10 @@ ${lanes.join("\n")} relatedInformation }; } - function chainDiagnosticMessages(details, message) { + function chainDiagnosticMessages(details, message, ...args) { let text = getLocaleSpecificMessage(message); - if (arguments.length > 2) { - text = formatStringFromArgs(text, arguments, 2); + if (some(args)) { + text = formatStringFromArgs(text, args); } return { messageText: text, @@ -18242,7 +17932,7 @@ ${lanes.join("\n")} return optionsHaveChanges(oldOptions, newOptions, affectsDeclarationPathOptionDeclarations); } function getCompilerOptionValue(options, option) { - return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + return option.strictFlag ? getStrictOptionValue(options, option.name) : option.allowJsFlag ? getAllowJSCompilerOption(options) : options[option.name]; } function getJSXTransformEnabled(options) { const jsx = options.jsx; @@ -18284,19 +17974,16 @@ ${lanes.join("\n")} if (!containsIgnoredPath(symlinkPath)) { symlinkPath = ensureTrailingDirectorySeparator(symlinkPath); if (real !== false && !(symlinkedDirectories == null ? void 0 : symlinkedDirectories.has(symlinkPath))) { - (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = createMultiMap())).add(ensureTrailingDirectorySeparator(real.realPath), symlink); + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = createMultiMap())).add(real.realPath, symlink); } (symlinkedDirectories || (symlinkedDirectories = /* @__PURE__ */ new Map())).set(symlinkPath, real); } }, - setSymlinksFromResolutions(files, typeReferenceDirectives) { - var _a, _b; + setSymlinksFromResolutions(forEachResolvedModule, forEachResolvedTypeReferenceDirective, typeReferenceDirectives) { Debug.assert(!hasProcessedResolutions); hasProcessedResolutions = true; - for (const file of files) { - (_a = file.resolvedModules) == null ? void 0 : _a.forEach((resolution) => processResolution(this, resolution.resolvedModule)); - (_b = file.resolvedTypeReferenceDirectiveNames) == null ? void 0 : _b.forEach((resolution) => processResolution(this, resolution.resolvedTypeReferenceDirective)); - } + forEachResolvedModule((resolution) => processResolution(this, resolution.resolvedModule)); + forEachResolvedTypeReferenceDirective((resolution) => processResolution(this, resolution.resolvedTypeReferenceDirective)); typeReferenceDirectives.forEach((resolution) => processResolution(this, resolution.resolvedTypeReferenceDirective)); }, hasProcessedResolutions: () => hasProcessedResolutions @@ -18310,7 +17997,10 @@ ${lanes.join("\n")} if (commonResolved && commonOriginal) { cache.setSymlinkedDirectory( commonOriginal, - { real: commonResolved, realPath: toPath(commonResolved, cwd, getCanonicalFileName) } + { + real: ensureTrailingDirectorySeparator(commonResolved), + realPath: ensureTrailingDirectorySeparator(toPath(commonResolved, cwd, getCanonicalFileName)) + } ); } } @@ -18540,7 +18230,7 @@ ${lanes.join("\n")} const flatBuiltins = flatten(builtins); const extensions = [ ...builtins, - ...mapDefined(extraFileExtensions, (x) => x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) && flatBuiltins.indexOf(x.extension) === -1 ? [x.extension] : void 0) + ...mapDefined(extraFileExtensions, (x) => x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) && !flatBuiltins.includes(x.extension) ? [x.extension] : void 0) ]; return extensions; } @@ -18864,7 +18554,7 @@ ${lanes.join("\n")} if (node.kind !== 167 /* ComputedPropertyName */) { return false; } - if (hasSyntacticModifier(node.parent, 256 /* Abstract */)) { + if (hasSyntacticModifier(node.parent, 64 /* Abstract */)) { return true; } const containerKind = node.parent.parent.kind; @@ -18990,7 +18680,7 @@ ${lanes.join("\n")} } } function containsIgnoredPath(path) { - return some(ignoredPaths, (p) => stringContains(path, p)); + return some(ignoredPaths, (p) => path.includes(p)); } function getContainingNodeArray(node) { if (!node.parent) @@ -19090,8 +18780,9 @@ ${lanes.join("\n")} function isNumericLiteralName(name) { return (+name).toString() === name; } - function createPropertyNameNodeForIdentifierOrLiteral(name, target, singleQuote, stringNamed) { - return isIdentifierText(name, target) ? factory.createIdentifier(name) : !stringNamed && isNumericLiteralName(name) && +name >= 0 ? factory.createNumericLiteral(+name) : factory.createStringLiteral(name, !!singleQuote); + function createPropertyNameNodeForIdentifierOrLiteral(name, target, singleQuote, stringNamed, isMethod) { + const isMethodNamedNew = isMethod && name === "new"; + return !isMethodNamedNew && isIdentifierText(name, target) ? factory.createIdentifier(name) : !stringNamed && !isMethodNamedNew && isNumericLiteralName(name) && +name >= 0 ? factory.createNumericLiteral(+name) : factory.createStringLiteral(name, !!singleQuote); } function isThisTypeParameter(type) { return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType); @@ -19251,7 +18942,16 @@ ${lanes.join("\n")} } 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; + function isExpandoPropertyDeclaration(declaration) { + return !!declaration && (isPropertyAccessExpression(declaration) || isElementAccessExpression(declaration) || isBinaryExpression(declaration)); + } + function hasResolutionModeOverride(node) { + if (node === void 0) { + return false; + } + return !!getResolutionModeOverride(node.attributes); + } + var resolvingEmptyArray, externalHelpersModuleNameText, defaultMaximumTruncationLength, noTruncationMaximumTruncationLength, stringWriter, getScriptTargetFeatures, 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"() { "use strict"; @@ -19261,6 +18961,402 @@ ${lanes.join("\n")} defaultMaximumTruncationLength = 160; noTruncationMaximumTruncationLength = 1e6; stringWriter = createSingleLineStringWriter(); + getScriptTargetFeatures = /* @__PURE__ */ memoize( + () => new Map(Object.entries({ + Array: new Map(Object.entries({ + es2015: [ + "find", + "findIndex", + "fill", + "copyWithin", + "entries", + "keys", + "values" + ], + es2016: [ + "includes" + ], + es2019: [ + "flat", + "flatMap" + ], + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast" + ] + })), + Iterator: new Map(Object.entries({ + es2015: emptyArray + })), + AsyncIterator: new Map(Object.entries({ + es2015: emptyArray + })), + Atomics: new Map(Object.entries({ + es2017: emptyArray + })), + SharedArrayBuffer: new Map(Object.entries({ + es2017: emptyArray + })), + AsyncIterable: new Map(Object.entries({ + es2018: emptyArray + })), + AsyncIterableIterator: new Map(Object.entries({ + es2018: emptyArray + })), + AsyncGenerator: new Map(Object.entries({ + es2018: emptyArray + })), + AsyncGeneratorFunction: new Map(Object.entries({ + es2018: emptyArray + })), + RegExp: new Map(Object.entries({ + es2015: [ + "flags", + "sticky", + "unicode" + ], + es2018: [ + "dotAll" + ] + })), + Reflect: new Map(Object.entries({ + es2015: [ + "apply", + "construct", + "defineProperty", + "deleteProperty", + "get", + "getOwnPropertyDescriptor", + "getPrototypeOf", + "has", + "isExtensible", + "ownKeys", + "preventExtensions", + "set", + "setPrototypeOf" + ] + })), + ArrayConstructor: new Map(Object.entries({ + es2015: [ + "from", + "of" + ] + })), + ObjectConstructor: new Map(Object.entries({ + es2015: [ + "assign", + "getOwnPropertySymbols", + "keys", + "is", + "setPrototypeOf" + ], + es2017: [ + "values", + "entries", + "getOwnPropertyDescriptors" + ], + es2019: [ + "fromEntries" + ], + es2022: [ + "hasOwn" + ] + })), + NumberConstructor: new Map(Object.entries({ + es2015: [ + "isFinite", + "isInteger", + "isNaN", + "isSafeInteger", + "parseFloat", + "parseInt" + ] + })), + Math: new Map(Object.entries({ + es2015: [ + "clz32", + "imul", + "sign", + "log10", + "log2", + "log1p", + "expm1", + "cosh", + "sinh", + "tanh", + "acosh", + "asinh", + "atanh", + "hypot", + "trunc", + "fround", + "cbrt" + ] + })), + Map: new Map(Object.entries({ + es2015: [ + "entries", + "keys", + "values" + ] + })), + Set: new Map(Object.entries({ + es2015: [ + "entries", + "keys", + "values" + ] + })), + PromiseConstructor: new Map(Object.entries({ + es2015: [ + "all", + "race", + "reject", + "resolve" + ], + es2020: [ + "allSettled" + ], + es2021: [ + "any" + ] + })), + Symbol: new Map(Object.entries({ + es2015: [ + "for", + "keyFor" + ], + es2019: [ + "description" + ] + })), + WeakMap: new Map(Object.entries({ + es2015: [ + "entries", + "keys", + "values" + ] + })), + WeakSet: new Map(Object.entries({ + es2015: [ + "entries", + "keys", + "values" + ] + })), + String: new Map(Object.entries({ + es2015: [ + "codePointAt", + "includes", + "endsWith", + "normalize", + "repeat", + "startsWith", + "anchor", + "big", + "blink", + "bold", + "fixed", + "fontcolor", + "fontsize", + "italics", + "link", + "small", + "strike", + "sub", + "sup" + ], + es2017: [ + "padStart", + "padEnd" + ], + es2019: [ + "trimStart", + "trimEnd", + "trimLeft", + "trimRight" + ], + es2020: [ + "matchAll" + ], + es2021: [ + "replaceAll" + ], + es2022: [ + "at" + ] + })), + StringConstructor: new Map(Object.entries({ + es2015: [ + "fromCodePoint", + "raw" + ] + })), + DateTimeFormat: new Map(Object.entries({ + es2017: [ + "formatToParts" + ] + })), + Promise: new Map(Object.entries({ + es2015: emptyArray, + es2018: [ + "finally" + ] + })), + RegExpMatchArray: new Map(Object.entries({ + es2018: [ + "groups" + ] + })), + RegExpExecArray: new Map(Object.entries({ + es2018: [ + "groups" + ] + })), + Intl: new Map(Object.entries({ + es2018: [ + "PluralRules" + ] + })), + NumberFormat: new Map(Object.entries({ + es2018: [ + "formatToParts" + ] + })), + SymbolConstructor: new Map(Object.entries({ + es2020: [ + "matchAll" + ] + })), + DataView: new Map(Object.entries({ + es2020: [ + "setBigInt64", + "setBigUint64", + "getBigInt64", + "getBigUint64" + ] + })), + BigInt: new Map(Object.entries({ + es2020: emptyArray + })), + RelativeTimeFormat: new Map(Object.entries({ + es2020: [ + "format", + "formatToParts", + "resolvedOptions" + ] + })), + Int8Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast" + ] + })), + Uint8Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast" + ] + })), + Uint8ClampedArray: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast" + ] + })), + Int16Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast" + ] + })), + Uint16Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast" + ] + })), + Int32Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast" + ] + })), + Uint32Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast" + ] + })), + Float32Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast" + ] + })), + Float64Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast" + ] + })), + BigInt64Array: new Map(Object.entries({ + es2020: emptyArray, + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast" + ] + })), + BigUint64Array: new Map(Object.entries({ + es2020: emptyArray, + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast" + ] + })), + Error: new Map(Object.entries({ + es2022: [ + "cause" + ] + })) + })) + ); GetLiteralTextFlags = /* @__PURE__ */ ((GetLiteralTextFlags2) => { GetLiteralTextFlags2[GetLiteralTextFlags2["None"] = 0] = "None"; GetLiteralTextFlags2[GetLiteralTextFlags2["NeverAsciiEscape"] = 1] = "NeverAsciiEscape"; @@ -20324,6 +20420,10 @@ ${lanes.join("\n")} updateAssertEntry, createImportTypeAssertionContainer, updateImportTypeAssertionContainer, + createImportAttributes, + updateImportAttributes, + createImportAttribute, + updateImportAttribute, createNamespaceImport, updateNamespaceImport, createNamespaceExport, @@ -20700,8 +20800,9 @@ ${lanes.join("\n")} ensureUseStrict, liftToBlock, mergeLexicalEnvironment, - updateModifiers, - updateModifierLike + replaceModifiers, + replaceDecoratorsAndModifiers, + replacePropertyName }; forEach(nodeFactoryPatchers, (fn) => fn(factory2)); return factory2; @@ -21034,35 +21135,35 @@ ${lanes.join("\n")} } function createModifiersFromModifierFlags(flags2) { const result = []; - if (flags2 & 1 /* Export */) + if (flags2 & 32 /* Export */) result.push(createModifier(95 /* ExportKeyword */)); - if (flags2 & 2 /* Ambient */) + if (flags2 & 128 /* Ambient */) result.push(createModifier(138 /* DeclareKeyword */)); - if (flags2 & 1024 /* Default */) + if (flags2 & 2048 /* Default */) result.push(createModifier(90 /* DefaultKeyword */)); - if (flags2 & 2048 /* Const */) + if (flags2 & 4096 /* Const */) result.push(createModifier(87 /* ConstKeyword */)); - if (flags2 & 4 /* Public */) + if (flags2 & 1 /* Public */) result.push(createModifier(125 /* PublicKeyword */)); - if (flags2 & 8 /* Private */) + if (flags2 & 2 /* Private */) result.push(createModifier(123 /* PrivateKeyword */)); - if (flags2 & 16 /* Protected */) + if (flags2 & 4 /* Protected */) result.push(createModifier(124 /* ProtectedKeyword */)); - if (flags2 & 256 /* Abstract */) + if (flags2 & 64 /* Abstract */) result.push(createModifier(128 /* AbstractKeyword */)); - if (flags2 & 32 /* Static */) + if (flags2 & 256 /* Static */) result.push(createModifier(126 /* StaticKeyword */)); - if (flags2 & 16384 /* Override */) + if (flags2 & 16 /* Override */) result.push(createModifier(164 /* OverrideKeyword */)); - if (flags2 & 64 /* Readonly */) + if (flags2 & 8 /* Readonly */) result.push(createModifier(148 /* ReadonlyKeyword */)); - if (flags2 & 128 /* Accessor */) + if (flags2 & 512 /* Accessor */) result.push(createModifier(129 /* AccessorKeyword */)); - if (flags2 & 512 /* Async */) + if (flags2 & 1024 /* Async */) result.push(createModifier(134 /* AsyncKeyword */)); - if (flags2 & 32768 /* In */) + if (flags2 & 8192 /* In */) result.push(createModifier(103 /* InKeyword */)); - if (flags2 & 65536 /* Out */) + if (flags2 & 16384 /* Out */) result.push(createModifier(147 /* OutKeyword */)); return result.length ? result : void 0; } @@ -21111,7 +21212,7 @@ ${lanes.join("\n")} if (isThisIdentifier(node.name)) { node.transformFlags = 1 /* ContainsTypeScript */; } else { - node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.dotDotDotToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.initializer) | (node.questionToken ?? node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | (node.dotDotDotToken ?? node.initializer ? 1024 /* ContainsES2015 */ : 0 /* None */) | (modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */ ? 8192 /* ContainsTypeScriptClassSyntax */ : 0 /* None */); + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.dotDotDotToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.initializer) | (node.questionToken ?? node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | (node.dotDotDotToken ?? node.initializer ? 1024 /* ContainsES2015 */ : 0 /* None */) | (modifiersToFlags(node.modifiers) & 31 /* ParameterPropertyModifier */ ? 8192 /* ContainsTypeScriptClassSyntax */ : 0 /* None */); } node.jsDoc = void 0; return node; @@ -21160,8 +21261,8 @@ ${lanes.join("\n")} node.exclamationToken = questionOrExclamationToken && isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : void 0; node.type = type; node.initializer = asInitializer(initializer); - const isAmbient = node.flags & 33554432 /* Ambient */ || modifiersToFlags(node.modifiers) & 2 /* Ambient */; - node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (isAmbient || node.questionToken || node.exclamationToken || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | (isComputedPropertyName(node.name) || modifiersToFlags(node.modifiers) & 32 /* Static */ && node.initializer ? 8192 /* ContainsTypeScriptClassSyntax */ : 0 /* None */) | 16777216 /* ContainsClassFields */; + const isAmbient = node.flags & 33554432 /* Ambient */ || modifiersToFlags(node.modifiers) & 128 /* Ambient */; + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (isAmbient || node.questionToken || node.exclamationToken || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | (isComputedPropertyName(node.name) || modifiersToFlags(node.modifiers) & 256 /* Static */ && node.initializer ? 8192 /* ContainsTypeScriptClassSyntax */ : 0 /* None */) | 16777216 /* ContainsClassFields */; node.jsDoc = void 0; return node; } @@ -21200,7 +21301,7 @@ ${lanes.join("\n")} if (!node.body) { node.transformFlags = 1 /* ContainsTypeScript */; } else { - const isAsync = modifiersToFlags(node.modifiers) & 512 /* Async */; + const isAsync = modifiersToFlags(node.modifiers) & 1024 /* Async */; const isGenerator = !!node.asteriskToken; const isAsyncGenerator = isAsync && isGenerator; node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (isAsyncGenerator ? 128 /* ContainsES2018 */ : isAsync ? 256 /* ContainsES2017 */ : isGenerator ? 2048 /* ContainsGenerator */ : 0 /* None */) | (node.questionToken || node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | 1024 /* ContainsES2015 */; @@ -21590,18 +21691,21 @@ ${lanes.join("\n")} function updateTemplateLiteralType(node, head, templateSpans) { return node.head !== head || node.templateSpans !== templateSpans ? update(createTemplateLiteralType(head, templateSpans), node) : node; } - function createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf = false) { + function createImportTypeNode(argument, attributes, qualifier, typeArguments, isTypeOf = false) { const node = createBaseNode(205 /* ImportType */); node.argument = argument; - node.assertions = assertions; + node.attributes = attributes; + if (node.assertions && node.assertions.assertClause && node.attributes) { + node.assertions.assertClause = node.attributes; + } node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.isTypeOf = isTypeOf; node.transformFlags = 1 /* ContainsTypeScript */; return node; } - function updateImportTypeNode(node, argument, assertions, qualifier, typeArguments, isTypeOf = node.isTypeOf) { - return node.argument !== argument || node.assertions !== assertions || node.qualifier !== qualifier || node.typeArguments !== typeArguments || node.isTypeOf !== isTypeOf ? update(createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf), node) : node; + function updateImportTypeNode(node, argument, attributes, qualifier, typeArguments, isTypeOf = node.isTypeOf) { + return node.argument !== argument || node.attributes !== attributes || node.qualifier !== qualifier || node.typeArguments !== typeArguments || node.isTypeOf !== isTypeOf ? update(createImportTypeNode(argument, attributes, qualifier, typeArguments, isTypeOf), node) : node; } function createParenthesizedType(type) { const node = createBaseNode(196 /* ParenthesizedType */); @@ -21940,7 +22044,7 @@ ${lanes.join("\n")} node.parameters = createNodeArray(parameters); node.type = type; node.body = body; - const isAsync = modifiersToFlags(node.modifiers) & 512 /* Async */; + const isAsync = modifiersToFlags(node.modifiers) & 1024 /* Async */; const isGenerator = !!node.asteriskToken; const isAsyncGenerator = isAsync && isGenerator; node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (isAsyncGenerator ? 128 /* ContainsES2018 */ : isAsync ? 256 /* ContainsES2017 */ : isGenerator ? 2048 /* ContainsGenerator */ : 0 /* None */) | (node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | 4194304 /* ContainsHoistedDeclarationOrCompletion */; @@ -21964,7 +22068,7 @@ ${lanes.join("\n")} node.type = type; node.equalsGreaterThanToken = equalsGreaterThanToken ?? createToken(39 /* EqualsGreaterThanToken */); node.body = parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body); - const isAsync = modifiersToFlags(node.modifiers) & 512 /* Async */; + const isAsync = modifiersToFlags(node.modifiers) & 1024 /* Async */; node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.equalsGreaterThanToken) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | (isAsync ? 256 /* ContainsES2017 */ | 16384 /* ContainsLexicalThis */ : 0 /* None */) | 1024 /* ContainsES2015 */; node.typeArguments = void 0; node.jsDoc = void 0; @@ -22316,7 +22420,7 @@ ${lanes.join("\n")} node.modifiers = asNodeArray(modifiers); node.declarationList = isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.declarationList); - if (modifiersToFlags(node.modifiers) & 2 /* Ambient */) { + if (modifiersToFlags(node.modifiers) & 128 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; } node.jsDoc = void 0; @@ -22566,10 +22670,10 @@ ${lanes.join("\n")} node.parameters = createNodeArray(parameters); node.type = type; node.body = body; - if (!node.body || modifiersToFlags(node.modifiers) & 2 /* Ambient */) { + if (!node.body || modifiersToFlags(node.modifiers) & 128 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; } else { - const isAsync = modifiersToFlags(node.modifiers) & 512 /* Async */; + const isAsync = modifiersToFlags(node.modifiers) & 1024 /* Async */; const isGenerator = !!node.asteriskToken; const isAsyncGenerator = isAsync && isGenerator; node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (isAsyncGenerator ? 128 /* ContainsES2018 */ : isAsync ? 256 /* ContainsES2017 */ : isGenerator ? 2048 /* ContainsGenerator */ : 0 /* None */) | (node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | 4194304 /* ContainsHoistedDeclarationOrCompletion */; @@ -22600,7 +22704,7 @@ ${lanes.join("\n")} node.typeParameters = asNodeArray(typeParameters); node.heritageClauses = asNodeArray(heritageClauses); node.members = createNodeArray(members); - if (modifiersToFlags(node.modifiers) & 2 /* Ambient */) { + if (modifiersToFlags(node.modifiers) & 128 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; } else { node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.heritageClauses) | propagateChildrenFlags(node.members) | (node.typeParameters ? 1 /* ContainsTypeScript */ : 0 /* None */) | 1024 /* ContainsES2015 */; @@ -22662,7 +22766,7 @@ ${lanes.join("\n")} node.flags |= flags2 & (32 /* Namespace */ | 8 /* NestedNamespace */ | 2048 /* GlobalAugmentation */); node.name = name; node.body = body; - if (modifiersToFlags(node.modifiers) & 2 /* Ambient */) { + if (modifiersToFlags(node.modifiers) & 128 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; } else { node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.name) | propagateChildFlags(node.body) | 1 /* ContainsTypeScript */; @@ -22731,19 +22835,19 @@ ${lanes.join("\n")} function updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference) { return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.name !== name || node.moduleReference !== moduleReference ? update(createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node) : node; } - function createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause) { + function createImportDeclaration(modifiers, importClause, moduleSpecifier, attributes) { const node = createBaseNode(272 /* ImportDeclaration */); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; - node.assertClause = assertClause; + node.attributes = node.assertClause = attributes; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; node.jsDoc = void 0; return node; } - function updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause) { - return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause ? update(createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause), node) : node; + function updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, attributes) { + return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes ? update(createImportDeclaration(modifiers, importClause, moduleSpecifier, attributes), node) : node; } function createImportClause(isTypeOnly, name, namedBindings) { const node = createBaseDeclaration(273 /* ImportClause */); @@ -22764,6 +22868,7 @@ ${lanes.join("\n")} const node = createBaseNode(300 /* AssertClause */); node.elements = createNodeArray(elements); node.multiLine = multiLine; + node.token = 132 /* AssertKeyword */; node.transformFlags |= 4 /* ContainsESNext */; return node; } @@ -22789,6 +22894,27 @@ ${lanes.join("\n")} function updateImportTypeAssertionContainer(node, clause, multiLine) { return node.assertClause !== clause || node.multiLine !== multiLine ? update(createImportTypeAssertionContainer(clause, multiLine), node) : node; } + function createImportAttributes(elements, multiLine, token) { + const node = createBaseNode(300 /* ImportAttributes */); + node.token = token ?? 118 /* WithKeyword */; + node.elements = createNodeArray(elements); + node.multiLine = multiLine; + node.transformFlags |= 4 /* ContainsESNext */; + return node; + } + function updateImportAttributes(node, elements, multiLine) { + return node.elements !== elements || node.multiLine !== multiLine ? update(createImportAttributes(elements, multiLine, node.token), node) : node; + } + function createImportAttribute(name, value) { + const node = createBaseNode(301 /* ImportAttribute */); + node.name = name; + node.value = value; + node.transformFlags |= 4 /* ContainsESNext */; + return node; + } + function updateImportAttribute(node, name, value) { + return node.name !== name || node.value !== value ? update(createImportAttribute(name, value), node) : node; + } function createNamespaceImport(name) { const node = createBaseDeclaration(274 /* NamespaceImport */); node.name = name; @@ -22849,20 +22975,20 @@ ${lanes.join("\n")} function updateExportAssignment(node, modifiers, expression) { return node.modifiers !== modifiers || node.expression !== expression ? update(createExportAssignment2(modifiers, node.isExportEquals, expression), node) : node; } - function createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + function createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes) { const node = createBaseDeclaration(278 /* ExportDeclaration */); node.modifiers = asNodeArray(modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; - node.assertClause = assertClause; + node.attributes = node.assertClause = attributes; node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; node.jsDoc = void 0; return node; } - function updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause ? finishUpdateExportDeclaration(createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) : node; + function updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes ? finishUpdateExportDeclaration(createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes), node) : node; } function finishUpdateExportDeclaration(updated, original) { if (updated !== original) { @@ -23460,7 +23586,6 @@ ${lanes.join("\n")} node.imports = void 0; node.moduleAugmentations = void 0; node.ambientModuleNames = void 0; - node.resolvedModules = void 0; node.classifiableNames = void 0; node.impliedNodeFormat = void 0; return node; @@ -24072,7 +24197,7 @@ ${lanes.join("\n")} return qualifiedName; } function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { - if (ns && hasSyntacticModifier(node, 1 /* Export */)) { + if (ns && hasSyntacticModifier(node, 32 /* Export */)) { return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); } return getExportName(node, allowComments, allowSourceMaps); @@ -24183,18 +24308,36 @@ ${lanes.join("\n")} } return statements; } - function updateModifiers(node, modifiers) { + function replaceModifiers(node, modifiers) { let modifierArray; if (typeof modifiers === "number") { modifierArray = createModifiersFromModifierFlags(modifiers); } else { modifierArray = modifiers; } - return isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : isPropertyDeclaration(node) ? updatePropertyDeclaration2(node, modifierArray, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) : isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : Debug.assertNever(node); + return isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : isPropertyDeclaration(node) ? updatePropertyDeclaration2(node, modifierArray, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) : isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.attributes) : isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.attributes) : Debug.assertNever(node); } - function updateModifierLike(node, modifierArray) { + function replaceDecoratorsAndModifiers(node, modifierArray) { return isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isPropertyDeclaration(node) ? updatePropertyDeclaration2(node, modifierArray, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) : isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : Debug.assertNever(node); } + function replacePropertyName(node, name) { + switch (node.kind) { + case 177 /* GetAccessor */: + return updateGetAccessorDeclaration(node, node.modifiers, name, node.parameters, node.type, node.body); + case 178 /* SetAccessor */: + return updateSetAccessorDeclaration(node, node.modifiers, name, node.parameters, node.body); + case 174 /* MethodDeclaration */: + return updateMethodDeclaration(node, node.modifiers, node.asteriskToken, name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body); + case 173 /* MethodSignature */: + return updateMethodSignature(node, node.modifiers, name, node.questionToken, node.typeParameters, node.parameters, node.type); + case 172 /* PropertyDeclaration */: + return updatePropertyDeclaration2(node, node.modifiers, name, node.questionToken ?? node.exclamationToken, node.type, node.initializer); + case 171 /* PropertySignature */: + return updatePropertySignature(node, node.modifiers, name, node.questionToken, node.type); + case 303 /* PropertyAssignment */: + return updatePropertyAssignment(node, name, node.initializer); + } + } function asNodeArray(array) { return array ? createNodeArray(array) : void 0; } @@ -25740,17 +25883,18 @@ ${lanes.join("\n")} scoped: false, dependencies: [awaitHelper], text: ` - var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - };` + var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + };` }; asyncDelegator = { name: "typescript:asyncDelegator", @@ -26566,6 +26710,12 @@ ${lanes.join("\n")} function isAssertEntry(node) { return node.kind === 301 /* AssertEntry */; } + function isImportAttributes(node) { + return node.kind === 300 /* ImportAttributes */; + } + function isImportAttribute(node) { + return node.kind === 301 /* ImportAttribute */; + } function isNamespaceImport(node) { return node.kind === 274 /* NamespaceImport */; } @@ -27257,21 +27407,18 @@ ${lanes.join("\n")} if (some(helperNames)) { helperNames.sort(compareStringsCaseSensitive); namedBindings = nodeFactory.createNamedImports( - map( - helperNames, - (name) => isFileLevelUniqueName(sourceFile, name) ? nodeFactory.createImportSpecifier( - /*isTypeOnly*/ - false, - /*propertyName*/ - void 0, - nodeFactory.createIdentifier(name) - ) : nodeFactory.createImportSpecifier( - /*isTypeOnly*/ - false, - nodeFactory.createIdentifier(name), - helperFactory.getUnscopedHelperName(name) - ) - ) + map(helperNames, (name) => isFileLevelUniqueName(sourceFile, name) ? nodeFactory.createImportSpecifier( + /*isTypeOnly*/ + false, + /*propertyName*/ + void 0, + nodeFactory.createIdentifier(name) + ) : nodeFactory.createImportSpecifier( + /*isTypeOnly*/ + false, + nodeFactory.createIdentifier(name), + helperFactory.getUnscopedHelperName(name) + )) ); const parseNode = getOriginalNode(sourceFile, isSourceFile); const emitNode = getOrCreateEmitNode(parseNode); @@ -27296,7 +27443,7 @@ ${lanes.join("\n")} namedBindings ), nodeFactory.createStringLiteral(externalHelpersModuleNameText), - /*assertClause*/ + /*attributes*/ void 0 ); addInternalEmitFlags(externalHelpersImportDeclaration, 2 /* NeverApplyImportHelper */); @@ -28088,7 +28235,8 @@ ${lanes.join("\n")} const { languageVersion, setExternalModuleIndicator: overrideSetExternalModuleIndicator, - impliedNodeFormat: format + impliedNodeFormat: format, + jsDocParsingMode } = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions : { languageVersion: languageVersionOrOptions }; if (languageVersion === 100 /* JSON */) { result = Parser.parseSourceFile( @@ -28099,7 +28247,8 @@ ${lanes.join("\n")} void 0, setParentNodes, 6 /* JSON */, - noop + noop, + jsDocParsingMode ); } else { const setIndicator = format === void 0 ? overrideSetExternalModuleIndicator : (file) => { @@ -28114,7 +28263,8 @@ ${lanes.join("\n")} void 0, setParentNodes, scriptKind, - setIndicator + setIndicator, + jsDocParsingMode ); } (_c = perfLogger) == null ? void 0 : _c.logStopParseSourceFile(); @@ -28148,7 +28298,7 @@ ${lanes.join("\n")} return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length2); } function isDeclarationFileName(fileName) { - return fileExtensionIsOneOf(fileName, supportedDeclarationExtensions) || fileExtensionIs(fileName, ".ts" /* Ts */) && stringContains(getBaseFileName(fileName), ".d."); + return fileExtensionIsOneOf(fileName, supportedDeclarationExtensions) || fileExtensionIs(fileName, ".ts" /* Ts */) && getBaseFileName(fileName).includes(".d."); } function parseResolutionMode(mode, pos, end, reportDiagnostic) { if (!mode) { @@ -28331,7 +28481,7 @@ ${lanes.join("\n")} return {}; if (!pragma.args) return {}; - const args = trimString(text).split(/\s+/); + const args = text.trim().split(/\s+/); const argMap = {}; for (let i = 0; i < pragma.args.length; i++) { const argument = pragma.args[i]; @@ -28470,7 +28620,7 @@ ${lanes.join("\n")} return visitNode2(cbNode, node.typeParameter); }, [205 /* ImportType */]: function forEachChildInImportType(node, cbNode, cbNodes) { - return visitNode2(cbNode, node.argument) || visitNode2(cbNode, node.assertions) || visitNode2(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); + return visitNode2(cbNode, node.argument) || visitNode2(cbNode, node.attributes) || visitNode2(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); }, [302 /* ImportTypeAssertionContainer */]: function forEachChildInImportTypeAssertionContainer(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.assertClause); @@ -28644,15 +28794,15 @@ ${lanes.join("\n")} return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.moduleReference); }, [272 /* ImportDeclaration */]: function forEachChildInImportDeclaration(node, cbNode, cbNodes) { - return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.importClause) || visitNode2(cbNode, node.moduleSpecifier) || visitNode2(cbNode, node.assertClause); + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.importClause) || visitNode2(cbNode, node.moduleSpecifier) || visitNode2(cbNode, node.attributes); }, [273 /* ImportClause */]: function forEachChildInImportClause(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.namedBindings); }, - [300 /* AssertClause */]: function forEachChildInAssertClause(node, cbNode, cbNodes) { + [300 /* ImportAttributes */]: function forEachChildInImportAttributes(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.elements); }, - [301 /* AssertEntry */]: function forEachChildInAssertEntry(node, cbNode, _cbNodes) { + [301 /* ImportAttribute */]: function forEachChildInImportAttribute(node, cbNode, _cbNodes) { return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.value); }, [270 /* NamespaceExportDeclaration */]: function forEachChildInNamespaceExportDeclaration(node, cbNode, cbNodes) { @@ -28667,7 +28817,7 @@ ${lanes.join("\n")} [275 /* NamedImports */]: forEachChildInNamedImportsOrExports, [279 /* NamedExports */]: forEachChildInNamedImportsOrExports, [278 /* ExportDeclaration */]: function forEachChildInExportDeclaration(node, cbNode, cbNodes) { - return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.exportClause) || visitNode2(cbNode, node.moduleSpecifier) || visitNode2(cbNode, node.assertClause); + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.exportClause) || visitNode2(cbNode, node.moduleSpecifier) || visitNode2(cbNode, node.attributes); }, [276 /* ImportSpecifier */]: forEachChildInImportOrExportSpecifier, [281 /* ExportSpecifier */]: forEachChildInImportOrExportSpecifier, @@ -28898,7 +29048,7 @@ ${lanes.join("\n")} var contextFlags; var topLevel = true; var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName2, sourceText2, languageVersion2, syntaxCursor2, setParentNodes = false, scriptKind2, setExternalModuleIndicatorOverride) { + function parseSourceFile(fileName2, sourceText2, languageVersion2, syntaxCursor2, setParentNodes = false, scriptKind2, setExternalModuleIndicatorOverride, jsDocParsingMode = 0 /* ParseAll */) { var _a; scriptKind2 = ensureScriptKind(fileName2, scriptKind2); if (scriptKind2 === 6 /* JSON */) { @@ -28920,8 +29070,8 @@ ${lanes.join("\n")} result2.pragmas = emptyMap; return result2; } - initializeState(fileName2, sourceText2, languageVersion2, syntaxCursor2, scriptKind2); - const result = parseSourceFileWorker(languageVersion2, setParentNodes, scriptKind2, setExternalModuleIndicatorOverride || setExternalModuleIndicator); + initializeState(fileName2, sourceText2, languageVersion2, syntaxCursor2, scriptKind2, jsDocParsingMode); + const result = parseSourceFileWorker(languageVersion2, setParentNodes, scriptKind2, setExternalModuleIndicatorOverride || setExternalModuleIndicator, jsDocParsingMode); clearState(); return result; } @@ -28933,20 +29083,21 @@ ${lanes.join("\n")} languageVersion2, /*syntaxCursor*/ void 0, - 1 /* JS */ + 1 /* JS */, + 0 /* ParseAll */ ); nextToken(); const entityName = parseEntityName( /*allowReservedWords*/ true ); - const isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; + const isValid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; clearState(); - return isInvalid ? entityName : void 0; + return isValid ? entityName : void 0; } Parser2.parseIsolatedEntityName = parseIsolatedEntityName2; function parseJsonText2(fileName2, sourceText2, languageVersion2 = 2 /* ES2015 */, syntaxCursor2, setParentNodes = false) { - initializeState(fileName2, sourceText2, languageVersion2, syntaxCursor2, 6 /* JSON */); + initializeState(fileName2, sourceText2, languageVersion2, syntaxCursor2, 6 /* JSON */, 0 /* ParseAll */); sourceFlags = contextFlags; nextToken(); const pos = getNodePos(); @@ -29027,7 +29178,7 @@ ${lanes.join("\n")} return result; } Parser2.parseJsonText = parseJsonText2; - function initializeState(_fileName, _sourceText, _languageVersion, _syntaxCursor, _scriptKind) { + function initializeState(_fileName, _sourceText, _languageVersion, _syntaxCursor, _scriptKind, _jsDocParsingMode) { NodeConstructor2 = objectAllocator.getNodeConstructor(); TokenConstructor2 = objectAllocator.getTokenConstructor(); IdentifierConstructor2 = objectAllocator.getIdentifierConstructor(); @@ -29063,11 +29214,15 @@ ${lanes.join("\n")} scanner2.setOnError(scanError); scanner2.setScriptTarget(languageVersion); scanner2.setLanguageVariant(languageVariant); + scanner2.setScriptKind(scriptKind); + scanner2.setJSDocParsingMode(_jsDocParsingMode); } function clearState() { scanner2.clearCommentDirectives(); scanner2.setText(""); scanner2.setOnError(void 0); + scanner2.setScriptKind(0 /* Unknown */); + scanner2.setJSDocParsingMode(0 /* ParseAll */); sourceText = void 0; languageVersion = void 0; syntaxCursor = void 0; @@ -29081,7 +29236,7 @@ ${lanes.join("\n")} notParenthesizedArrow = void 0; topLevel = true; } - function parseSourceFileWorker(languageVersion2, setParentNodes, scriptKind2, setExternalModuleIndicator2) { + function parseSourceFileWorker(languageVersion2, setParentNodes, scriptKind2, setExternalModuleIndicator2, jsDocParsingMode) { const isDeclarationFile = isDeclarationFileName(fileName); if (isDeclarationFile) { contextFlags |= 33554432 /* Ambient */; @@ -29100,6 +29255,7 @@ ${lanes.join("\n")} sourceFile.identifierCount = identifierCount; sourceFile.identifiers = identifiers; sourceFile.parseDiagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile); + sourceFile.jsDocParsingMode = jsDocParsingMode; if (jsDocDiagnostics) { sourceFile.jsDocDiagnostics = attachFileToDiagnostics(jsDocDiagnostics, sourceFile); } @@ -29108,7 +29264,7 @@ ${lanes.join("\n")} } return sourceFile; function reportPragmaDiagnostic(pos, end, diagnostic) { - parseDiagnostics.push(createDetachedDiagnostic(fileName, pos, end, diagnostic)); + parseDiagnostics.push(createDetachedDiagnostic(fileName, sourceText, pos, end, diagnostic)); } } let hasDeprecatedTag = false; @@ -29348,7 +29504,7 @@ ${lanes.join("\n")} const lastError = lastOrUndefined(parseDiagnostics); let result; if (!lastError || start !== lastError.start) { - result = createDetachedDiagnostic(fileName, start, length2, message, ...args); + result = createDetachedDiagnostic(fileName, sourceText, start, length2, message, ...args); parseDiagnostics.push(result); } parseErrorBeforeNextFinishedNode = true; @@ -29576,7 +29732,7 @@ ${lanes.join("\n")} if (lastError) { addRelatedInfo( lastError, - createDetachedDiagnostic(fileName, openPosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, tokenToString(openKind), tokenToString(closeKind)) + createDetachedDiagnostic(fileName, sourceText, openPosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, tokenToString(openKind), tokenToString(closeKind)) ); } } @@ -29746,10 +29902,16 @@ ${lanes.join("\n")} function parseIdentifierName(diagnosticMessage) { return createIdentifier(tokenIsIdentifierOrKeyword(token()), diagnosticMessage); } + function parseIdentifierNameErrorOnUnicodeEscapeSequence() { + if (scanner2.hasUnicodeEscape() || scanner2.hasExtendedUnicodeEscape()) { + parseErrorAtCurrentToken(Diagnostics.Unicode_escape_sequence_cannot_appear_here); + } + return createIdentifier(tokenIsIdentifierOrKeyword(token())); + } function isLiteralPropertyName() { return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */; } - function isAssertionKey2() { + function isImportAttributeName2() { return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */; } function parsePropertyNameWorker(allowComputedPropertyNames) { @@ -29868,8 +30030,8 @@ ${lanes.join("\n")} return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: return token() === 23 /* OpenBracketToken */ || token() === 26 /* DotDotDotToken */ || isLiteralPropertyName(); - case 24 /* AssertEntries */: - return isAssertionKey2(); + case 24 /* ImportAttributes */: + return isImportAttributeName2(); case 7 /* HeritageClauseElement */: if (token() === 19 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); @@ -29972,7 +30134,7 @@ ${lanes.join("\n")} case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: case 23 /* ImportOrExportSpecifiers */: - case 24 /* AssertEntries */: + case 24 /* ImportAttributes */: return token() === 20 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: return token() === 20 /* CloseBraceToken */ || token() === 84 /* CaseKeyword */ || token() === 90 /* DefaultKeyword */; @@ -30278,7 +30440,7 @@ ${lanes.join("\n")} return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 14 /* JsxChildren */: return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); - case 24 /* AssertEntries */: + case 24 /* ImportAttributes */: return parseErrorAtCurrentToken(Diagnostics.Identifier_or_string_literal_expected); case 25 /* JSDocComment */: return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); @@ -30372,7 +30534,9 @@ ${lanes.join("\n")} parseRightSideOfDot( allowReservedWords, /*allowPrivateIdentifiers*/ - false + false, + /*allowUnicodeEscapeSequenceInIdentifierName*/ + true ) ), pos @@ -30383,7 +30547,7 @@ ${lanes.join("\n")} function createQualifiedName(entity, name) { return finishNode(factory2.createQualifiedName(entity, name), entity.pos); } - function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) { + function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers, allowUnicodeEscapeSequenceInIdentifierName) { if (scanner2.hasPrecedingLineBreak() && tokenIsIdentifierOrKeyword(token())) { const matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { @@ -30404,7 +30568,10 @@ ${lanes.join("\n")} Diagnostics.Identifier_expected ); } - return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + if (allowIdentifierNames) { + return allowUnicodeEscapeSequenceInIdentifierName ? parseIdentifierName() : parseIdentifierNameErrorOnUnicodeEscapeSequence(); + } + return parseIdentifier(); } function parseTemplateSpans(isTaggedTemplate) { const pos = getNodePos(); @@ -31148,28 +31315,6 @@ ${lanes.join("\n")} nextToken(); return token() === 102 /* ImportKeyword */; } - function parseImportTypeAssertions() { - const pos = getNodePos(); - const openBracePosition = scanner2.getTokenStart(); - parseExpected(19 /* OpenBraceToken */); - const multiLine = scanner2.hasPrecedingLineBreak(); - parseExpected(132 /* AssertKeyword */); - parseExpected(59 /* ColonToken */); - const clause = parseAssertClause( - /*skipAssertKeyword*/ - true - ); - if (!parseExpected(20 /* CloseBraceToken */)) { - const lastError = lastOrUndefined(parseDiagnostics); - if (lastError && lastError.code === Diagnostics._0_expected.code) { - addRelatedInfo( - lastError, - createDetachedDiagnostic(fileName, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") - ); - } - } - return finishNode(factory2.createImportTypeAssertionContainer(clause, multiLine), pos); - } function parseImportType() { sourceFlags |= 4194304 /* PossiblyContainsDynamicImport */; const pos = getNodePos(); @@ -31177,14 +31322,36 @@ ${lanes.join("\n")} parseExpected(102 /* ImportKeyword */); parseExpected(21 /* OpenParenToken */); const type = parseType(); - let assertions; + let attributes; if (parseOptional(28 /* CommaToken */)) { - assertions = parseImportTypeAssertions(); + const openBracePosition = scanner2.getTokenStart(); + parseExpected(19 /* OpenBraceToken */); + const currentToken2 = token(); + if (currentToken2 === 118 /* WithKeyword */ || currentToken2 === 132 /* AssertKeyword */) { + nextToken(); + } else { + parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(118 /* WithKeyword */)); + } + parseExpected(59 /* ColonToken */); + attributes = parseImportAttributes( + currentToken2, + /*skipKeyword*/ + true + ); + if (!parseExpected(20 /* CloseBraceToken */)) { + const lastError = lastOrUndefined(parseDiagnostics); + if (lastError && lastError.code === Diagnostics._0_expected.code) { + addRelatedInfo( + lastError, + createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") + ); + } + } } parseExpected(22 /* CloseParenToken */); const qualifier = parseOptional(25 /* DotToken */) ? parseEntityNameOfTypeReference() : void 0; const typeArguments = parseTypeArgumentsOfTypeReference(); - return finishNode(factory2.createImportTypeNode(type, assertions, qualifier, typeArguments, isTypeOf), pos); + return finishNode(factory2.createImportTypeNode(type, attributes, qualifier, typeArguments, isTypeOf), pos); } function nextTokenIsNumericOrBigIntLiteral() { nextToken(); @@ -32179,6 +32346,8 @@ ${lanes.join("\n")} /*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ + true, + /*allowUnicodeEscapeSequenceInIdentifierName*/ true )), pos); } @@ -32346,6 +32515,8 @@ ${lanes.join("\n")} /*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ + false, + /*allowUnicodeEscapeSequenceInIdentifierName*/ false )), pos); } @@ -32355,10 +32526,10 @@ ${lanes.join("\n")} const pos = getNodePos(); scanJsxIdentifier(); const isThis2 = token() === 110 /* ThisKeyword */; - const tagName = parseIdentifierName(); + const tagName = parseIdentifierNameErrorOnUnicodeEscapeSequence(); if (parseOptional(59 /* ColonToken */)) { scanJsxIdentifier(); - return finishNode(factory2.createJsxNamespacedName(tagName, parseIdentifierName()), pos); + return finishNode(factory2.createJsxNamespacedName(tagName, parseIdentifierNameErrorOnUnicodeEscapeSequence()), pos); } return isThis2 ? finishNode(factory2.createToken(110 /* ThisKeyword */), pos) : tagName; } @@ -32370,7 +32541,9 @@ ${lanes.join("\n")} let dotDotDotToken; let expression; if (token() !== 20 /* CloseBraceToken */) { - dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */); + if (!inExpressionContext) { + dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */); + } expression = parseExpression(); } if (inExpressionContext) { @@ -32419,10 +32592,10 @@ ${lanes.join("\n")} function parseJsxAttributeName() { const pos = getNodePos(); scanJsxIdentifier(); - const attrName = parseIdentifierName(); + const attrName = parseIdentifierNameErrorOnUnicodeEscapeSequence(); if (parseOptional(59 /* ColonToken */)) { scanJsxIdentifier(); - return finishNode(factory2.createJsxNamespacedName(attrName, parseIdentifierName()), pos); + return finishNode(factory2.createJsxNamespacedName(attrName, parseIdentifierNameErrorOnUnicodeEscapeSequence()), pos); } return attrName; } @@ -32510,6 +32683,8 @@ ${lanes.join("\n")} /*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ + true, + /*allowUnicodeEscapeSequenceInIdentifierName*/ true ); const isOptionalChain2 = questionDotToken || tryReparseOptionalChain(expression); @@ -32994,7 +33169,8 @@ ${lanes.join("\n")} parseExpected(21 /* OpenParenToken */); let initializer; if (token() !== 27 /* SemicolonToken */) { - if (token() === 115 /* VarKeyword */ || token() === 121 /* LetKeyword */ || token() === 87 /* ConstKeyword */ || token() === 160 /* UsingKeyword */ && lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf) || token() === 135 /* AwaitKeyword */ && lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLineDisallowOf)) { + if (token() === 115 /* VarKeyword */ || token() === 121 /* LetKeyword */ || token() === 87 /* ConstKeyword */ || token() === 160 /* UsingKeyword */ && lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf) || // this one is meant to allow of + token() === 135 /* AwaitKeyword */ && lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine)) { initializer = parseVariableDeclarationList( /*inForStatementInitializer*/ true @@ -33315,12 +33491,6 @@ ${lanes.join("\n")} function isUsingDeclaration() { return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine); } - function nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLineDisallowOf() { - return nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine( - /*disallowOf*/ - true - ); - } function nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine(disallowOf) { if (nextToken() === 160 /* UsingKeyword */) { return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf); @@ -33677,11 +33847,11 @@ ${lanes.join("\n")} const modifierFlags = modifiersToFlags(modifiers); parseExpected(100 /* FunctionKeyword */); const asteriskToken = parseOptionalToken(42 /* AsteriskToken */); - const name = modifierFlags & 1024 /* Default */ ? parseOptionalBindingIdentifier() : parseBindingIdentifier(); + const name = modifierFlags & 2048 /* Default */ ? parseOptionalBindingIdentifier() : parseBindingIdentifier(); const isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; - const isAsync = modifierFlags & 512 /* Async */ ? 2 /* Await */ : 0 /* None */; + const isAsync = modifierFlags & 1024 /* Async */ ? 2 /* Await */ : 0 /* None */; const typeParameters = parseTypeParameters(); - if (modifierFlags & 1 /* Export */) + if (modifierFlags & 32 /* Export */) setAwaitContext( /*value*/ true @@ -34149,7 +34319,7 @@ ${lanes.join("\n")} } function parseModuleOrNamespaceDeclaration(pos, hasJSDoc, modifiers, flags) { const namespaceFlag = flags & 32 /* Namespace */; - const name = parseIdentifier(); + const name = flags & 8 /* NestedNamespace */ ? parseIdentifierName() : parseIdentifier(); const body = parseOptional(25 /* DotToken */) ? parseModuleOrNamespaceDeclaration( getNodePos(), /*hasJSDoc*/ @@ -34238,16 +34408,16 @@ ${lanes.join("\n")} parseExpected(161 /* FromKeyword */); } const moduleSpecifier = parseModuleSpecifier(); - let assertClause; - const hasAssertKeyword = token() === 132 /* AssertKeyword */ || token() === 118 /* WithKeyword */; - if (hasAssertKeyword && !scanner2.hasPrecedingLineBreak()) { - assertClause = parseAssertClause(); + const currentToken2 = token(); + let attributes; + if ((currentToken2 === 118 /* WithKeyword */ || currentToken2 === 132 /* AssertKeyword */) && !scanner2.hasPrecedingLineBreak()) { + attributes = parseImportAttributes(currentToken2); } parseSemicolon(); - const node = factory2.createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + const node = factory2.createImportDeclaration(modifiers, importClause, moduleSpecifier, attributes); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseAssertEntry() { + function parseImportAttribute() { const pos = getNodePos(); const name = tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(11 /* StringLiteral */); parseExpected(59 /* ColonToken */); @@ -34255,23 +34425,19 @@ ${lanes.join("\n")} /*allowReturnTypeInArrowFunction*/ true ); - return finishNode(factory2.createAssertEntry(name, value), pos); + return finishNode(factory2.createImportAttribute(name, value), pos); } - function parseAssertClause(skipAssertKeyword) { + function parseImportAttributes(token2, skipKeyword) { const pos = getNodePos(); - if (!skipAssertKeyword) { - if (token() === 118 /* WithKeyword */) { - parseExpected(118 /* WithKeyword */); - } else { - parseExpected(132 /* AssertKeyword */); - } + if (!skipKeyword) { + parseExpected(token2); } const openBracePosition = scanner2.getTokenStart(); if (parseExpected(19 /* OpenBraceToken */)) { const multiLine = scanner2.hasPrecedingLineBreak(); const elements = parseDelimitedList( - 24 /* AssertEntries */, - parseAssertEntry, + 24 /* ImportAttributes */, + parseImportAttribute, /*considerSemicolonAsDelimiter*/ true ); @@ -34280,11 +34446,11 @@ ${lanes.join("\n")} if (lastError && lastError.code === Diagnostics._0_expected.code) { addRelatedInfo( lastError, - createDetachedDiagnostic(fileName, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") + createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") ); } } - return finishNode(factory2.createAssertClause(elements, multiLine), pos); + return finishNode(factory2.createImportAttributes(elements, multiLine, token2), pos); } else { const elements = createNodeArray( [], @@ -34294,10 +34460,11 @@ ${lanes.join("\n")} /*hasTrailingComma*/ false ); - return finishNode(factory2.createAssertClause( + return finishNode(factory2.createImportAttributes( elements, /*multiLine*/ - false + false, + token2 ), pos); } } @@ -34429,7 +34596,7 @@ ${lanes.join("\n")} ); let exportClause; let moduleSpecifier; - let assertClause; + let attributes; const isTypeOnly = parseOptional(156 /* TypeKeyword */); const namespaceExportPos = getNodePos(); if (parseOptional(42 /* AsteriskToken */)) { @@ -34445,12 +34612,13 @@ ${lanes.join("\n")} moduleSpecifier = parseModuleSpecifier(); } } - if (moduleSpecifier && token() === 132 /* AssertKeyword */ && !scanner2.hasPrecedingLineBreak()) { - assertClause = parseAssertClause(); + const currentToken2 = token(); + if (moduleSpecifier && (currentToken2 === 118 /* WithKeyword */ || currentToken2 === 132 /* AssertKeyword */) && !scanner2.hasPrecedingLineBreak()) { + attributes = parseImportAttributes(currentToken2); } parseSemicolon(); setAwaitContext(savedAwaitContext); - const node = factory2.createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + const node = factory2.createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseExportAssignment(pos, hasJSDoc, modifiers) { @@ -34500,7 +34668,7 @@ ${lanes.join("\n")} ParsingContext2[ParsingContext2["TupleElementTypes"] = 21] = "TupleElementTypes"; ParsingContext2[ParsingContext2["HeritageClauses"] = 22] = "HeritageClauses"; ParsingContext2[ParsingContext2["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; - ParsingContext2[ParsingContext2["AssertEntries"] = 24] = "AssertEntries"; + ParsingContext2[ParsingContext2["ImportAttributes"] = 24] = "ImportAttributes"; ParsingContext2[ParsingContext2["JSDocComment"] = 25] = "JSDocComment"; ParsingContext2[ParsingContext2["Count"] = 26] = "Count"; })(ParsingContext || (ParsingContext = {})); @@ -34519,7 +34687,8 @@ ${lanes.join("\n")} 99 /* Latest */, /*syntaxCursor*/ void 0, - 1 /* JS */ + 1 /* JS */, + 0 /* ParseAll */ ); scanner2.setText(content, start, length2); currentToken = scanner2.scan(); @@ -34583,7 +34752,8 @@ ${lanes.join("\n")} 99 /* Latest */, /*syntaxCursor*/ void 0, - 1 /* JS */ + 1 /* JS */, + 0 /* ParseAll */ ); const jsDoc = doInsideOfContext(16777216 /* JSDoc */, () => parseJSDocCommentWorker(start, length2)); const sourceFile = { languageVariant: 0 /* Standard */, text: content }; @@ -34624,8 +34794,6 @@ ${lanes.join("\n")} PropertyLikeParse2[PropertyLikeParse2["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start = 0, length2) { - const saveParsingContext = parsingContext; - parsingContext |= 1 << 25 /* JSDocComment */; const content = sourceText; const end = length2 === void 0 ? content.length : start + length2; length2 = end - start; @@ -34642,26 +34810,28 @@ ${lanes.join("\n")} let commentsPos; let comments = []; const parts = []; + const saveParsingContext = parsingContext; + parsingContext |= 1 << 25 /* JSDocComment */; const result = scanner2.scanRange(start + 3, length2 - 5, doJSDocScan); parsingContext = saveParsingContext; return result; function doJSDocScan() { let state = 1 /* SawAsterisk */; let margin; - let indent2 = start - (content.lastIndexOf("\n", start) + 1) + 4; + let indent3 = start - (content.lastIndexOf("\n", start) + 1) + 4; function pushComment(text) { if (!margin) { - margin = indent2; + margin = indent3; } comments.push(text); - indent2 += text.length; + indent3 += text.length; } nextTokenJSDoc(); while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) ; if (parseOptionalJsdoc(4 /* NewLineTrivia */)) { state = 0 /* BeginningOfLine */; - indent2 = 0; + indent3 = 0; } loop: while (true) { @@ -34670,14 +34840,14 @@ ${lanes.join("\n")} removeTrailingWhitespace(comments); if (!commentsPos) commentsPos = getNodePos(); - addTag(parseTag(indent2)); + addTag(parseTag(indent3)); state = 0 /* BeginningOfLine */; margin = void 0; break; case 4 /* NewLineTrivia */: comments.push(scanner2.getTokenText()); state = 0 /* BeginningOfLine */; - indent2 = 0; + indent3 = 0; break; case 42 /* AsteriskToken */: const asterisk = scanner2.getTokenText(); @@ -34687,16 +34857,16 @@ ${lanes.join("\n")} } else { Debug.assert(state === 0 /* BeginningOfLine */); state = 1 /* SawAsterisk */; - indent2 += asterisk.length; + indent3 += asterisk.length; } break; case 5 /* WhitespaceTrivia */: Debug.assert(state !== 2 /* SavingComments */, "whitespace shouldn't come from the scanner while saving top-level comment text"); const whitespace = scanner2.getTokenText(); - if (margin !== void 0 && indent2 + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent2)); + if (margin !== void 0 && indent3 + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent3)); } - indent2 += whitespace.length; + indent3 += whitespace.length; break; case 1 /* EndOfFileToken */: break loop; @@ -34733,7 +34903,7 @@ ${lanes.join("\n")} nextTokenJSDoc(); } } - const trimmedComments = trimStringEnd(comments.join("")); + const trimmedComments = comments.join("").trimEnd(); if (parts.length && trimmedComments.length) { parts.push(finishNode(factory2.createJSDocText(trimmedComments), linkEnd ?? start, commentsPos)); } @@ -34749,7 +34919,7 @@ ${lanes.join("\n")} } function removeTrailingWhitespace(comments2) { while (comments2.length) { - const trimmed = trimStringEnd(comments2[comments2.length - 1]); + const trimmed = comments2[comments2.length - 1].trimEnd(); if (trimmed === "") { comments2.pop(); } else if (trimmed.length < comments2[comments2.length - 1].length) { @@ -34898,7 +35068,7 @@ ${lanes.join("\n")} } return parseTagComments(margin, indentText.slice(margin)); } - function parseTagComments(indent2, initialMargin) { + function parseTagComments(indent3, initialMargin) { const commentsPos2 = getNodePos(); let comments2 = []; const parts2 = []; @@ -34907,10 +35077,10 @@ ${lanes.join("\n")} let margin; function pushComment(text) { if (!margin) { - margin = indent2; + margin = indent3; } comments2.push(text); - indent2 += text.length; + indent3 += text.length; } if (initialMargin !== void 0) { if (initialMargin !== "") { @@ -34925,7 +35095,7 @@ ${lanes.join("\n")} case 4 /* NewLineTrivia */: state = 0 /* BeginningOfLine */; comments2.push(scanner2.getTokenText()); - indent2 = 0; + indent3 = 0; break; case 60 /* AtToken */: scanner2.resetTokenState(scanner2.getTokenEnd() - 1); @@ -34935,11 +35105,11 @@ ${lanes.join("\n")} case 5 /* WhitespaceTrivia */: Debug.assert(state !== 2 /* SavingComments */ && state !== 3 /* SavingBackticks */, "whitespace shouldn't come from the scanner while saving comment text"); const whitespace = scanner2.getTokenText(); - if (margin !== void 0 && indent2 + whitespace.length > margin) { - comments2.push(whitespace.slice(margin - indent2)); + if (margin !== void 0 && indent3 + whitespace.length > margin) { + comments2.push(whitespace.slice(margin - indent3)); state = 2 /* SavingComments */; } - indent2 += whitespace.length; + indent3 += whitespace.length; break; case 19 /* OpenBraceToken */: state = 2 /* SavingComments */; @@ -34972,7 +35142,7 @@ ${lanes.join("\n")} case 42 /* AsteriskToken */: if (state === 0 /* BeginningOfLine */) { state = 1 /* SawAsterisk */; - indent2 += 1; + indent3 += 1; break; } default: @@ -34989,7 +35159,7 @@ ${lanes.join("\n")} } } removeLeadingNewlines(comments2); - const trimmedComments = trimStringEnd(comments2.join("")); + const trimmedComments = comments2.join("").trimEnd(); if (parts2.length) { if (trimmedComments.length) { parts2.push(finishNode(factory2.createJSDocText(trimmedComments), linkEnd2 ?? commentsPos2)); @@ -35037,8 +35207,8 @@ ${lanes.join("\n")} function isJSDocLinkTag(kind) { return kind === "link" || kind === "linkcode" || kind === "linkplain"; } - function parseUnknownTag(start2, tagName, indent2, indentText) { - return finishNode(factory2.createJSDocUnknownTag(tagName, parseTrailingTagComments(start2, getNodePos(), indent2, indentText)), start2); + function parseUnknownTag(start2, tagName, indent3, indentText) { + return finishNode(factory2.createJSDocUnknownTag(tagName, parseTrailingTagComments(start2, getNodePos(), indent3, indentText)), start2); } function addTag(tag) { if (!tag) { @@ -35085,7 +35255,7 @@ ${lanes.join("\n")} return isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments; } } - function parseParameterOrPropertyTag(start2, tagName, target, indent2) { + function parseParameterOrPropertyTag(start2, tagName, target, indent3) { let typeExpression = tryParseTypeExpression(); let isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); @@ -35094,8 +35264,8 @@ ${lanes.join("\n")} if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) { typeExpression = tryParseTypeExpression(); } - const comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText); - const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target, indent2); + const comment = parseTrailingTagComments(start2, getNodePos(), indent3, indentText); + const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target, indent3); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -35103,12 +35273,12 @@ ${lanes.join("\n")} const result2 = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); return finishNode(result2, start2); } - function parseNestedTypeLiteral(typeExpression, name, target, indent2) { + function parseNestedTypeLiteral(typeExpression, name, target, indent3) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { const pos = getNodePos(); let child; let children; - while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent2, name))) { + while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent3, name))) { if (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */) { children = append(children, child); } else if (child.kind === 352 /* JSDocTemplateTag */) { @@ -35121,14 +35291,14 @@ ${lanes.join("\n")} } } } - function parseReturnTag(start2, tagName, indent2, indentText) { + function parseReturnTag(start2, tagName, indent3, indentText) { if (some(tags, isJSDocReturnTag)) { parseErrorAt(tagName.pos, scanner2.getTokenStart(), Diagnostics._0_tag_already_specified, unescapeLeadingUnderscores(tagName.escapedText)); } const typeExpression = tryParseTypeExpression(); - return finishNode(factory2.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start2, getNodePos(), indent2, indentText)), start2); + return finishNode(factory2.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start2, getNodePos(), indent3, indentText)), start2); } - function parseTypeTag(start2, tagName, indent2, indentText) { + function parseTypeTag(start2, tagName, indent3, indentText) { if (some(tags, isJSDocTypeTag)) { parseErrorAt(tagName.pos, scanner2.getTokenStart(), Diagnostics._0_tag_already_specified, unescapeLeadingUnderscores(tagName.escapedText)); } @@ -35136,25 +35306,25 @@ ${lanes.join("\n")} /*mayOmitBraces*/ true ); - const comments2 = indent2 !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), indent2, indentText) : void 0; + const comments2 = indent3 !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), indent3, indentText) : void 0; return finishNode(factory2.createJSDocTypeTag(tagName, typeExpression, comments2), start2); } - function parseSeeTag(start2, tagName, indent2, indentText) { + function parseSeeTag(start2, tagName, indent3, indentText) { const isMarkdownOrJSDocLink = token() === 23 /* OpenBracketToken */ || lookAhead(() => nextTokenJSDoc() === 60 /* AtToken */ && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && isJSDocLinkTag(scanner2.getTokenValue())); const nameExpression = isMarkdownOrJSDocLink ? void 0 : parseJSDocNameReference(); - const comments2 = indent2 !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), indent2, indentText) : void 0; + const comments2 = indent3 !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), indent3, indentText) : void 0; return finishNode(factory2.createJSDocSeeTag(tagName, nameExpression, comments2), start2); } - function parseThrowsTag(start2, tagName, indent2, indentText) { + function parseThrowsTag(start2, tagName, indent3, indentText) { const typeExpression = tryParseTypeExpression(); - const comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText); + const comment = parseTrailingTagComments(start2, getNodePos(), indent3, indentText); return finishNode(factory2.createJSDocThrowsTag(tagName, typeExpression, comment), start2); } - function parseAuthorTag(start2, tagName, indent2, indentText) { + function parseAuthorTag(start2, tagName, indent3, indentText) { const commentStart = getNodePos(); const textOnly = parseAuthorNameAndEmail(); let commentEnd = scanner2.getTokenFullStart(); - const comments2 = parseTrailingTagComments(start2, commentEnd, indent2, indentText); + const comments2 = parseTrailingTagComments(start2, commentEnd, indent3, indentText); if (!comments2) { commentEnd = scanner2.getTokenFullStart(); } @@ -35238,19 +35408,19 @@ ${lanes.join("\n")} skipWhitespace(); return finishNode(factory2.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2); } - function parseTypedefTag(start2, tagName, indent2, indentText) { + function parseTypedefTag(start2, tagName, indent3, indentText) { let typeExpression = tryParseTypeExpression(); skipWhitespaceOrAsterisk(); const fullName = parseJSDocTypeNameWithNamespace(); skipWhitespace(); - let comment = parseTagComments(indent2); + let comment = parseTagComments(indent3); let end2; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { let child; let childTypeTag; let jsDocPropertyTags; let hasChildren = false; - while (child = tryParse(() => parseChildPropertyTag(indent2))) { + while (child = tryParse(() => parseChildPropertyTag(indent3))) { if (child.kind === 352 /* JSDocTemplateTag */) { break; } @@ -35259,7 +35429,7 @@ ${lanes.join("\n")} if (childTypeTag) { const lastError = parseErrorAtCurrentToken(Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); if (lastError) { - addRelatedInfo(lastError, createDetachedDiagnostic(fileName, 0, 0, Diagnostics.The_tag_was_first_specified_here)); + addRelatedInfo(lastError, createDetachedDiagnostic(fileName, sourceText, 0, 0, Diagnostics.The_tag_was_first_specified_here)); } break; } else { @@ -35278,7 +35448,7 @@ ${lanes.join("\n")} } end2 = end2 || comment !== void 0 ? getNodePos() : (fullName ?? typeExpression ?? tagName).end; if (!comment) { - comment = parseTrailingTagComments(start2, end2, indent2, indentText); + comment = parseTrailingTagComments(start2, end2, indent3, indentText); } const typedefTag = factory2.createJSDocTypedefTag(tagName, typeExpression, fullName, comment); return finishNode(typedefTag, start2, end2); @@ -35308,11 +35478,11 @@ ${lanes.join("\n")} } return typeNameOrNamespaceName; } - function parseCallbackTagParameters(indent2) { + function parseCallbackTagParameters(indent3) { const pos = getNodePos(); let child; let parameters; - while (child = tryParse(() => parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent2))) { + while (child = tryParse(() => parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent3))) { if (child.kind === 352 /* JSDocTemplateTag */) { parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); break; @@ -35321,11 +35491,11 @@ ${lanes.join("\n")} } return createNodeArray(parameters || [], pos); } - function parseJSDocSignature(start2, indent2) { - const parameters = parseCallbackTagParameters(indent2); + function parseJSDocSignature(start2, indent3) { + const parameters = parseCallbackTagParameters(indent3); const returnTag = tryParse(() => { if (parseOptionalJsdoc(60 /* AtToken */)) { - const tag = parseTag(indent2); + const tag = parseTag(indent3); if (tag && tag.kind === 349 /* JSDocReturnTag */) { return tag; } @@ -35338,23 +35508,23 @@ ${lanes.join("\n")} returnTag ), start2); } - function parseCallbackTag(start2, tagName, indent2, indentText) { + function parseCallbackTag(start2, tagName, indent3, indentText) { const fullName = parseJSDocTypeNameWithNamespace(); skipWhitespace(); - let comment = parseTagComments(indent2); - const typeExpression = parseJSDocSignature(start2, indent2); + let comment = parseTagComments(indent3); + const typeExpression = parseJSDocSignature(start2, indent3); if (!comment) { - comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText); + comment = parseTrailingTagComments(start2, getNodePos(), indent3, indentText); } const end2 = comment !== void 0 ? getNodePos() : typeExpression.end; return finishNode(factory2.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start2, end2); } - function parseOverloadTag(start2, tagName, indent2, indentText) { + function parseOverloadTag(start2, tagName, indent3, indentText) { skipWhitespace(); - let comment = parseTagComments(indent2); - const typeExpression = parseJSDocSignature(start2, indent2); + let comment = parseTagComments(indent3); + const typeExpression = parseJSDocSignature(start2, indent3); if (!comment) { - comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText); + comment = parseTrailingTagComments(start2, getNodePos(), indent3, indentText); } const end2 = comment !== void 0 ? getNodePos() : typeExpression.end; return finishNode(factory2.createJSDocOverloadTag(tagName, typeExpression, comment), start2, end2); @@ -35370,17 +35540,17 @@ ${lanes.join("\n")} } return a.escapedText === b.escapedText; } - function parseChildPropertyTag(indent2) { - return parseChildParameterOrPropertyTag(1 /* Property */, indent2); + function parseChildPropertyTag(indent3) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent3); } - function parseChildParameterOrPropertyTag(target, indent2, name) { + function parseChildParameterOrPropertyTag(target, indent3, name) { let canParseTag = true; let seenAsterisk = false; while (true) { switch (nextTokenJSDoc()) { case 60 /* AtToken */: if (canParseTag) { - const child = tryParseChildTag(target, indent2); + const child = tryParseChildTag(target, indent3); if (child && (child.kind === 348 /* JSDocParameterTag */ || child.kind === 355 /* JSDocPropertyTag */) && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } @@ -35406,7 +35576,7 @@ ${lanes.join("\n")} } } } - function tryParseChildTag(target, indent2) { + function tryParseChildTag(target, indent3) { Debug.assert(token() === 60 /* AtToken */); const start2 = scanner2.getTokenFullStart(); nextTokenJSDoc(); @@ -35426,14 +35596,14 @@ ${lanes.join("\n")} t = 2 /* Parameter */ | 4 /* CallbackParameter */; break; case "template": - return parseTemplateTag(start2, tagName, indent2, indentText); + return parseTemplateTag(start2, tagName, indent3, indentText); default: return false; } if (!(target & t)) { return false; } - return parseParameterOrPropertyTag(start2, tagName, target, indent2); + return parseParameterOrPropertyTag(start2, tagName, target, indent3); } function parseTemplateTagTypeParameter() { const typeParameterPos = getNodePos(); @@ -35474,10 +35644,10 @@ ${lanes.join("\n")} } while (parseOptionalJsdoc(28 /* CommaToken */)); return createNodeArray(typeParameters, pos); } - function parseTemplateTag(start2, tagName, indent2, indentText) { + function parseTemplateTag(start2, tagName, indent3, indentText) { const constraint = token() === 19 /* OpenBraceToken */ ? parseJSDocTypeExpression() : void 0; const typeParameters = parseTemplateTagTypeParameters(); - return finishNode(factory2.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start2, getNodePos(), indent2, indentText)), start2); + return finishNode(factory2.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start2, getNodePos(), indent3, indentText)), start2); } function parseOptionalJsdoc(t) { if (token() === t) { @@ -35538,7 +35708,8 @@ ${lanes.join("\n")} /*setParentNodes*/ true, sourceFile.scriptKind, - sourceFile.setExternalModuleIndicator + sourceFile.setExternalModuleIndicator, + sourceFile.jsDocParsingMode ); } const incrementalSourceFile = sourceFile; @@ -35553,16 +35724,7 @@ ${lanes.join("\n")} Debug.assert(textSpanEnd(changeRange.span) === textSpanEnd(textChangeRange.span)); Debug.assert(textSpanEnd(textChangeRangeNewSpan(changeRange)) === textSpanEnd(textChangeRangeNewSpan(textChangeRange))); const delta = textChangeRangeNewSpan(changeRange).length - changeRange.span.length; - updateTokenPositionsAndMarkElements( - incrementalSourceFile, - changeRange.span.start, - textSpanEnd(changeRange.span), - textSpanEnd(textChangeRangeNewSpan(changeRange)), - delta, - oldText, - newText, - aggressiveChecks - ); + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, textSpanEnd(changeRange.span), textSpanEnd(textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); const result = Parser.parseSourceFile( sourceFile.fileName, newText, @@ -35571,7 +35733,8 @@ ${lanes.join("\n")} /*setParentNodes*/ true, sourceFile.scriptKind, - sourceFile.setExternalModuleIndicator + sourceFile.setExternalModuleIndicator, + sourceFile.jsDocParsingMode ); result.commentDirectives = getNewCommentDirectives( sourceFile.commentDirectives, @@ -35924,14 +36087,14 @@ ${lanes.join("\n")} return createDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, stringNames); } function parseCustomTypeOption(opt, value, errors) { - return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); + return convertJsonOptionOfCustomType(opt, (value ?? "").trim(), errors); } function parseListTypeOption(opt, value = "", errors) { - value = trimString(value); + value = value.trim(); if (startsWith(value, "-")) { return void 0; } - if (opt.type === "listOrElement" && !stringContains(value, ",")) { + if (opt.type === "listOrElement" && !value.includes(",")) { return validateJsonOptionValue(opt, value, errors); } if (value === "") { @@ -36152,9 +36315,8 @@ ${lanes.join("\n")} } return { buildOptions, watchOptions, projects, errors }; } - function getDiagnosticText(_message, ..._args) { - const diagnostic = createCompilerDiagnostic.apply(void 0, arguments); - return diagnostic.messageText; + function getDiagnosticText(message, ...args) { + return cast(createCompilerDiagnostic(message, ...args).messageText, isString); } function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) { const configFileText = tryReadFile(configFileName, (fileName) => host.readFile(fileName)); @@ -36911,7 +37073,7 @@ ${lanes.join("\n")} var _a; basePath = normalizeSlashes(basePath); const resolvedPath = getNormalizedAbsolutePath(configFileName || "", basePath); - if (resolutionStack.indexOf(resolvedPath) >= 0) { + if (resolutionStack.includes(resolvedPath)) { errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))); return { raw: json || convertToObject(sourceFile, errors) }; } @@ -36993,14 +37155,17 @@ ${lanes.join("\n")} for (let index = 0; index < value.length; index++) { const fileName = value[index]; if (isString(fileName)) { - extendedConfigPath = append(extendedConfigPath, getExtendsConfigPath( - fileName, - host, - newBase, - errors, - valueExpression == null ? void 0 : valueExpression.elements[index], - sourceFile - )); + extendedConfigPath = append( + extendedConfigPath, + getExtendsConfigPath( + fileName, + host, + newBase, + errors, + valueExpression == null ? void 0 : valueExpression.elements[index], + sourceFile + ) + ); } else { convertJsonOption(extendsOptionDeclaration.element, value, basePath, errors, propertyAssignment, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile); } @@ -37430,7 +37595,7 @@ ${lanes.join("\n")} return false; } for (const ext of extensionGroup) { - if (fileExtensionIs(file, ext)) { + if (fileExtensionIs(file, ext) && (ext !== ".ts" /* Ts */ || !fileExtensionIs(file, ".d.ts" /* Dts */))) { return false; } const higherPriorityPath = keyMapper(changeExtension(file, ext)); @@ -37924,6 +38089,7 @@ ${lanes.join("\n")} node16: 100 /* Node16 */, nodenext: 199 /* NodeNext */ })), + affectsSourceFile: true, affectsModuleResolution: true, affectsEmit: true, affectsBuildInfo: true, @@ -38016,7 +38182,8 @@ ${lanes.join("\n")} { name: "allowJs", type: "boolean", - affectsModuleResolution: true, + allowJsFlag: true, + affectsBuildInfo: true, showInSimplifiedHelpView: true, category: Diagnostics.JavaScript_Support, description: Diagnostics.Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files, @@ -38026,6 +38193,8 @@ ${lanes.join("\n")} name: "checkJs", type: "boolean", affectsModuleResolution: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, showInSimplifiedHelpView: true, category: Diagnostics.JavaScript_Support, description: Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files, @@ -38038,6 +38207,10 @@ ${lanes.join("\n")} affectsEmit: true, affectsBuildInfo: true, affectsModuleResolution: true, + // The checker emits an error when it sees JSX but this option is not set in compilerOptions. + // This is effectively a semantic error, so mark this option as affecting semantic diagnostics + // so we know to refresh errors when this option is changed. + affectsSemanticDiagnostics: true, paramType: Diagnostics.KIND, showInSimplifiedHelpView: true, category: Diagnostics.Language_and_Environment, @@ -38353,6 +38526,7 @@ ${lanes.join("\n")} bundler: 100 /* Bundler */ })), deprecatedKeys: /* @__PURE__ */ new Set(["node"]), + affectsSourceFile: true, affectsModuleResolution: true, paramType: Diagnostics.STRATEGY, category: Diagnostics.Modules, @@ -38603,7 +38777,7 @@ ${lanes.join("\n")} affectsBuildInfo: true, affectsDeclarationPath: true, isFilePath: false, - // This is intentionally broken to support compatability with existing tsconfig files + // This is intentionally broken to support compatibility with existing tsconfig files // for correct behaviour, please use outFile category: Diagnostics.Backwards_Compatibility, paramType: Diagnostics.FILE, @@ -38895,6 +39069,7 @@ ${lanes.join("\n")} legacy: 1 /* Legacy */, force: 3 /* Force */ })), + affectsSourceFile: true, affectsModuleResolution: true, description: Diagnostics.Control_what_method_is_used_to_detect_module_format_JS_files, category: Diagnostics.Language_and_Environment, @@ -38914,7 +39089,7 @@ ${lanes.join("\n")} affectsEmitOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsEmit); affectsDeclarationPathOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsDeclarationPath); moduleResolutionOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsModuleResolution); - sourceFileAffectingCompilerOptions = optionDeclarations.filter((option) => !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics); + sourceFileAffectingCompilerOptions = optionDeclarations.filter((option) => !!option.affectsSourceFile || !!option.affectsBindDiagnostics); optionsAffectingProgramStructure = optionDeclarations.filter((option) => !!option.affectsProgramStructure); transpileOptionValueCompilerOptions = optionDeclarations.filter((option) => hasProperty(option, "transpileOptionValue")); optionsForBuild = [ @@ -39061,8 +39236,8 @@ ${lanes.join("\n")} }); // src/compiler/moduleNameResolver.ts - function trace(host) { - host.trace(formatMessage.apply(void 0, arguments)); + function trace(host, message, ...args) { + host.trace(formatMessage(message, ...args)); } function isTraceEnabled(compilerOptions, host) { return !!compilerOptions.traceResolution && host.trace !== void 0; @@ -39125,7 +39300,7 @@ ${lanes.join("\n")} Debug.assert(extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocationsHandlingSymlink(moduleName, resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state, legacyResult) { + function createResolvedModuleWithFailedLookupLocationsHandlingSymlink(moduleName, resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state, cache, legacyResult) { if (!state.resultFromCache && !state.compilerOptions.preserveSymlinks && resolved && isExternalLibraryImport && !resolved.originalPath && !isExternalModuleNameRelative(moduleName)) { const { resolvedFileName, originalPath } = getOriginalAndResolvedFileName(resolved.path, state.host, state.traceEnabled); if (originalPath) @@ -39138,15 +39313,25 @@ ${lanes.join("\n")} affectingLocations, diagnostics, state.resultFromCache, + cache, legacyResult ); } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, resultFromCache, legacyResult) { + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, resultFromCache, cache, legacyResult) { if (resultFromCache) { - resultFromCache.failedLookupLocations = updateResolutionField(resultFromCache.failedLookupLocations, failedLookupLocations); - resultFromCache.affectingLocations = updateResolutionField(resultFromCache.affectingLocations, affectingLocations); - resultFromCache.resolutionDiagnostics = updateResolutionField(resultFromCache.resolutionDiagnostics, diagnostics); - return resultFromCache; + if (!(cache == null ? void 0 : cache.isReadonly)) { + resultFromCache.failedLookupLocations = updateResolutionField(resultFromCache.failedLookupLocations, failedLookupLocations); + resultFromCache.affectingLocations = updateResolutionField(resultFromCache.affectingLocations, affectingLocations); + resultFromCache.resolutionDiagnostics = updateResolutionField(resultFromCache.resolutionDiagnostics, diagnostics); + return resultFromCache; + } else { + return { + ...resultFromCache, + failedLookupLocations: initializeResolutionFieldForReadonlyCache(resultFromCache.failedLookupLocations, failedLookupLocations), + affectingLocations: initializeResolutionFieldForReadonlyCache(resultFromCache.affectingLocations, affectingLocations), + resolutionDiagnostics: initializeResolutionFieldForReadonlyCache(resultFromCache.resolutionDiagnostics, diagnostics) + }; + } } return { resolvedModule: resolved && { @@ -39174,6 +39359,13 @@ ${lanes.join("\n")} to.push(...value); return to; } + function initializeResolutionFieldForReadonlyCache(fromCache, value) { + if (!(fromCache == null ? void 0 : fromCache.length)) + return initializeResolutionField(value); + if (!value.length) + return fromCache.slice(); + return [...fromCache, ...value]; + } function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { if (!hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { @@ -39349,10 +39541,14 @@ ${lanes.join("\n")} const failedLookupLocations = []; const affectingLocations = []; let features = getNodeResolutionFeatures(options); - if (resolutionMode === 99 /* ESNext */ && (getEmitModuleResolutionKind(options) === 3 /* Node16 */ || getEmitModuleResolutionKind(options) === 99 /* NodeNext */)) { + if (resolutionMode !== void 0) { + features |= 30 /* AllFeatures */; + } + const moduleResolution = getEmitModuleResolutionKind(options); + if (resolutionMode === 99 /* ESNext */ && (3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */)) { features |= 32 /* EsmMode */; } - const conditions = features & 8 /* Exports */ ? getConditions(options, !!(features & 32 /* EsmMode */)) : []; + const conditions = features & 8 /* Exports */ ? getConditions(options, resolutionMode) : []; const diagnostics = []; const moduleResolutionState = { compilerOptions: options, @@ -39394,15 +39590,15 @@ ${lanes.join("\n")} affectingLocations: initializeResolutionField(affectingLocations), resolutionDiagnostics: initializeResolutionField(diagnostics) }; - if (containingDirectory) { - cache == null ? void 0 : cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set( + if (containingDirectory && cache && !cache.isReadonly) { + cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set( typeReferenceDirectiveName, /*mode*/ resolutionMode, result ); if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) { - cache == null ? void 0 : cache.getOrCreateCacheForNonRelativeName(typeReferenceDirectiveName, resolutionMode, redirectedReference).set(containingDirectory, result); + cache.getOrCreateCacheForNonRelativeName(typeReferenceDirectiveName, resolutionMode, redirectedReference).set(containingDirectory, result); } } if (traceEnabled) @@ -39443,12 +39639,7 @@ ${lanes.join("\n")} } } return resolvedTypeScriptOnly( - loadNodeModuleFromDirectory( - 4 /* Declaration */, - candidate, - !directoryExists, - moduleResolutionState - ) + loadNodeModuleFromDirectory(4 /* Declaration */, candidate, !directoryExists, moduleResolutionState) ); }); } else { @@ -39525,12 +39716,20 @@ ${lanes.join("\n")} } return features; } - function getConditions(options, esmMode) { - const conditions = esmMode || getEmitModuleResolutionKind(options) === 100 /* Bundler */ ? ["import"] : ["require"]; + function getConditions(options, resolutionMode) { + const moduleResolution = getEmitModuleResolutionKind(options); + if (resolutionMode === void 0) { + if (moduleResolution === 100 /* Bundler */) { + resolutionMode = 99 /* ESNext */; + } else if (moduleResolution === 2 /* Node10 */) { + return []; + } + } + const conditions = resolutionMode === 99 /* ESNext */ ? ["import"] : ["require"]; if (!options.noDtsResolution) { conditions.push("types"); } - if (getEmitModuleResolutionKind(options) !== 100 /* Bundler */) { + if (moduleResolution !== 100 /* Bundler */) { conditions.push("node"); } return concatenate(conditions, options.customConditions); @@ -39596,9 +39795,8 @@ ${lanes.join("\n")} function getKeyForCompilerOptions(options, affectingOptionDeclarations) { return affectingOptionDeclarations.map((option) => compilerOptionValueToString(getCompilerOptionValue(options, option))).join("|") + `|${options.pathsBasePath}`; } - function createCacheWithRedirects(ownOptions) { + function createCacheWithRedirects(ownOptions, optionsToRedirectsKey) { const redirectsMap = /* @__PURE__ */ new Map(); - const optionsToRedirectsKey = /* @__PURE__ */ new Map(); const redirectsKeyToMap = /* @__PURE__ */ new Map(); let ownMap = /* @__PURE__ */ new Map(); if (ownOptions) @@ -39607,7 +39805,8 @@ ${lanes.join("\n")} getMapOfCacheRedirects, getOrCreateMapOfCacheRedirects, update, - clear: clear2 + clear: clear2, + getOwnMap: () => ownMap }; function getMapOfCacheRedirects(redirectedReference) { return redirectedReference ? getOrCreateMap( @@ -39708,13 +39907,14 @@ ${lanes.join("\n")} } return result; } - function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, options) { - const directoryToModuleNameMap = createCacheWithRedirects(options); + function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, options, optionsToRedirectsKey) { + const directoryToModuleNameMap = createCacheWithRedirects(options, optionsToRedirectsKey); return { getFromDirectoryCache, getOrCreateCacheForDirectory, clear: clear2, - update + update, + directoryToModuleNameMap }; function clear2() { directoryToModuleNameMap.clear(); @@ -39770,23 +39970,14 @@ ${lanes.join("\n")} return result; } } - function zipToModeAwareCache(file, keys, values, nameAndModeGetter) { - Debug.assert(keys.length === values.length); - const map2 = createModeAwareCache(); - for (let i = 0; i < keys.length; ++i) { - const entry = keys[i]; - map2.set(nameAndModeGetter.getName(entry), nameAndModeGetter.getMode(entry, file), values[i]); - } - return map2; - } function getOriginalOrResolvedModuleFileName(result) { return result.resolvedModule && (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); } function getOriginalOrResolvedTypeReferenceFileName(result) { return result.resolvedTypeReferenceDirective && (result.resolvedTypeReferenceDirective.originalPath || result.resolvedTypeReferenceDirective.resolvedFileName); } - function createNonRelativeNameResolutionCache(currentDirectory, getCanonicalFileName, options, getResolvedFileName) { - const moduleNameToDirectoryMap = createCacheWithRedirects(options); + function createNonRelativeNameResolutionCache(currentDirectory, getCanonicalFileName, options, getResolvedFileName, optionsToRedirectsKey) { + const moduleNameToDirectoryMap = createCacheWithRedirects(options, optionsToRedirectsKey); return { getFromNonRelativeNameCache, getOrCreateCacheForNonRelativeName, @@ -39854,13 +40045,20 @@ ${lanes.join("\n")} } } } - function createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, getResolvedFileName) { - const perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, options); + function createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, getResolvedFileName, optionsToRedirectsKey) { + optionsToRedirectsKey ?? (optionsToRedirectsKey = /* @__PURE__ */ new Map()); + const perDirectoryResolutionCache = createPerDirectoryResolutionCache( + currentDirectory, + getCanonicalFileName, + options, + optionsToRedirectsKey + ); const nonRelativeNameResolutionCache = createNonRelativeNameResolutionCache( currentDirectory, getCanonicalFileName, options, - getResolvedFileName + getResolvedFileName, + optionsToRedirectsKey ); packageJsonInfoCache ?? (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); return { @@ -39870,7 +40068,8 @@ ${lanes.join("\n")} clear: clear2, update, getPackageJsonInfoCache: () => packageJsonInfoCache, - clearAllExceptPackageJsonInfoCache + clearAllExceptPackageJsonInfoCache, + optionsToRedirectsKey }; function clear2() { clearAllExceptPackageJsonInfoCache(); @@ -39885,24 +40084,26 @@ ${lanes.join("\n")} nonRelativeNameResolutionCache.update(options2); } } - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache) { + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, optionsToRedirectsKey) { const result = createModuleOrTypeReferenceResolutionCache( currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, - getOriginalOrResolvedModuleFileName + getOriginalOrResolvedModuleFileName, + optionsToRedirectsKey ); result.getOrCreateCacheForModuleName = (nonRelativeName, mode, redirectedReference) => result.getOrCreateCacheForNonRelativeName(nonRelativeName, mode, redirectedReference); return result; } - function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache) { + function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, optionsToRedirectsKey) { return createModuleOrTypeReferenceResolutionCache( currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, - getOriginalOrResolvedTypeReferenceFileName + getOriginalOrResolvedTypeReferenceFileName, + optionsToRedirectsKey ); } function getOptionsForLibraryResolution(options) { @@ -39973,13 +40174,13 @@ ${lanes.join("\n")} result = nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); break; case 2 /* Node10 */: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode ? getConditions(compilerOptions, resolutionMode) : void 0); break; case 1 /* Classic */: result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; case 100 /* Bundler */: - result = bundlerModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + result = bundlerModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode ? getConditions(compilerOptions, resolutionMode) : void 0); break; default: return Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`); @@ -39987,9 +40188,11 @@ ${lanes.join("\n")} if (result && result.resolvedModule) (_b = perfLogger) == null ? void 0 : _b.logInfoEvent(`Module "${moduleName}" resolved to "${result.resolvedModule.resolvedFileName}"`); (_c = perfLogger) == null ? void 0 : _c.logStopResolveModule(result && result.resolvedModule ? "" + result.resolvedModule.resolvedFileName : "null"); - cache == null ? void 0 : cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set(moduleName, resolutionMode, result); - if (!isExternalModuleNameRelative(moduleName)) { - cache == null ? void 0 : cache.getOrCreateCacheForNonRelativeName(moduleName, resolutionMode, redirectedReference).set(containingDirectory, result); + if (cache && !cache.isReadonly) { + cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set(moduleName, resolutionMode, result); + if (!isExternalModuleNameRelative(moduleName)) { + cache.getOrCreateCacheForNonRelativeName(moduleName, resolutionMode, redirectedReference).set(containingDirectory, result); + } } } if (traceEnabled) { @@ -40144,7 +40347,7 @@ ${lanes.join("\n")} resolutionMode ); } - function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { + function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode, conditions) { const containingDirectory = getDirectoryPath(containingFile); const esmMode = resolutionMode === 99 /* ESNext */ ? 32 /* EsmMode */ : 0; let extensions = compilerOptions.noDtsResolution ? 3 /* ImplementationFiles */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */; @@ -40161,7 +40364,8 @@ ${lanes.join("\n")} extensions, /*isConfigLookup*/ false, - redirectedReference + redirectedReference, + conditions ); } function tryResolveJSModuleWorker(moduleName, initialDir, host) { @@ -40177,10 +40381,12 @@ ${lanes.join("\n")} /*isConfigLookup*/ false, /*redirectedReference*/ + void 0, + /*conditions*/ void 0 ); } - function bundlerModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + function bundlerModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, conditions) { const containingDirectory = getDirectoryPath(containingFile); let extensions = compilerOptions.noDtsResolution ? 3 /* ImplementationFiles */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */; if (getResolveJsonModule(compilerOptions)) { @@ -40196,10 +40402,11 @@ ${lanes.join("\n")} extensions, /*isConfigLookup*/ false, - redirectedReference + redirectedReference, + conditions ); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, isConfigLookup) { + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, conditions, isConfigLookup) { let extensions; if (isConfigLookup) { extensions = 8 /* Json */; @@ -40210,7 +40417,7 @@ ${lanes.join("\n")} } else { extensions = getResolveJsonModule(compilerOptions) ? 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */ | 8 /* Json */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */; } - return nodeModuleNameResolverWorker(0 /* None */, moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, extensions, !!isConfigLookup, redirectedReference); + return nodeModuleNameResolverWorker(conditions ? 30 /* AllFeatures */ : 0 /* None */, moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, extensions, !!isConfigLookup, redirectedReference, conditions); } function nodeNextJsonConfigResolver(moduleName, containingFile, host) { return nodeModuleNameResolverWorker( @@ -40225,15 +40432,21 @@ ${lanes.join("\n")} /*isConfigLookup*/ true, /*redirectedReference*/ + void 0, + /*conditions*/ void 0 ); } - function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, compilerOptions, host, cache, extensions, isConfigLookup, redirectedReference) { + function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, compilerOptions, host, cache, extensions, isConfigLookup, redirectedReference, conditions) { var _a, _b, _c, _d; const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations = []; const affectingLocations = []; - const conditions = getConditions(compilerOptions, !!(features & 32 /* EsmMode */)); + const moduleResolution = getEmitModuleResolutionKind(compilerOptions); + conditions ?? (conditions = getConditions( + compilerOptions, + moduleResolution === 100 /* Bundler */ || moduleResolution === 2 /* Node10 */ ? void 0 : features & 32 /* EsmMode */ ? 99 /* ESNext */ : 1 /* CommonJS */ + )); const diagnostics = []; const state = { compilerOptions, @@ -40243,17 +40456,17 @@ ${lanes.join("\n")} affectingLocations, packageJsonInfoCache: cache, features, - conditions, + conditions: conditions ?? emptyArray, requestContainingDirectory: containingDirectory, reportDiagnostic: (diag2) => void diagnostics.push(diag2), isConfigLookup, candidateIsFromPackageJsonField: false }; - if (traceEnabled && moduleResolutionSupportsPackageJsonExportsAndImports(getEmitModuleResolutionKind(compilerOptions))) { - trace(host, Diagnostics.Resolving_in_0_mode_with_conditions_1, features & 32 /* EsmMode */ ? "ESM" : "CJS", conditions.map((c) => `'${c}'`).join(", ")); + if (traceEnabled && moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) { + trace(host, Diagnostics.Resolving_in_0_mode_with_conditions_1, features & 32 /* EsmMode */ ? "ESM" : "CJS", state.conditions.map((c) => `'${c}'`).join(", ")); } let result; - if (getEmitModuleResolutionKind(compilerOptions) === 2 /* Node10 */) { + if (moduleResolution === 2 /* Node10 */) { const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */); const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */); result = priorityExtensions && tryResolve(priorityExtensions, state) || secondaryExtensions && tryResolve(secondaryExtensions, state) || void 0; @@ -40261,7 +40474,7 @@ ${lanes.join("\n")} result = tryResolve(extensions, state); } let legacyResult; - if (((_a = result == null ? void 0 : result.value) == null ? void 0 : _a.isExternalLibraryImport) && !isConfigLookup && extensions & (1 /* TypeScript */ | 4 /* Declaration */) && features & 8 /* Exports */ && !isExternalModuleNameRelative(moduleName) && !extensionIsOk(1 /* TypeScript */ | 4 /* Declaration */, result.value.resolved.extension) && conditions.indexOf("import") > -1) { + if (((_a = result == null ? void 0 : result.value) == null ? void 0 : _a.isExternalLibraryImport) && !isConfigLookup && extensions & (1 /* TypeScript */ | 4 /* Declaration */) && features & 8 /* Exports */ && !isExternalModuleNameRelative(moduleName) && !extensionIsOk(1 /* TypeScript */ | 4 /* Declaration */, result.value.resolved.extension) && (conditions == null ? void 0 : conditions.includes("import"))) { traceIfEnabled(state, Diagnostics.Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_if_npm_library_needs_configuration_update); const diagnosticState = { ...state, @@ -40281,6 +40494,7 @@ ${lanes.join("\n")} affectingLocations, diagnostics, state, + cache, legacyResult ); function tryResolve(extensions2, state2) { @@ -40305,7 +40519,7 @@ ${lanes.join("\n")} resolved2 = loadModuleFromSelfNameReference(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); } if (!resolved2) { - if (moduleName.indexOf(":") > -1) { + if (moduleName.includes(":")) { if (traceEnabled) { trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); } @@ -40350,7 +40564,6 @@ ${lanes.join("\n")} if (traceEnabled) { trace(host, Diagnostics.Resolving_real_path_for_0_result_1, path, real); } - Debug.assert(host.fileExists(real), `${path} linked to nonexistent file ${real}`); return real; } function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { @@ -40394,7 +40607,7 @@ ${lanes.join("\n")} return void 0; } function pathContainsNodeModules(path) { - return stringContains(path, nodeModulesPathPart); + return path.includes(nodeModulesPathPart); } function parseNodeModuleFromPath(resolved, isFolder) { const path = normalizePath(resolved); @@ -40430,7 +40643,7 @@ ${lanes.join("\n")} } function loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state) { const filename = getBaseFileName(candidate); - if (filename.indexOf(".") === -1) { + if (!filename.includes(".")) { return void 0; } let extensionless = removeFileExtension(candidate); @@ -40542,15 +40755,7 @@ ${lanes.join("\n")} entrypoints = append(entrypoints, mainResolution == null ? void 0 : mainResolution.path); if (features & 8 /* Exports */ && packageJsonInfo.contents.packageJsonContent.exports) { const conditionSets = deduplicate( - [getConditions( - options, - /*esmMode*/ - true - ), getConditions( - options, - /*esmMode*/ - false - )], + [getConditions(options, 99 /* ESNext */), getConditions(options, 1 /* CommonJS */)], arrayIsEqualTo ); for (const conditions of conditionSets) { @@ -40587,7 +40792,7 @@ ${lanes.join("\n")} function loadEntrypointsFromTargetExports(target) { var _a, _b; if (typeof target === "string" && startsWith(target, "./")) { - if (target.indexOf("*") >= 0 && state.host.readDirectory) { + if (target.includes("*") && state.host.readDirectory) { if (target.indexOf("*") !== target.lastIndexOf("*")) { return false; } @@ -40596,7 +40801,9 @@ ${lanes.join("\n")} extensionsToExtensionsArray(extensions), /*excludes*/ void 0, - [changeAnyExtension(target.replace("*", "**/*"), getDeclarationEmitExtensionForPath(target))] + [ + isDeclarationFileName(target) ? target.replace("*", "**/*") : changeAnyExtension(target.replace("*", "**/*"), getDeclarationEmitExtensionForPath(target)) + ] ).forEach((entry) => { entrypoints = appendIfUnique(entrypoints, { path: entry, @@ -40606,7 +40813,7 @@ ${lanes.join("\n")} }); } else { const partsAfterFirst = getPathComponents(target).slice(2); - if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) { + if (partsAfterFirst.includes("..") || partsAfterFirst.includes(".") || partsAfterFirst.includes("node_modules")) { return false; } const resolvedTarget = combinePaths(scope.packageDirectory, target); @@ -40680,7 +40887,7 @@ ${lanes.join("\n")} return packageJsonInfo.contents.versionPaths || void 0; } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { - var _a, _b, _c, _d, _e, _f, _g, _h; + var _a, _b, _c, _d, _e, _f; const { host, traceEnabled } = state; const packageJsonPath = combinePaths(packageDirectory, "package.json"); if (onlyRecordFailures) { @@ -40708,15 +40915,17 @@ ${lanes.join("\n")} trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath); } const result = { packageDirectory, contents: { packageJsonContent, versionPaths: void 0, resolvedEntrypoints: void 0 } }; - (_e = state.packageJsonInfoCache) == null ? void 0 : _e.setPackageJsonInfo(packageJsonPath, result); - (_f = state.affectingLocations) == null ? void 0 : _f.push(packageJsonPath); + if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) + state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, result); + (_e = state.affectingLocations) == null ? void 0 : _e.push(packageJsonPath); return result; } else { if (directoryExists && traceEnabled) { trace(host, Diagnostics.File_0_does_not_exist, packageJsonPath); } - (_g = state.packageJsonInfoCache) == null ? void 0 : _g.setPackageJsonInfo(packageJsonPath, directoryExists); - (_h = state.failedLookupLocations) == null ? void 0 : _h.push(packageJsonPath); + if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) + state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, directoryExists); + (_f = state.failedLookupLocations) == null ? void 0 : _f.push(packageJsonPath); } } function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { @@ -40974,7 +41183,7 @@ ${lanes.join("\n")} } function loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) { const loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); - if (!endsWith(moduleName, directorySeparator) && moduleName.indexOf("*") === -1 && hasProperty(lookupTable, moduleName)) { + if (!endsWith(moduleName, directorySeparator) && !moduleName.includes("*") && hasProperty(lookupTable, moduleName)) { const target = lookupTable[moduleName]; return loadModuleFromTargetImportOrExport( target, @@ -40985,7 +41194,7 @@ ${lanes.join("\n")} moduleName ); } - const expandingKeys = sort(filter(getOwnKeys(lookupTable), (k) => k.indexOf("*") !== -1 || endsWith(k, "/")), comparePatternKeys); + const expandingKeys = sort(filter(getOwnKeys(lookupTable), (k) => k.includes("*") || endsWith(k, "/")), comparePatternKeys); for (const potentialTarget of expandingKeys) { if (state.features & 16 /* ExportsPatternTrailers */ && matchesPatternWithTrailer(potentialTarget, moduleName)) { const target = lookupTable[potentialTarget]; @@ -41057,15 +41266,18 @@ ${lanes.join("\n")} extensions, /*isConfigLookup*/ false, - redirectedReference + redirectedReference, + state.conditions + ); + return toSearchResult( + result.resolvedModule ? { + path: result.resolvedModule.resolvedFileName, + extension: result.resolvedModule.extension, + packageId: result.resolvedModule.packageId, + originalPath: result.resolvedModule.originalPath, + resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension + } : void 0 ); - return toSearchResult(result.resolvedModule ? { - path: result.resolvedModule.resolvedFileName, - extension: result.resolvedModule.extension, - packageId: result.resolvedModule.packageId, - originalPath: result.resolvedModule.originalPath, - resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension - } : void 0); } if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); @@ -41077,7 +41289,7 @@ ${lanes.join("\n")} } const parts = pathIsRelative(target) ? getPathComponents(target).slice(1) : getPathComponents(target); const partsAfterFirst = parts.slice(1); - if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) { + if (partsAfterFirst.includes("..") || partsAfterFirst.includes(".") || partsAfterFirst.includes("node_modules")) { if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); } @@ -41088,7 +41300,7 @@ ${lanes.join("\n")} } const resolvedTarget = combinePaths(scope.packageDirectory, target); const subpathParts = getPathComponents(subpath); - if (subpathParts.indexOf("..") >= 0 || subpathParts.indexOf(".") >= 0 || subpathParts.indexOf("node_modules") >= 0) { + if (subpathParts.includes("..") || subpathParts.includes(".") || subpathParts.includes("node_modules")) { if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); } @@ -41098,13 +41310,7 @@ ${lanes.join("\n")} ); } if (state.traceEnabled) { - trace( - state.host, - Diagnostics.Using_0_subpath_1_with_target_2, - isImports ? "imports" : "exports", - key, - pattern ? target.replace(/\*/g, subpath) : target + subpath - ); + trace(state.host, Diagnostics.Using_0_subpath_1_with_target_2, isImports ? "imports" : "exports", key, pattern ? target.replace(/\*/g, subpath) : target + subpath); } const finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath); const inputLink = tryLoadInputFileForPath(finalPath, subpath, combinePaths(scope.packageDirectory, "package.json"), isImports); @@ -41121,7 +41327,7 @@ ${lanes.join("\n")} if (!Array.isArray(target)) { traceIfEnabled(state, Diagnostics.Entering_conditional_exports); for (const condition of getOwnKeys(target)) { - if (condition === "default" || state.conditions.indexOf(condition) >= 0 || isApplicableVersionedTypesKey(state.conditions, condition)) { + if (condition === "default" || state.conditions.includes(condition) || isApplicableVersionedTypesKey(state.conditions, condition)) { traceIfEnabled(state, Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition); const subTarget = target[condition]; const result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern, key); @@ -41182,7 +41388,7 @@ ${lanes.join("\n")} } 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(state)) : true)) { + if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && !finalPath.includes("/node_modules/") && (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) { @@ -41256,7 +41462,7 @@ ${lanes.join("\n")} } } function isApplicableVersionedTypesKey(conditions, key) { - if (conditions.indexOf("types") === -1) + if (!conditions.includes("types")) return false; if (!startsWith(key, "types@")) return false; @@ -41460,7 +41666,7 @@ ${lanes.join("\n")} return mangledName; } function unmangleScopedPackageName(typesPackageName) { - return stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, directorySeparator) : typesPackageName; + return typesPackageName.includes(mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, directorySeparator) : typesPackageName; } function tryFindNonRelativeModuleNameInCache(cache, moduleName, mode, containingDirectory, redirectedReference, state) { const result = cache && cache.getFromNonRelativeNameCache(moduleName, mode, containingDirectory, redirectedReference); @@ -41508,7 +41714,8 @@ ${lanes.join("\n")} failedLookupLocations, affectingLocations, diagnostics, - state + state, + cache ); function tryResolve(extensions) { const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); @@ -41627,7 +41834,9 @@ ${lanes.join("\n")} failedLookupLocations, affectingLocations, diagnostics, - state.resultFromCache + state.resultFromCache, + /*cache*/ + void 0 ); } function toSearchResult(value) { @@ -41699,7 +41908,7 @@ ${lanes.join("\n")} break; case 272 /* ImportDeclaration */: case 271 /* ImportEqualsDeclaration */: - if (!hasSyntacticModifier(node, 1 /* Export */)) { + if (!hasSyntacticModifier(node, 32 /* Export */)) { return 0 /* NonInstantiated */; } break; @@ -41976,7 +42185,7 @@ ${lanes.join("\n")} } function declareSymbol(symbolTable, parent3, node, includes, excludes, isReplaceableByMethod, isComputedName) { Debug.assert(isComputedName || !hasDynamicName(node)); - const isDefaultExport = hasSyntacticModifier(node, 1024 /* Default */) || isExportSpecifier(node) && node.name.escapedText === "default"; + const isDefaultExport = hasSyntacticModifier(node, 2048 /* Default */) || isExportSpecifier(node) && node.name.escapedText === "default"; const name = isComputedName ? "__computed" /* Computed */ : isDefaultExport && parent3 ? "default" /* Default */ : getDeclarationName(node); let symbol; if (name === void 0) { @@ -42020,7 +42229,7 @@ ${lanes.join("\n")} } } const relatedInformation = []; - if (isTypeAliasDeclaration(node) && nodeIsMissing(node.type) && hasSyntacticModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) { + if (isTypeAliasDeclaration(node) && nodeIsMissing(node.type) && hasSyntacticModifier(node, 32 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) { relatedInformation.push(createDiagnosticForNode2(node, Diagnostics.Did_you_mean_0, `export type { ${unescapeLeadingUnderscores(node.name.escapedText)} }`)); } const declarationName = getNameOfDeclaration(node) || node; @@ -42049,7 +42258,7 @@ ${lanes.join("\n")} return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { - const hasExportModifier = !!(getCombinedModifierFlags(node) & 1 /* Export */) || jsdocTreatAsExported(node); + const hasExportModifier = !!(getCombinedModifierFlags(node) & 32 /* Export */) || jsdocTreatAsExported(node); if (symbolFlags & 2097152 /* Alias */) { if (node.kind === 281 /* ExportSpecifier */ || node.kind === 271 /* ImportEqualsDeclaration */ && hasExportModifier) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -42068,7 +42277,7 @@ ${lanes.join("\n")} if (isJSDocTypeAlias(node)) Debug.assert(isInJSFile(node)); if (!isAmbientModule(node) && (hasExportModifier || container.flags & 128 /* ExportContext */)) { - if (!canHaveLocals(container) || !container.locals || hasSyntacticModifier(node, 1024 /* Default */) && !getDeclarationName(node)) { + if (!canHaveLocals(container) || !container.locals || hasSyntacticModifier(node, 2048 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } const exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0; @@ -42109,7 +42318,7 @@ ${lanes.join("\n")} return false; if (isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent)) return true; - if (isDeclaration(declName.parent) && getCombinedModifierFlags(declName.parent) & 1 /* Export */) + if (isDeclaration(declName.parent) && getCombinedModifierFlags(declName.parent) & 32 /* Export */) return true; return false; } @@ -42140,7 +42349,7 @@ ${lanes.join("\n")} const saveExceptionTarget = currentExceptionTarget; const saveActiveLabelList = activeLabelList; const saveHasExplicitReturn = hasExplicitReturn; - const isImmediatelyInvoked = containerFlags & 16 /* IsFunctionExpression */ && !hasSyntacticModifier(node, 512 /* Async */) && !node.asteriskToken && !!getImmediatelyInvokedFunctionExpression(node) || node.kind === 175 /* ClassStaticBlockDeclaration */; + const isImmediatelyInvoked = containerFlags & 16 /* IsFunctionExpression */ && !hasSyntacticModifier(node, 1024 /* Async */) && !node.asteriskToken && !!getImmediatelyInvokedFunctionExpression(node) || node.kind === 175 /* ClassStaticBlockDeclaration */; if (!isImmediatelyInvoked) { currentFlow = initFlowNode({ flags: 2 /* Start */ }); if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */)) { @@ -42381,7 +42590,7 @@ ${lanes.join("\n")} case 36 /* ExclamationEqualsToken */: case 37 /* EqualsEqualsEqualsToken */: case 38 /* ExclamationEqualsEqualsToken */: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || (isBooleanLiteral(expr.right) && isNarrowingExpression(expr.left) || isBooleanLiteral(expr.left) && isNarrowingExpression(expr.right)); case 104 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); case 103 /* InKeyword */: @@ -42701,7 +42910,7 @@ ${lanes.join("\n")} } function bindCaseBlock(node) { const clauses = node.clauses; - const isNarrowingSwitch = isNarrowingExpression(node.parent.expression); + const isNarrowingSwitch = node.parent.expression.kind === 112 /* TrueKeyword */ || isNarrowingExpression(node.parent.expression); let fallthroughFlow = unreachableFlow; for (let i = 0; i < clauses.length; i++) { const clauseStart = i; @@ -43187,7 +43396,7 @@ ${lanes.join("\n")} function bindModuleDeclaration(node) { setExportContextFlag(node); if (isAmbientModule(node)) { - if (hasSyntacticModifier(node, 1 /* Export */)) { + if (hasSyntacticModifier(node, 32 /* Export */)) { errorOnFirstToken(node, Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); } if (isModuleAugmentationExternal(node)) { @@ -43348,31 +43557,15 @@ ${lanes.join("\n")} return; } if (inStrictMode && originalKeywordKind >= 119 /* FirstFutureReservedWord */ && originalKeywordKind <= 127 /* LastFutureReservedWord */) { - file.bindDiagnostics.push(createDiagnosticForNode2( - node, - getStrictModeIdentifierMessage(node), - declarationNameToString(node) - )); + file.bindDiagnostics.push(createDiagnosticForNode2(node, getStrictModeIdentifierMessage(node), declarationNameToString(node))); } else if (originalKeywordKind === 135 /* AwaitKeyword */) { if (isExternalModule(file) && isInTopLevelContext(node)) { - file.bindDiagnostics.push(createDiagnosticForNode2( - node, - Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, - declarationNameToString(node) - )); + file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, declarationNameToString(node))); } else if (node.flags & 65536 /* AwaitContext */) { - file.bindDiagnostics.push(createDiagnosticForNode2( - node, - Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, - declarationNameToString(node) - )); + file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node))); } } else if (originalKeywordKind === 127 /* YieldKeyword */ && node.flags & 16384 /* YieldContext */) { - file.bindDiagnostics.push(createDiagnosticForNode2( - node, - Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, - declarationNameToString(node) - )); + file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node))); } } } @@ -43388,11 +43581,7 @@ ${lanes.join("\n")} function checkPrivateIdentifier(node) { if (node.escapedText === "#constructor") { if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(createDiagnosticForNode2( - node, - Diagnostics.constructor_is_a_reserved_word, - declarationNameToString(node) - )); + file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.constructor_is_a_reserved_word, declarationNameToString(node))); } } } @@ -43420,13 +43609,7 @@ ${lanes.join("\n")} const identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { const span = getErrorSpanForNode(file, name); - file.bindDiagnostics.push(createFileDiagnostic( - file, - span.start, - span.length, - getStrictModeEvalOrArgumentsMessage(contextNode), - idText(identifier) - )); + file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), idText(identifier))); } } } @@ -43457,12 +43640,7 @@ ${lanes.join("\n")} if (languageVersion < 2 /* ES2015 */) { if (blockScopeContainer.kind !== 312 /* SourceFile */ && blockScopeContainer.kind !== 267 /* ModuleDeclaration */ && !isFunctionLikeOrClassStaticBlockDeclaration(blockScopeContainer)) { const errorSpan = getErrorSpanForNode(file, node); - file.bindDiagnostics.push(createFileDiagnostic( - file, - errorSpan.start, - errorSpan.length, - getStrictModeBlockScopeFunctionDeclarationMessage(node) - )); + file.bindDiagnostics.push(createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); } } } @@ -43693,11 +43871,7 @@ ${lanes.join("\n")} return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); case 174 /* MethodDeclaration */: case 173 /* MethodSignature */: - return bindPropertyOrMethodOrAccessor( - node, - 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), - isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */ - ); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */); case 262 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 176 /* Constructor */: @@ -44283,7 +44457,7 @@ ${lanes.join("\n")} } if (!isBindingPattern(node.name)) { const possibleVariableDecl = node.kind === 260 /* VariableDeclaration */ ? node : node.parent.parent; - if (isInJSFile(node) && shouldResolveJsRequire(options) && isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && !getJSDocTypeTag(node) && !(getCombinedModifierFlags(node) & 1 /* Export */)) { + if (isInJSFile(node) && shouldResolveJsRequire(options) && isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && !getJSDocTypeTag(node) && !(getCombinedModifierFlags(node) & 32 /* Export */)) { declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } else if (isBlockOrCatchScoped(node)) { bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */); @@ -44435,7 +44609,7 @@ ${lanes.join("\n")} case 267 /* ModuleDeclaration */: return getModuleInstanceState(s) !== 1 /* Instantiated */; case 266 /* EnumDeclaration */: - return hasSyntacticModifier(s, 2048 /* Const */); + return hasSyntacticModifier(s, 4096 /* Const */); default: return false; } @@ -44778,20 +44952,17 @@ ${lanes.join("\n")} function getNodeModulesPackageName(compilerOptions, importingSourceFile, nodeModulesFileName, host, preferences, options = {}) { const info = getInfo(importingSourceFile.path, host); const modulePaths = getAllModulePaths(importingSourceFile.path, nodeModulesFileName, host, preferences, options); - return firstDefined( - modulePaths, - (modulePath) => tryGetModuleNameAsNodeModule( - modulePath, - info, - importingSourceFile, - host, - compilerOptions, - preferences, - /*packageNameOnly*/ - true, - options.overrideImportMode - ) - ); + return firstDefined(modulePaths, (modulePath) => tryGetModuleNameAsNodeModule( + modulePath, + info, + importingSourceFile, + host, + compilerOptions, + preferences, + /*packageNameOnly*/ + true, + options.overrideImportMode + )); } function getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName2, host, preferences, userPreferences, options = {}) { const info = getInfo(importingSourceFileName, host); @@ -44835,10 +45006,12 @@ ${lanes.join("\n")} importingSourceFile, host, userPreferences, - options + options, + /*forAutoImport*/ + false ).moduleSpecifiers; } - function getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options = {}) { + function getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) { let computedWithoutCache = false; const ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker); if (ambient) @@ -44856,11 +45029,19 @@ ${lanes.join("\n")} return { moduleSpecifiers: emptyArray, computedWithoutCache }; computedWithoutCache = true; modulePaths || (modulePaths = getAllModulePathsWorker(importingSourceFile.path, moduleSourceFile.originalFileName, host)); - const result = computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFile, host, userPreferences, options); + const result = computeModuleSpecifiers( + modulePaths, + compilerOptions, + importingSourceFile, + host, + userPreferences, + options, + forAutoImport + ); cache == null ? void 0 : cache.set(importingSourceFile.path, moduleSourceFile.path, userPreferences, options, modulePaths, result); return { moduleSpecifiers: result, computedWithoutCache }; } - function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFile, host, userPreferences, options = {}) { + function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) { const info = getInfo(importingSourceFile.path, host); const preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); const existingSpecifier = forEach(modulePaths, (modulePath) => forEach( @@ -44917,7 +45098,7 @@ ${lanes.join("\n")} redirectPathsSpecifiers = append(redirectPathsSpecifiers, local); } else if (pathIsBareSpecifier(local)) { pathsSpecifiers = append(pathsSpecifiers, local); - } else if (!importedFileIsInNodeModules || modulePath.isInNodeModules) { + } else if (forAutoImport || !importedFileIsInNodeModules || modulePath.isInNodeModules) { relativeSpecifiers = append(relativeSpecifiers, local); } } @@ -45100,32 +45281,29 @@ ${lanes.join("\n")} if (decl) { return decl.name.text; } - const ambientModuleDeclareCandidates = mapDefined( - moduleSymbol.declarations, - (d) => { - var _a2, _b, _c, _d; - if (!isModuleDeclaration(d)) - return; - const topNamespace = getTopNamespace(d); - if (!(((_a2 = topNamespace == null ? void 0 : topNamespace.parent) == null ? void 0 : _a2.parent) && isModuleBlock(topNamespace.parent) && isAmbientModule(topNamespace.parent.parent) && isSourceFile(topNamespace.parent.parent.parent))) - return; - const exportAssignment = (_d = (_c = (_b = topNamespace.parent.parent.symbol.exports) == null ? void 0 : _b.get("export=")) == null ? void 0 : _c.valueDeclaration) == null ? void 0 : _d.expression; - if (!exportAssignment) - return; - const exportSymbol = checker.getSymbolAtLocation(exportAssignment); - if (!exportSymbol) - return; - const originalExportSymbol = (exportSymbol == null ? void 0 : exportSymbol.flags) & 2097152 /* Alias */ ? checker.getAliasedSymbol(exportSymbol) : exportSymbol; - if (originalExportSymbol === d.symbol) - return topNamespace.parent.parent; - function getTopNamespace(namespaceDeclaration) { - while (namespaceDeclaration.flags & 8 /* NestedNamespace */) { - namespaceDeclaration = namespaceDeclaration.parent; - } - return namespaceDeclaration; + const ambientModuleDeclareCandidates = mapDefined(moduleSymbol.declarations, (d) => { + var _a2, _b, _c, _d; + if (!isModuleDeclaration(d)) + return; + const topNamespace = getTopNamespace(d); + if (!(((_a2 = topNamespace == null ? void 0 : topNamespace.parent) == null ? void 0 : _a2.parent) && isModuleBlock(topNamespace.parent) && isAmbientModule(topNamespace.parent.parent) && isSourceFile(topNamespace.parent.parent.parent))) + return; + const exportAssignment = (_d = (_c = (_b = topNamespace.parent.parent.symbol.exports) == null ? void 0 : _b.get("export=")) == null ? void 0 : _c.valueDeclaration) == null ? void 0 : _d.expression; + if (!exportAssignment) + return; + const exportSymbol = checker.getSymbolAtLocation(exportAssignment); + if (!exportSymbol) + return; + const originalExportSymbol = (exportSymbol == null ? void 0 : exportSymbol.flags) & 2097152 /* Alias */ ? checker.getAliasedSymbol(exportSymbol) : exportSymbol; + if (originalExportSymbol === d.symbol) + return topNamespace.parent.parent; + function getTopNamespace(namespaceDeclaration) { + while (namespaceDeclaration.flags & 8 /* NestedNamespace */) { + namespaceDeclaration = namespaceDeclaration.parent; } + return namespaceDeclaration; } - ); + }); const ambientModuleDeclare = ambientModuleDeclareCandidates[0]; if (ambientModuleDeclare) { return ambientModuleDeclare.name.text; @@ -45216,12 +45394,12 @@ ${lanes.join("\n")} /*currentDirectory*/ void 0 ); - const mode2 = endsWith(k, "/") ? 1 /* Directory */ : stringContains(k, "*") ? 2 /* Pattern */ : 0 /* Exact */; + const mode2 = endsWith(k, "/") ? 1 /* Directory */ : k.includes("*") ? 2 /* Pattern */ : 0 /* Exact */; return tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, subPackageName, exports[k], conditions, mode2); }); } else { for (const key of getOwnKeys(exports)) { - if (key === "default" || conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(conditions, key)) { + if (key === "default" || conditions.includes(key) || isApplicableVersionedTypesKey(conditions, key)) { const subTarget = exports[key]; const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions, mode); if (result) { @@ -45311,7 +45489,7 @@ ${lanes.join("\n")} if (getResolvePackageJsonExports(options)) { const nodeModulesDirectoryName2 = packageRootPath.substring(parts.topLevelPackageNameIndex + 1); const packageName2 = getPackageNameFromTypesPackageName(nodeModulesDirectoryName2); - const conditions = getConditions(options, importMode === 99 /* ESNext */); + const conditions = getConditions(options, importMode); const fromExports = packageJsonContent.exports ? tryGetModuleNameFromExports(options, path, packageRootPath, packageName2, packageJsonContent.exports, conditions) : void 0; if (fromExports) { const withJsExtension = !hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; @@ -45387,7 +45565,7 @@ ${lanes.join("\n")} return fileName; } else if (fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".d.cts" /* Dcts */, ".cts" /* Cts */])) { return noExtension + getJSExtensionForFile(fileName, options); - } else if (!fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */]) && fileExtensionIsOneOf(fileName, [".ts" /* Ts */]) && stringContains(fileName, ".d.")) { + } else if (!fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */]) && fileExtensionIsOneOf(fileName, [".ts" /* Ts */]) && fileName.includes(".d.")) { return tryGetRealFileNameForNonJsDeclarationFileName(fileName); } switch (allowedEndings[0]) { @@ -45413,7 +45591,7 @@ ${lanes.join("\n")} } function tryGetRealFileNameForNonJsDeclarationFileName(fileName) { const baseName = getBaseFileName(fileName); - if (!endsWith(fileName, ".ts" /* Ts */) || !stringContains(baseName, ".d.") || fileExtensionIsOneOf(baseName, [".d.ts" /* Dts */])) + if (!endsWith(fileName, ".ts" /* Ts */) || !baseName.includes(".d.") || fileExtensionIsOneOf(baseName, [".d.ts" /* Dts */])) return void 0; const noExtension = removeExtension(fileName, ".ts" /* Ts */); const ext = noExtension.substring(noExtension.lastIndexOf(".")); @@ -45521,7 +45699,7 @@ ${lanes.join("\n")} var externalHelpersModule; var Symbol47 = objectAllocator.getSymbolConstructor(); var Type27 = objectAllocator.getTypeConstructor(); - var Signature15 = objectAllocator.getSignatureConstructor(); + var Signature14 = objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; var totalInstantiationCount = 0; @@ -45758,24 +45936,7 @@ ${lanes.join("\n")} getTypeOfPropertyOfContextualType, getFullyQualifiedName, getResolvedSignature: (node, candidatesOutArray, argumentCount) => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */), - getResolvedSignatureForStringLiteralCompletions: (call, editingArgument, candidatesOutArray, checkMode = 32 /* IsForStringLiteralArgumentCompletions */) => { - if (checkMode & 32 /* IsForStringLiteralArgumentCompletions */) { - return runWithInferenceBlockedFromSourceNode(editingArgument, () => getResolvedSignatureWorker( - call, - candidatesOutArray, - /*argumentCount*/ - void 0, - checkMode & ~32 /* IsForStringLiteralArgumentCompletions */ - )); - } - return runWithoutResolvedSignatureCaching(editingArgument, () => getResolvedSignatureWorker( - call, - candidatesOutArray, - /*argumentCount*/ - void 0, - checkMode & ~32 /* IsForStringLiteralArgumentCompletions */ - )); - }, + getCandidateSignaturesForStringLiteralCompletions, getResolvedSignatureForSignatureHelp: (node, candidatesOutArray, argumentCount) => runWithoutResolvedSignatureCaching(node, () => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */)), getExpandedParameters, hasEffectiveRestParameter, @@ -45974,22 +46135,59 @@ ${lanes.join("\n")} isTypeParameterPossiblyReferenced, typeHasCallOrConstructSignatures }; + function getCandidateSignaturesForStringLiteralCompletions(call, editingArgument) { + const candidatesSet = /* @__PURE__ */ new Set(); + const candidates = []; + runWithInferenceBlockedFromSourceNode(editingArgument, () => getResolvedSignatureWorker( + call, + candidates, + /*argumentCount*/ + void 0, + 0 /* Normal */ + )); + for (const candidate of candidates) { + candidatesSet.add(candidate); + } + candidates.length = 0; + runWithoutResolvedSignatureCaching(editingArgument, () => getResolvedSignatureWorker( + call, + candidates, + /*argumentCount*/ + void 0, + 0 /* Normal */ + )); + for (const candidate of candidates) { + candidatesSet.add(candidate); + } + return arrayFrom(candidatesSet); + } function runWithoutResolvedSignatureCaching(node, fn) { - const cachedSignatures = []; - while (node) { - if (isCallLikeExpression(node)) { + node = findAncestor(node, isCallLikeOrFunctionLikeExpression); + if (node) { + const cachedResolvedSignatures = []; + const cachedTypes2 = []; + while (node) { const nodeLinks2 = getNodeLinks(node); - const resolvedSignature = nodeLinks2.resolvedSignature; - cachedSignatures.push([nodeLinks2, resolvedSignature]); + cachedResolvedSignatures.push([nodeLinks2, nodeLinks2.resolvedSignature]); nodeLinks2.resolvedSignature = void 0; + if (isFunctionExpressionOrArrowFunction(node)) { + const symbolLinks2 = getSymbolLinks(getSymbolOfDeclaration(node)); + const type = symbolLinks2.type; + cachedTypes2.push([symbolLinks2, type]); + symbolLinks2.type = void 0; + } + node = findAncestor(node.parent, isCallLikeOrFunctionLikeExpression); } - node = node.parent; + const result = fn(); + for (const [nodeLinks2, resolvedSignature] of cachedResolvedSignatures) { + nodeLinks2.resolvedSignature = resolvedSignature; + } + for (const [symbolLinks2, type] of cachedTypes2) { + symbolLinks2.type = type; + } + return result; } - const result = fn(); - for (const [nodeLinks2, resolvedSignature] of cachedSignatures) { - nodeLinks2.resolvedSignature = resolvedSignature; - } - return result; + return fn(); } function runWithInferenceBlockedFromSourceNode(node, fn) { const containingCall = findAncestor(node, isCallLikeExpression); @@ -46041,28 +46239,72 @@ ${lanes.join("\n")} var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */); var unresolvedSymbols = /* @__PURE__ */ new Map(); var errorTypes = /* @__PURE__ */ new Map(); + var seenIntrinsicNames = /* @__PURE__ */ new Set(); var anyType = createIntrinsicType(1 /* Any */, "any"); - var autoType = createIntrinsicType(1 /* Any */, "any", 262144 /* NonInferrableType */); - var wildcardType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any", 262144 /* NonInferrableType */, "auto"); + var wildcardType = createIntrinsicType( + 1 /* Any */, + "any", + /*objectFlags*/ + void 0, + "wildcard" + ); + var blockedStringType = createIntrinsicType( + 1 /* Any */, + "any", + /*objectFlags*/ + void 0, + "blocked string" + ); var errorType = createIntrinsicType(1 /* Any */, "error"); var unresolvedType = createIntrinsicType(1 /* Any */, "unresolved"); - var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 65536 /* ContainsWideningType */); + var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 65536 /* ContainsWideningType */, "non-inferrable"); var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); - var nonNullUnknownType = createIntrinsicType(2 /* Unknown */, "unknown"); + var nonNullUnknownType = createIntrinsicType( + 2 /* Unknown */, + "unknown", + /*objectFlags*/ + void 0, + "non-null" + ); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 65536 /* ContainsWideningType */); - var missingType = createIntrinsicType(32768 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 65536 /* ContainsWideningType */, "widening"); + var missingType = createIntrinsicType( + 32768 /* Undefined */, + "undefined", + /*objectFlags*/ + void 0, + "missing" + ); var undefinedOrMissingType = exactOptionalPropertyTypes ? missingType : undefinedType; - var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); + var optionalType = createIntrinsicType( + 32768 /* Undefined */, + "undefined", + /*objectFlags*/ + void 0, + "optional" + ); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 65536 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 65536 /* ContainsWideningType */, "widening"); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); - var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var falseType = createIntrinsicType( + 512 /* BooleanLiteral */, + "false", + /*objectFlags*/ + void 0, + "fresh" + ); var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); - var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + var trueType = createIntrinsicType( + 512 /* BooleanLiteral */, + "true", + /*objectFlags*/ + void 0, + "fresh" + ); var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); trueType.regularType = regularTrueType; trueType.freshType = trueType; @@ -46076,9 +46318,21 @@ ${lanes.join("\n")} var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(16384 /* Void */, "void"); var neverType = createIntrinsicType(131072 /* Never */, "never"); - var silentNeverType = createIntrinsicType(131072 /* Never */, "never", 262144 /* NonInferrableType */); - var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); - var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); + var silentNeverType = createIntrinsicType(131072 /* Never */, "never", 262144 /* NonInferrableType */, "silent"); + var implicitNeverType = createIntrinsicType( + 131072 /* Never */, + "never", + /*objectFlags*/ + void 0, + "implicit" + ); + var unreachableNeverType = createIntrinsicType( + 131072 /* Never */, + "never", + /*objectFlags*/ + void 0, + "unreachable" + ); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); var stringOrNumberType = getUnionType([stringType, numberType]); var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); @@ -46088,7 +46342,13 @@ ${lanes.join("\n")} var numericStringType = getTemplateLiteralType(["", ""], [numberType]); var restrictiveMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t, () => "(restrictive mapper)"); var permissiveMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? wildcardType : t, () => "(permissive mapper)"); - var uniqueLiteralType = createIntrinsicType(131072 /* Never */, "never"); + var uniqueLiteralType = createIntrinsicType( + 131072 /* Never */, + "never", + /*objectFlags*/ + void 0, + "unique literal" + ); var uniqueLiteralMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? uniqueLiteralType : t, () => "(unique literal mapper)"); var outofbandVarianceMarkerHandler; var reportUnreliableMapper = makeFunctionTypeMapper((t) => { @@ -46886,6 +47146,9 @@ ${lanes.join("\n")} const sourceFiles = host.getSourceFiles(); return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } + if (!!(usage.flags & 16777216 /* JSDoc */) || isInTypeQuery(usage) || isInAmbientOrTypeNode(usage)) { + return true; + } if (declaration.pos <= usage.pos && !(isPropertyDeclaration(declaration) && isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { if (declaration.kind === 208 /* BindingElement */) { const errorBindingElement = getAncestor(usage, 208 /* BindingElement */); @@ -46915,9 +47178,6 @@ ${lanes.join("\n")} if (usage.kind === 277 /* ExportAssignment */ && usage.isExportEquals) { return true; } - if (!!(usage.flags & 16777216 /* JSDoc */) || isInTypeQuery(usage) || isInAmbientOrTypeNode(usage)) { - return true; - } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { if (emitStandardClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration( @@ -47437,7 +47697,7 @@ ${lanes.join("\n")} if (lastLocation && lastLocation === location.name) { return false; } - if (location.asteriskToken || hasSyntacticModifier(location, 512 /* Async */)) { + if (location.asteriskToken || hasSyntacticModifier(location, 1024 /* Async */)) { return true; } return !getImmediatelyInvokedFunctionExpression(location); @@ -47601,8 +47861,17 @@ ${lanes.join("\n")} function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & 111551 /* Value */) { if (isPrimitiveTypeName(name)) { - if (isExtendedByInterface(errorLocation)) { - error2(errorLocation, Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes, unescapeLeadingUnderscores(name)); + const grandparent = errorLocation.parent.parent; + if (grandparent && grandparent.parent && isHeritageClause(grandparent)) { + const heritageKind = grandparent.token; + const containerKind = grandparent.parent.kind; + if (containerKind === 264 /* InterfaceDeclaration */ && heritageKind === 96 /* ExtendsKeyword */) { + error2(errorLocation, Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types, unescapeLeadingUnderscores(name)); + } else if (containerKind === 263 /* ClassDeclaration */ && heritageKind === 96 /* ExtendsKeyword */) { + error2(errorLocation, Diagnostics.A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values, unescapeLeadingUnderscores(name)); + } else if (containerKind === 263 /* ClassDeclaration */ && heritageKind === 119 /* ImplementsKeyword */) { + error2(errorLocation, Diagnostics.A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types, unescapeLeadingUnderscores(name)); + } } else { error2(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, unescapeLeadingUnderscores(name)); } @@ -47634,16 +47903,6 @@ ${lanes.join("\n")} } return false; } - function isExtendedByInterface(node) { - const grandparent = node.parent.parent; - const parentOfGrandparent = grandparent.parent; - if (grandparent && parentOfGrandparent) { - const isExtending = isHeritageClause(grandparent) && grandparent.token === 96 /* ExtendsKeyword */; - const isInterface = isInterfaceDeclaration(parentOfGrandparent); - return isExtending && isInterface; - } - return false; - } function maybeMappedType(node, symbol) { const container = findAncestor(node.parent, (n) => isComputedPropertyName(n) || isPropertySignature(n) ? false : isTypeLiteralNode(n) || "quit"); if (container && container.members.length === 1) { @@ -47731,15 +47990,12 @@ ${lanes.join("\n")} diagnosticMessage = error2(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationName); } if (diagnosticMessage) { - addRelatedInfo( - diagnosticMessage, - createDiagnosticForNode(declaration, Diagnostics._0_is_declared_here, declarationName) - ); + addRelatedInfo(diagnosticMessage, createDiagnosticForNode(declaration, Diagnostics._0_is_declared_here, declarationName)); } } } function isSameScopeDescendentOf(initial, parent2, stopAt) { - return !!parent2 && !!findAncestor(initial, (n) => n === parent2 || (n === stopAt || isFunctionLike(n) && (!getImmediatelyInvokedFunctionExpression(n) || isAsyncFunction(n)) ? "quit" : false)); + return !!parent2 && !!findAncestor(initial, (n) => n === parent2 || (n === stopAt || isFunctionLike(n) && (!getImmediatelyInvokedFunctionExpression(n) || getFunctionFlags(n) & 3 /* AsyncGenerator */) ? "quit" : false)); } function getAnyImportSyntax(node) { switch (node.kind) { @@ -47825,7 +48081,7 @@ ${lanes.join("\n")} return resolved; } function isSyntacticDefault(node) { - return isExportAssignment(node) && !node.isExportEquals || hasSyntacticModifier(node, 1024 /* Default */) || isExportSpecifier(node); + return isExportAssignment(node) && !node.isExportEquals || hasSyntacticModifier(node, 2048 /* Default */) || isExportSpecifier(node) || isNamespaceExport(node); } function getUsageModeForExpression(usage) { return isStringLiteralLike(usage) ? getModeForUsageLocation(getSourceFileOfNode(usage), usage) : void 0; @@ -47910,11 +48166,14 @@ ${lanes.join("\n")} const exportAssignment = exportEqualsSymbol.valueDeclaration; const err = error2(node.name, Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); if (exportAssignment) { - addRelatedInfo(err, createDiagnosticForNode( - exportAssignment, - Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, - compilerOptionName - )); + addRelatedInfo( + err, + createDiagnosticForNode( + exportAssignment, + Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, + compilerOptionName + ) + ); } } else if (isImportClause(node)) { reportNonDefaultExport(moduleSymbol, node); @@ -47971,10 +48230,12 @@ ${lanes.join("\n")} const diagnostic = error2(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); const exportStar = (_b = moduleSymbol.exports) == null ? void 0 : _b.get("__export" /* ExportStar */); if (exportStar) { - const defaultExport = (_c = exportStar.declarations) == null ? void 0 : _c.find((decl) => { - var _a2, _b2; - return !!(isExportDeclaration(decl) && decl.moduleSpecifier && ((_b2 = (_a2 = resolveExternalModuleName(decl, decl.moduleSpecifier)) == null ? void 0 : _a2.exports) == null ? void 0 : _b2.has("default" /* Default */))); - }); + const defaultExport = (_c = exportStar.declarations) == null ? void 0 : _c.find( + (decl) => { + var _a2, _b2; + return !!(isExportDeclaration(decl) && decl.moduleSpecifier && ((_b2 = (_a2 = resolveExternalModuleName(decl, decl.moduleSpecifier)) == null ? void 0 : _a2.exports) == null ? void 0 : _b2.has("default" /* Default */))); + } + ); if (defaultExport) { addRelatedInfo(diagnostic, createDiagnosticForNode(defaultExport, Diagnostics.export_Asterisk_does_not_re_export_a_default)); } @@ -48121,10 +48382,7 @@ ${lanes.join("\n")} const suggestionName = symbolToString(suggestion); const diagnostic = error2(name, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName); if (suggestion.valueDeclaration) { - addRelatedInfo( - diagnostic, - createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName) - ); + addRelatedInfo(diagnostic, createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName)); } } else { if ((_a = moduleSymbol.exports) == null ? void 0 : _a.has("default" /* Default */)) { @@ -48151,10 +48409,7 @@ ${lanes.join("\n")} const exportedSymbol = exports ? find(symbolsToArray(exports), (symbol) => !!getSymbolIfSameReference(symbol, localSymbol)) : void 0; const diagnostic = exportedSymbol ? error2(name, Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error2(name, Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); if (localSymbol.declarations) { - addRelatedInfo( - diagnostic, - ...map(localSymbol.declarations, (decl, index) => createDiagnosticForNode(decl, index === 0 ? Diagnostics._0_is_declared_here : Diagnostics.and_here, declarationName)) - ); + addRelatedInfo(diagnostic, ...map(localSymbol.declarations, (decl, index) => createDiagnosticForNode(decl, index === 0 ? Diagnostics._0_is_declared_here : Diagnostics.and_here, declarationName))); } } } else { @@ -48756,7 +49011,7 @@ ${lanes.join("\n")} const contextSpecifier = isStringLiteralLike(location) ? location : ((_a = findAncestor(location, isImportCall)) == null ? void 0 : _a.arguments[0]) || ((_b = findAncestor(location, isImportDeclaration)) == null ? void 0 : _b.moduleSpecifier) || ((_c = findAncestor(location, isExternalModuleImportEqualsDeclaration)) == null ? void 0 : _c.moduleReference.expression) || ((_d = findAncestor(location, isExportDeclaration)) == null ? void 0 : _d.moduleSpecifier) || ((_e = isModuleDeclaration(location) ? location : location.parent && isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : void 0) == null ? void 0 : _e.name) || ((_f = isLiteralImportTypeNode(location) ? location : void 0) == null ? void 0 : _f.argument.literal); const mode = contextSpecifier && isStringLiteralLike(contextSpecifier) ? getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat; const moduleResolutionKind = getEmitModuleResolutionKind(compilerOptions); - const resolvedModule = getResolvedModule(currentSourceFile, moduleReference, mode); + const resolvedModule = (_g = host.getResolvedModule(currentSourceFile, moduleReference, mode)) == null ? void 0 : _g.resolvedModule; const resolutionDiagnostic = resolvedModule && getResolutionDiagnostic(compilerOptions, resolvedModule, currentSourceFile); const sourceFile = resolvedModule && (!resolutionDiagnostic || resolutionDiagnostic === Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set) && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { @@ -48764,7 +49019,7 @@ ${lanes.join("\n")} error2(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } if (resolvedModule.resolvedUsingTsExtension && isDeclarationFileName(moduleReference)) { - const importOrExport = ((_g = findAncestor(location, isImportDeclaration)) == null ? void 0 : _g.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); + const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); if (importOrExport && !importOrExport.isTypeOnly || findAncestor(location, isImportCall)) { error2( errorNode, @@ -48773,7 +49028,7 @@ ${lanes.join("\n")} ); } } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) { - const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); + const importOrExport = ((_i = findAncestor(location, isImportDeclaration)) == null ? void 0 : _i.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); @@ -48793,9 +49048,8 @@ ${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) ? (_i = overrideClauseHost.assertions) == null ? void 0 : _i.assertClause : overrideClauseHost == null ? void 0 : overrideClauseHost.assertClause; - if (isSyncImport && sourceFile.impliedNodeFormat === 99 /* ESNext */ && !getResolutionModeOverrideForClause(overrideClause)) { + const overrideHost = findAncestor(location, (l) => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l)); + if (isSyncImport && sourceFile.impliedNodeFormat === 99 /* ESNext */ && !hasResolutionModeOverride(overrideHost)) { 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); } else { @@ -48838,11 +49092,15 @@ ${lanes.join("\n")} } } } - diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorNode), errorNode, chainDiagnosticMessages( - diagnosticDetails, - Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead, - moduleReference - ))); + diagnostics.add(createDiagnosticForNodeFromMessageChain( + getSourceFileOfNode(errorNode), + errorNode, + chainDiagnosticMessages( + diagnosticDetails, + Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead, + moduleReference + ) + )); } } } @@ -48899,13 +49157,9 @@ ${lanes.join("\n")} const absoluteRef = getNormalizedAbsolutePath(moduleReference, getDirectoryPath(currentSourceFile.path)); const suggestedExt = (_j = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _j[1]; if (suggestedExt) { - error2( - errorNode, - Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node16_or_nodenext_Did_you_mean_0, - moduleReference + suggestedExt - ); + error2(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt); } else { - error2(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node16_or_nodenext_Consider_adding_an_extension_to_the_import_path); + error2(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Consider_adding_an_extension_to_the_import_path); } } else { error2(errorNode, moduleNotFoundError, moduleReference); @@ -48928,12 +49182,16 @@ ${lanes.join("\n")} if (!isExternalModuleNameRelative(moduleReference) && packageId) { errorInfo = createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageId.name); } - errorOrSuggestion(isError, errorNode, chainDiagnosticMessages( - errorInfo, - Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, - moduleReference, - resolvedFileName - )); + errorOrSuggestion( + isError, + errorNode, + chainDiagnosticMessages( + errorInfo, + Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, + moduleReference, + resolvedFileName + ) + ); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { if (moduleSymbol == null ? void 0 : moduleSymbol.exports) { @@ -49170,10 +49428,12 @@ ${lanes.join("\n")} } if (exportStar == null ? void 0 : exportStar.isTypeOnly) { typeOnlyExportStarMap ?? (typeOnlyExportStarMap = /* @__PURE__ */ new Map()); - symbols.forEach((_, escapedName) => typeOnlyExportStarMap.set( - escapedName, - exportStar - )); + symbols.forEach( + (_, escapedName) => typeOnlyExportStarMap.set( + escapedName, + exportStar + ) + ); } return symbols; } @@ -49355,12 +49615,21 @@ ${lanes.join("\n")} function createOriginType(flags) { return new Type27(checker, flags); } - function createIntrinsicType(kind, intrinsicName, objectFlags = 0 /* None */) { + function createIntrinsicType(kind, intrinsicName, objectFlags = 0 /* None */, debugIntrinsicName) { + checkIntrinsicName(intrinsicName, debugIntrinsicName); const type = createType(kind); type.intrinsicName = intrinsicName; + type.debugIntrinsicName = debugIntrinsicName; type.objectFlags = objectFlags | 524288 /* CouldContainTypeVariablesComputed */ | 2097152 /* IsGenericTypeComputed */ | 33554432 /* IsUnknownLikeUnionComputed */ | 16777216 /* IsNeverIntersectionComputed */; return type; } + function checkIntrinsicName(name, debug) { + const key = `${name},${debug ?? ""}`; + if (seenIntrinsicNames.has(key)) { + Debug.fail(`Duplicate intrinsic type name ${name}${debug ? ` (${debug})` : ""}; you may need to pass a name to createIntrinsicType.`); + } + seenIntrinsicNames.add(key); + } function createObjectType(objectFlags, symbol) { const type = createTypeWithSymbol(524288 /* Object */, symbol); type.objectFlags = objectFlags; @@ -49409,13 +49678,7 @@ ${lanes.join("\n")} return resolved; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, indexInfos) { - return setStructuredTypeMembers( - createObjectType(16 /* Anonymous */, symbol), - members, - callSignatures, - constructSignatures, - indexInfos - ); + return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, indexInfos); } function getResolvedTypeWithoutAbstractConstructSignatures(type) { if (type.constructSignatures.length === 0) @@ -49779,20 +50042,20 @@ ${lanes.join("\n")} var _a, _b; if (!isDeclarationVisible(declaration)) { const anyImportSyntax = getAnyImportSyntax(declaration); - if (anyImportSyntax && !hasSyntacticModifier(anyImportSyntax, 1 /* Export */) && // import clause without export + if (anyImportSyntax && !hasSyntacticModifier(anyImportSyntax, 32 /* Export */) && // import clause without export isDeclarationVisible(anyImportSyntax.parent)) { return addVisibleAlias(declaration, anyImportSyntax); - } else if (isVariableDeclaration(declaration) && isVariableStatement(declaration.parent.parent) && !hasSyntacticModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement + } else if (isVariableDeclaration(declaration) && isVariableStatement(declaration.parent.parent) && !hasSyntacticModifier(declaration.parent.parent, 32 /* Export */) && // unexported variable statement isDeclarationVisible(declaration.parent.parent.parent)) { return addVisibleAlias(declaration, declaration.parent.parent); - } else if (isLateVisibilityPaintedStatement(declaration) && !hasSyntacticModifier(declaration, 1 /* Export */) && isDeclarationVisible(declaration.parent)) { + } else if (isLateVisibilityPaintedStatement(declaration) && !hasSyntacticModifier(declaration, 32 /* Export */) && isDeclarationVisible(declaration.parent)) { return addVisibleAlias(declaration, declaration); } else if (isBindingElement(declaration)) { - if (symbol.flags & 2097152 /* Alias */ && isInJSFile(declaration) && ((_a = declaration.parent) == null ? void 0 : _a.parent) && isVariableDeclaration(declaration.parent.parent) && ((_b = declaration.parent.parent.parent) == null ? void 0 : _b.parent) && isVariableStatement(declaration.parent.parent.parent.parent) && !hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* Export */) && declaration.parent.parent.parent.parent.parent && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { + if (symbol.flags & 2097152 /* Alias */ && isInJSFile(declaration) && ((_a = declaration.parent) == null ? void 0 : _a.parent) && isVariableDeclaration(declaration.parent.parent) && ((_b = declaration.parent.parent.parent) == null ? void 0 : _b.parent) && isVariableStatement(declaration.parent.parent.parent.parent) && !hasSyntacticModifier(declaration.parent.parent.parent.parent, 32 /* Export */) && declaration.parent.parent.parent.parent.parent && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); } else if (symbol.flags & 2 /* BlockScopedVariable */) { const variableStatement = findAncestor(declaration, isVariableStatement); - if (hasSyntacticModifier(variableStatement, 1 /* Export */)) { + if (hasSyntacticModifier(variableStatement, 32 /* Export */)) { return true; } if (!isDeclarationVisible(variableStatement.parent)) { @@ -50015,7 +50278,8 @@ ${lanes.join("\n")} visitedTypes: void 0, symbolDepth: void 0, inferTypeParameters: void 0, - approximateLength: 0 + approximateLength: 0, + trackedSymbols: void 0 }; context.tracker = new SymbolTrackerImpl(context, tracker, moduleResolverHost); const resultingNode = cb(context); @@ -50469,7 +50733,7 @@ ${lanes.join("\n")} } } function visitAndTransformType(type2, transform2) { - var _a2, _b2; + var _a2, _b2, _c; const typeId = type2.id; const isConstructorObject = getObjectFlags(type2) & 16 /* Anonymous */ && type2.symbol && type2.symbol.flags & 32 /* Class */; const id = getObjectFlags(type2) & 4 /* Reference */ && type2.node ? "N" + getNodeId(type2.node) : type2.flags & 16777216 /* Conditional */ ? "N" + getNodeId(type2.root.node) : type2.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type2.symbol) : void 0; @@ -50486,6 +50750,13 @@ ${lanes.join("\n")} } const cachedResult = (_a2 = links == null ? void 0 : links.serializedTypes) == null ? void 0 : _a2.get(key); if (cachedResult) { + (_b2 = cachedResult.trackedSymbols) == null ? void 0 : _b2.forEach( + ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol( + symbol, + enclosingDeclaration, + meaning + ) + ); if (cachedResult.truncating) { context.truncating = true; } @@ -50501,16 +50772,24 @@ ${lanes.join("\n")} context.symbolDepth.set(id, depth + 1); } context.visitedTypes.add(typeId); + const prevTrackedSymbols = context.trackedSymbols; + context.trackedSymbols = void 0; const startLength = context.approximateLength; const result = transform2(type2); const addedLength = context.approximateLength - startLength; if (!context.reportedDiagnostic && !context.encounteredError) { - (_b2 = links == null ? void 0 : links.serializedTypes) == null ? void 0 : _b2.set(key, { node: result, truncating: context.truncating, addedLength }); + (_c = links == null ? void 0 : links.serializedTypes) == null ? void 0 : _c.set(key, { + node: result, + truncating: context.truncating, + addedLength, + trackedSymbols: context.trackedSymbols + }); } context.visitedTypes.delete(typeId); if (id) { context.symbolDepth.set(id, depth); } + context.trackedSymbols = prevTrackedSymbols; return result; function deepCloneOrReuseNode(node) { if (!nodeIsSynthesized(node) && getParseTreeNode(node) === node) { @@ -50661,11 +50940,7 @@ ${lanes.join("\n")} } } else { if (typeArguments !== getIdentifierTypeArguments(qualifier.right)) { - qualifier = factory.updateQualifiedName( - qualifier, - qualifier.left, - setIdentifierTypeArguments(factory.cloneNode(qualifier.right), typeArguments) - ); + qualifier = factory.updateQualifiedName(qualifier, qualifier.left, setIdentifierTypeArguments(factory.cloneNode(qualifier.right), typeArguments)); } } } @@ -50677,7 +50952,7 @@ ${lanes.join("\n")} return factory.updateImportTypeNode( root, root.argument, - root.assertions, + root.attributes, qualifier, typeArguments, root.isTypeOf @@ -50691,11 +50966,7 @@ ${lanes.join("\n")} } } else { if (typeArguments !== getIdentifierTypeArguments(typeName.right)) { - typeName = factory.updateQualifiedName( - typeName, - typeName.left, - setIdentifierTypeArguments(factory.cloneNode(typeName.right), typeArguments) - ); + typeName = factory.updateQualifiedName(typeName, typeName.left, setIdentifierTypeArguments(factory.cloneNode(typeName.right), typeArguments)); } } typeArguments = ref.typeArguments; @@ -50755,7 +51026,7 @@ ${lanes.join("\n")} if (propertySymbol.flags & 4194304 /* Prototype */) { continue; } - if (getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { + if (getDeclarationModifierFlagsFromSymbol(propertySymbol) & (2 /* Private */ | 4 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { context.tracker.reportPrivateInBaseOfClassExpression(unescapeLeadingUnderscores(propertySymbol.escapedName)); } } @@ -50819,6 +51090,28 @@ ${lanes.join("\n")} const propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); context.enclosingDeclaration = saveEnclosingDeclaration; context.approximateLength += symbolName(propertySymbol).length + 1; + if (propertySymbol.flags & 98304 /* Accessor */) { + const writeType = getWriteTypeOfSymbol(propertySymbol); + if (propertyType !== writeType && !isErrorType(propertyType) && !isErrorType(writeType)) { + const getterDeclaration = getDeclarationOfKind(propertySymbol, 177 /* GetAccessor */); + const getterSignature = getSignatureFromDeclaration(getterDeclaration); + typeElements.push( + setCommentRange( + signatureToSignatureDeclarationHelper(getterSignature, 177 /* GetAccessor */, context, { name: propertyName }), + getterDeclaration + ) + ); + const setterDeclaration = getDeclarationOfKind(propertySymbol, 178 /* SetAccessor */); + const setterSignature = getSignatureFromDeclaration(setterDeclaration); + typeElements.push( + setCommentRange( + signatureToSignatureDeclarationHelper(setterSignature, 178 /* SetAccessor */, context, { name: propertyName }), + setterDeclaration + ) + ); + return; + } + } const optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { const signatures = getSignaturesOfType(filterType(propertyType, (t) => !(t.flags & 32768 /* Undefined */)), 0 /* Call */); @@ -50856,9 +51149,9 @@ ${lanes.join("\n")} typeElements.push(preserveCommentsOn(propertySignature)); function preserveCommentsOn(node) { var _a2; - if (some(propertySymbol.declarations, (d) => d.kind === 355 /* JSDocPropertyTag */)) { - const d = (_a2 = propertySymbol.declarations) == null ? void 0 : _a2.find((d2) => d2.kind === 355 /* JSDocPropertyTag */); - const commentText = getTextOfJSDocComment(d.comment); + const jsdocPropertyTag = (_a2 = propertySymbol.declarations) == null ? void 0 : _a2.find((d) => d.kind === 355 /* JSDocPropertyTag */); + if (jsdocPropertyTag) { + const commentText = getTextOfJSDocComment(jsdocPropertyTag.comment); if (commentText) { setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); } @@ -51036,7 +51329,7 @@ ${lanes.join("\n")} let modifiers = options == null ? void 0 : options.modifiers; if (kind === 185 /* ConstructorType */ && signature.flags & 4 /* Abstract */) { const flags = modifiersToFlags(modifiers); - modifiers = factory.createModifiersFromModifierFlags(flags | 256 /* Abstract */); + modifiers = factory.createModifiersFromModifierFlags(flags | 64 /* Abstract */); } const node = kind === 179 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 180 /* ConstructSignature */ ? factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 173 /* MethodSignature */ ? factory.createMethodSignature(modifiers, (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), options == null ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : kind === 174 /* MethodDeclaration */ ? factory.createMethodDeclaration( modifiers, @@ -51150,11 +51443,17 @@ ${lanes.join("\n")} const constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } - function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { - let parameterDeclaration = getDeclarationOfKind(parameterSymbol, 169 /* Parameter */); - if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = getDeclarationOfKind(parameterSymbol, 348 /* JSDocParameterTag */); + function getEffectiveParameterDeclaration(parameterSymbol) { + const parameterDeclaration = getDeclarationOfKind(parameterSymbol, 169 /* Parameter */); + if (parameterDeclaration) { + return parameterDeclaration; } + if (!isTransientSymbol(parameterSymbol)) { + return getDeclarationOfKind(parameterSymbol, 348 /* JSDocParameterTag */); + } + } + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { + const parameterDeclaration = getEffectiveParameterDeclaration(parameterSymbol); let parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); @@ -51163,7 +51462,7 @@ ${lanes.join("\n")} const modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && canHaveModifiers(parameterDeclaration) ? map(getModifiers(parameterDeclaration), factory.cloneNode) : void 0; const isRest = parameterDeclaration && isRestParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 32768 /* RestParameter */; const dotDotDotToken = isRest ? factory.createToken(26 /* DotDotDotToken */) : void 0; - const name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : parameterDeclaration.name.kind === 166 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); + const name = parameterToParameterDeclarationName(parameterSymbol, parameterDeclaration, context); const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */; const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0; const parameterNode = factory.createParameterDeclaration( @@ -51177,6 +51476,9 @@ ${lanes.join("\n")} ); context.approximateLength += symbolName(parameterSymbol).length + 3; return parameterNode; + } + function parameterToParameterDeclarationName(parameterSymbol, parameterDeclaration, context) { + return parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : parameterDeclaration.name.kind === 166 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node2) { @@ -51252,7 +51554,9 @@ ${lanes.join("\n")} if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning2 : getQualifiedLeftMeaning(meaning2))) { const parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol2, context.enclosingDeclaration, meaning2); if (length(parents)) { - parentSpecifiers = parents.map((symbol3) => some(symbol3.declarations, hasNonGlobalAugmentationExternalModuleSymbol) ? getSpecifierForModuleSymbol(symbol3, context) : void 0); + parentSpecifiers = parents.map( + (symbol3) => some(symbol3.declarations, hasNonGlobalAugmentationExternalModuleSymbol) ? getSpecifierForModuleSymbol(symbol3, context) : void 0 + ); const indices = parents.map((_, i) => i); indices.sort(sortByBestName); const sortedParents = indices.map((i) => parents[i]); @@ -51403,7 +51707,6 @@ ${lanes.join("\n")} return symbol.parent ? factory.createQualifiedName(symbolToEntityNameNode(symbol.parent), identifier) : identifier; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { - var _a, _b, _c, _d; const chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); const isTypeOf = meaning === 111551 /* Value */; if (some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { @@ -51412,40 +51715,42 @@ ${lanes.join("\n")} const contextFile = getSourceFileOfNode(getOriginalNode(context.enclosingDeclaration)); const targetFile = getSourceFileOfModule(chain[0]); let specifier; - let assertion; + let attributes; if (getEmitModuleResolutionKind(compilerOptions) === 3 /* Node16 */ || getEmitModuleResolutionKind(compilerOptions) === 99 /* NodeNext */) { if ((targetFile == null ? void 0 : targetFile.impliedNodeFormat) === 99 /* ESNext */ && targetFile.impliedNodeFormat !== (contextFile == null ? void 0 : contextFile.impliedNodeFormat)) { specifier = getSpecifierForModuleSymbol(chain[0], context, 99 /* ESNext */); - assertion = factory.createImportTypeAssertionContainer(factory.createAssertClause(factory.createNodeArray([ - factory.createAssertEntry( - factory.createStringLiteral("resolution-mode"), - factory.createStringLiteral("import") - ) - ]))); - (_b = (_a = context.tracker).reportImportTypeNodeResolutionModeOverride) == null ? void 0 : _b.call(_a); + attributes = factory.createImportAttributes( + factory.createNodeArray([ + factory.createImportAttribute( + factory.createStringLiteral("resolution-mode"), + factory.createStringLiteral("import") + ) + ]) + ); } } if (!specifier) { specifier = getSpecifierForModuleSymbol(chain[0], context); } - if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && getEmitModuleResolutionKind(compilerOptions) !== 1 /* Classic */ && specifier.indexOf("/node_modules/") >= 0) { + if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && getEmitModuleResolutionKind(compilerOptions) !== 1 /* Classic */ && specifier.includes("/node_modules/")) { const oldSpecifier = specifier; if (getEmitModuleResolutionKind(compilerOptions) === 3 /* Node16 */ || getEmitModuleResolutionKind(compilerOptions) === 99 /* NodeNext */) { const swappedMode = (contextFile == null ? void 0 : contextFile.impliedNodeFormat) === 99 /* ESNext */ ? 1 /* CommonJS */ : 99 /* ESNext */; specifier = getSpecifierForModuleSymbol(chain[0], context, swappedMode); - if (specifier.indexOf("/node_modules/") >= 0) { + if (specifier.includes("/node_modules/")) { specifier = oldSpecifier; } else { - assertion = factory.createImportTypeAssertionContainer(factory.createAssertClause(factory.createNodeArray([ - factory.createAssertEntry( - factory.createStringLiteral("resolution-mode"), - factory.createStringLiteral(swappedMode === 99 /* ESNext */ ? "import" : "require") - ) - ]))); - (_d = (_c = context.tracker).reportImportTypeNodeResolutionModeOverride) == null ? void 0 : _d.call(_c); + attributes = factory.createImportAttributes( + factory.createNodeArray([ + factory.createImportAttribute( + factory.createStringLiteral("resolution-mode"), + factory.createStringLiteral(swappedMode === 99 /* ESNext */ ? "import" : "require") + ) + ]) + ); } } - if (!assertion) { + if (!attributes) { context.encounteredError = true; if (context.tracker.reportLikelyUnsafeImportRequiredError) { context.tracker.reportLikelyUnsafeImportRequiredError(oldSpecifier); @@ -51465,11 +51770,11 @@ ${lanes.join("\n")} void 0 ); } - return factory.createImportTypeNode(lit, assertion, nonRootParts, typeParameterNodes, isTypeOf); + return factory.createImportTypeNode(lit, attributes, nonRootParts, typeParameterNodes, isTypeOf); } else { const splitNode = getTopmostIndexedAccessType(nonRootParts); const qualifier = splitNode.objectType.typeName; - return factory.createIndexedAccessTypeNode(factory.createImportTypeNode(lit, assertion, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + return factory.createIndexedAccessTypeNode(factory.createImportTypeNode(lit, attributes, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); } } const entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); @@ -51669,7 +51974,18 @@ ${lanes.join("\n")} } function isStringNamed(d) { const name = getNameOfDeclaration(d); - return !!name && isStringLiteral(name); + if (!name) { + return false; + } + if (isComputedPropertyName(name)) { + const type = checkExpression(name.expression); + return !!(type.flags & 402653316 /* StringLike */); + } + if (isElementAccessExpression(name)) { + const type = checkExpression(name.argumentExpression); + return !!(type.flags & 402653316 /* StringLike */); + } + return isStringLiteral(name); } function isSingleQuotedStringNamed(d) { const name = getNameOfDeclaration(d); @@ -51682,14 +51998,15 @@ ${lanes.join("\n")} function getPropertyNameNodeForSymbol(symbol, context) { const stringNamed = !!length(symbol.declarations) && every(symbol.declarations, isStringNamed); const singleQuote = !!length(symbol.declarations) && every(symbol.declarations, isSingleQuotedStringNamed); - const fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote, stringNamed); + const isMethod = !!(symbol.flags & 8192 /* Method */); + const fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote, stringNamed, isMethod); if (fromNameType) { return fromNameType; } const rawName = unescapeLeadingUnderscores(symbol.escapedName); - return createPropertyNameNodeForIdentifierOrLiteral(rawName, getEmitScriptTarget(compilerOptions), singleQuote, stringNamed); + return createPropertyNameNodeForIdentifierOrLiteral(rawName, getEmitScriptTarget(compilerOptions), singleQuote, stringNamed, isMethod); } - function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote, stringNamed) { + function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote, stringNamed, isMethod) { const nameType = getSymbolLinks(symbol).nameType; if (nameType) { if (nameType.flags & 384 /* StringOrNumberLiteral */) { @@ -51700,7 +52017,7 @@ ${lanes.join("\n")} if (isNumericLiteralName(name) && startsWith(name, "-")) { return factory.createComputedPropertyName(factory.createNumericLiteral(+name)); } - return createPropertyNameNodeForIdentifierOrLiteral(name, getEmitScriptTarget(compilerOptions)); + return createPropertyNameNodeForIdentifierOrLiteral(name, getEmitScriptTarget(compilerOptions), singleQuote, stringNamed, isMethod); } if (nameType.flags & 8192 /* UniqueESSymbol */) { return factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */)); @@ -51933,7 +52250,7 @@ ${lanes.join("\n")} return factory.updateImportTypeNode( node, factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), - node.assertions, + node.attributes, node.qualifier, visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode), node.isTypeOf @@ -51989,6 +52306,7 @@ ${lanes.join("\n")} } } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { + var _a; const serializePropertySymbolForClass = makeSerializePropertySymbol( factory.createPropertyDeclaration, 174 /* MethodDeclaration */, @@ -52010,12 +52328,15 @@ ${lanes.join("\n")} ...oldcontext, usedSymbolNames: new Set(oldcontext.usedSymbolNames), remappedSymbolNames: /* @__PURE__ */ new Map(), + remappedSymbolReferences: new Map((_a = oldcontext.remappedSymbolReferences) == null ? void 0 : _a.entries()), tracker: void 0 }; const tracker = { ...oldcontext.tracker.inner, trackSymbol: (sym, decl, meaning) => { - var _a; + var _a2, _b; + if ((_a2 = context.remappedSymbolNames) == null ? void 0 : _a2.has(getSymbolId(sym))) + return false; const accessibleResult = isSymbolAccessible( sym, decl, @@ -52026,9 +52347,13 @@ ${lanes.join("\n")} if (accessibleResult.accessibility === 0 /* Accessible */) { const chain = lookupSymbolChainWorker(sym, context, meaning); if (!(sym.flags & 4 /* Property */)) { - includePrivateSymbol(chain[0]); + const root = chain[0]; + const contextFile = getSourceFileOfNode(oldcontext.enclosingDeclaration); + if (some(root.declarations, (d) => getSourceFileOfNode(d) === contextFile)) { + includePrivateSymbol(root); + } } - } else if ((_a = oldcontext.tracker.inner) == null ? void 0 : _a.trackSymbol) { + } else if ((_b = oldcontext.tracker.inner) == null ? void 0 : _b.trackSymbol) { return oldcontext.tracker.inner.trackSymbol(sym, decl, meaning); } return false; @@ -52061,7 +52386,7 @@ ${lanes.join("\n")} const nsIndex = findIndex(statements, isModuleDeclaration); let ns = nsIndex !== -1 ? statements[nsIndex] : void 0; if (ns && exportAssignment && exportAssignment.isExportEquals && isIdentifier(exportAssignment.expression) && isIdentifier(ns.name) && idText(ns.name) === idText(exportAssignment.expression) && ns.body && isModuleBlock(ns.body)) { - const excessExports = filter(statements, (s) => !!(getEffectiveModifierFlags(s) & 1 /* Export */)); + const excessExports = filter(statements, (s) => !!(getEffectiveModifierFlags(s) & 32 /* Export */)); const name = ns.name; let body = ns.body; if (length(excessExports)) { @@ -52071,30 +52396,33 @@ ${lanes.join("\n")} ns.name, body = factory.updateModuleBlock( body, - factory.createNodeArray([...ns.body.statements, factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports(map(flatMap(excessExports, (e) => getNamesOfDeclaration(e)), (id) => factory.createExportSpecifier( + factory.createNodeArray([ + ...ns.body.statements, + factory.createExportDeclaration( + /*modifiers*/ + void 0, /*isTypeOnly*/ false, - /*propertyName*/ - void 0, - id - ))), - /*moduleSpecifier*/ - void 0 - )]) + factory.createNamedExports(map(flatMap(excessExports, (e) => getNamesOfDeclaration(e)), (id) => factory.createExportSpecifier( + /*isTypeOnly*/ + false, + /*propertyName*/ + void 0, + id + ))), + /*moduleSpecifier*/ + void 0 + ) + ]) ) ); statements = [...statements.slice(0, nsIndex), ns, ...statements.slice(nsIndex + 1)]; } if (!find(statements, (s) => s !== ns && nodeHasName(s, name))) { results = []; - const mixinExportFlag = !some(body.statements, (s) => hasSyntacticModifier(s, 1 /* Export */) || isExportAssignment(s) || isExportDeclaration(s)); + const mixinExportFlag = !some(body.statements, (s) => hasSyntacticModifier(s, 32 /* Export */) || isExportAssignment(s) || isExportDeclaration(s)); forEach(body.statements, (s) => { - addResult(s, mixinExportFlag ? 1 /* Export */ : 0 /* None */); + addResult(s, mixinExportFlag ? 32 /* Export */ : 0 /* None */); }); statements = [...filter(statements, (s) => s !== ns && s !== exportAssignment), ...results]; } @@ -52105,15 +52433,18 @@ ${lanes.join("\n")} const exports = filter(statements, (d) => isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause)); if (length(exports) > 1) { const nonExports = filter(statements, (d) => !isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause); - statements = [...nonExports, factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports(flatMap(exports, (e) => cast(e.exportClause, isNamedExports).elements)), - /*moduleSpecifier*/ - void 0 - )]; + statements = [ + ...nonExports, + factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports(flatMap(exports, (e) => cast(e.exportClause, isNamedExports).elements)), + /*moduleSpecifier*/ + void 0 + ) + ]; } const reexports = filter(statements, (d) => isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause)); if (length(reexports) > 1) { @@ -52122,7 +52453,7 @@ ${lanes.join("\n")} for (const group2 of groups) { if (group2.length > 1) { statements = [ - ...filter(statements, (s) => group2.indexOf(s) === -1), + ...filter(statements, (s) => !group2.includes(s)), factory.createExportDeclaration( /*modifiers*/ void 0, @@ -52139,7 +52470,7 @@ ${lanes.join("\n")} return statements; } function inlineExportModifiers(statements) { - const index = findIndex(statements, (d) => isExportDeclaration(d) && !d.moduleSpecifier && !d.assertClause && !!d.exportClause && isNamedExports(d.exportClause)); + const index = findIndex(statements, (d) => isExportDeclaration(d) && !d.moduleSpecifier && !d.attributes && !!d.exportClause && isNamedExports(d.exportClause)); if (index >= 0) { const exportDecl = statements[index]; const replacements = mapDefined(exportDecl.exportClause.elements, (e) => { @@ -52167,7 +52498,7 @@ ${lanes.join("\n")} replacements ), exportDecl.moduleSpecifier, - exportDecl.assertClause + exportDecl.attributes ); } } @@ -52183,12 +52514,12 @@ ${lanes.join("\n")} return statements; } function addExportModifier(node) { - const flags = (getEffectiveModifierFlags(node) | 1 /* Export */) & ~2 /* Ambient */; - return factory.updateModifiers(node, flags); + const flags = (getEffectiveModifierFlags(node) | 32 /* Export */) & ~128 /* Ambient */; + return factory.replaceModifiers(node, flags); } function removeExportModifier(node) { - const flags = getEffectiveModifierFlags(node) & ~1 /* Export */; - return factory.updateModifiers(node, flags); + const flags = getEffectiveModifierFlags(node) & ~32 /* Export */; + return factory.replaceModifiers(node, flags); } function visitSymbolTable(symbolTable2, suppressNewPrivateContext, propertyAsAlias) { if (!suppressNewPrivateContext) { @@ -52228,13 +52559,19 @@ ${lanes.join("\n")} if (context.reportedDiagnostic) { oldcontext.reportedDiagnostic = context.reportedDiagnostic; } + if (context.trackedSymbols) { + if (!oldContext.trackedSymbols) + oldContext.trackedSymbols = context.trackedSymbols; + else + Debug.assert(context.trackedSymbols === oldContext.trackedSymbols); + } context = oldContext; } } - function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { - var _a, _b, _c, _d; - const symbolName2 = unescapeLeadingUnderscores(symbol.escapedName); - const isDefault = symbol.escapedName === "default" /* Default */; + function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias, escapedSymbolName = symbol.escapedName) { + var _a2, _b, _c, _d, _e, _f; + const symbolName2 = unescapeLeadingUnderscores(escapedSymbolName); + const isDefault = escapedSymbolName === "default" /* Default */; if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && isStringANonContextualKeyword(symbolName2) && !isDefault) { context.encounteredError = true; return; @@ -52244,8 +52581,8 @@ ${lanes.join("\n")} if (needsPostExportDefault || needsExportDeclaration) { isPrivate = true; } - const modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 1024 /* Default */ : 0); - const isConstMergedWithNS = symbol.flags & 1536 /* Module */ && symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && symbol.escapedName !== "export=" /* ExportEquals */; + const modifierFlags = (!isPrivate ? 32 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 2048 /* Default */ : 0); + const isConstMergedWithNS = symbol.flags & 1536 /* Module */ && symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && escapedSymbolName !== "export=" /* ExportEquals */; const isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol); if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) { serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags); @@ -52253,7 +52590,7 @@ ${lanes.join("\n")} if (symbol.flags & 524288 /* TypeAlias */) { serializeTypeAlias(symbol, symbolName2, modifierFlags); } - if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */ | 98304 /* Accessor */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) && !(symbol.flags & 32 /* Class */) && !(symbol.flags & 8192 /* Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) { + if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */ | 98304 /* Accessor */) && escapedSymbolName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) && !(symbol.flags & 32 /* Class */) && !(symbol.flags & 8192 /* Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) { if (propertyAsAlias) { const createdExport = serializeMaybeAliasAssignment(symbol); if (createdExport) { @@ -52263,17 +52600,24 @@ ${lanes.join("\n")} } else { const type = getTypeOfSymbol(symbol); const localName = getInternalSymbolName(symbol, symbolName2); - if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) { + if (type.symbol && type.symbol !== symbol && type.symbol.flags & 16 /* Function */ && some(type.symbol.declarations, isFunctionExpressionOrArrowFunction) && (((_a2 = type.symbol.members) == null ? void 0 : _a2.size) || ((_b = type.symbol.exports) == null ? void 0 : _b.size))) { + if (!context.remappedSymbolReferences) { + context.remappedSymbolReferences = /* @__PURE__ */ new Map(); + } + context.remappedSymbolReferences.set(getSymbolId(type.symbol), symbol); + serializeSymbolWorker(type.symbol, isPrivate, propertyAsAlias, escapedSymbolName); + context.remappedSymbolReferences.delete(getSymbolId(type.symbol)); + } else if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) { serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags); } else { - const flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? ((_a = symbol.parent) == null ? void 0 : _a.valueDeclaration) && isSourceFile((_b = symbol.parent) == null ? void 0 : _b.valueDeclaration) ? 2 /* Const */ : void 0 : isConstantVariable(symbol) ? 2 /* Const */ : 1 /* Let */; + const flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? ((_c = symbol.parent) == null ? void 0 : _c.valueDeclaration) && isSourceFile((_d = symbol.parent) == null ? void 0 : _d.valueDeclaration) ? 2 /* Const */ : void 0 : isConstantVariable(symbol) ? 2 /* Const */ : 1 /* Let */; const name = needsPostExportDefault || !(symbol.flags & 4 /* Property */) ? localName : getUnusedName(localName, symbol); let textRange = symbol.declarations && find(symbol.declarations, (d) => isVariableDeclaration(d)); if (textRange && isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) { textRange = textRange.parent.parent; } - const propertyAccessRequire = (_c = symbol.declarations) == null ? void 0 : _c.find(isPropertyAccessExpression); - if (propertyAccessRequire && isBinaryExpression(propertyAccessRequire.parent) && isIdentifier(propertyAccessRequire.parent.right) && ((_d = type.symbol) == null ? void 0 : _d.valueDeclaration) && isSourceFile(type.symbol.valueDeclaration)) { + const propertyAccessRequire = (_e = symbol.declarations) == null ? void 0 : _e.find(isPropertyAccessExpression); + if (propertyAccessRequire && isBinaryExpression(propertyAccessRequire.parent) && isIdentifier(propertyAccessRequire.parent.right) && ((_f = type.symbol) == null ? void 0 : _f.valueDeclaration) && isSourceFile(type.symbol.valueDeclaration)) { const alias = localName === propertyAccessRequire.parent.right.escapedText ? void 0 : propertyAccessRequire.parent.right; addResult( factory.createExportDeclaration( @@ -52292,19 +52636,22 @@ ${lanes.join("\n")} ); context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* Value */); } else { - const statement = setTextRange(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([ - factory.createVariableDeclaration( - name, - /*exclamationToken*/ - void 0, - serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) - ) - ], flags) - ), textRange); - addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags); + const statement = setTextRange( + factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([ + factory.createVariableDeclaration( + name, + /*exclamationToken*/ + void 0, + serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) + ) + ], flags) + ), + textRange + ); + addResult(statement, name !== localName ? modifierFlags & ~32 /* Export */ : modifierFlags); if (name !== localName && !isPrivate) { addResult( factory.createExportDeclaration( @@ -52377,18 +52724,21 @@ ${lanes.join("\n")} factory.createIdentifier(getInternalSymbolName(symbol, symbolName2)) ), 0 /* None */); } else if (needsExportDeclaration) { - addResult(factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports([factory.createExportSpecifier( + addResult( + factory.createExportDeclaration( + /*modifiers*/ + void 0, /*isTypeOnly*/ false, - getInternalSymbolName(symbol, symbolName2), - symbolName2 - )]) - ), 0 /* None */); + factory.createNamedExports([factory.createExportSpecifier( + /*isTypeOnly*/ + false, + getInternalSymbolName(symbol, symbolName2), + symbolName2 + )]) + ), + 0 /* None */ + ); } } function includePrivateSymbol(symbol) { @@ -52396,10 +52746,7 @@ ${lanes.join("\n")} return; Debug.assertIsDefined(deferredPrivatesStack[deferredPrivatesStack.length - 1]); getUnusedName(unescapeLeadingUnderscores(symbol.escapedName), symbol); - const isExternalImportAlias = !!(symbol.flags & 2097152 /* Alias */) && !some( - symbol.declarations, - (d) => !!findAncestor(d, isExportDeclaration) || isNamespaceExport(d) || isImportEqualsDeclaration(d) && !isExternalModuleReference(d.moduleReference) - ); + const isExternalImportAlias = !!(symbol.flags & 2097152 /* Alias */) && !some(symbol.declarations, (d) => !!findAncestor(d, isExportDeclaration) || isNamespaceExport(d) || isImportEqualsDeclaration(d) && !isExternalModuleReference(d.moduleReference)); deferredPrivatesStack[isExternalImportAlias ? 0 : deferredPrivatesStack.length - 1].set(getSymbolId(symbol), symbol); } function isExportingScope(enclosingDeclaration2) { @@ -52409,43 +52756,46 @@ ${lanes.join("\n")} if (canHaveModifiers(node)) { let newModifierFlags = 0 /* None */; const enclosingDeclaration2 = context.enclosingDeclaration && (isJSDocTypeAlias(context.enclosingDeclaration) ? getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); - if (additionalModifierFlags & 1 /* Export */ && enclosingDeclaration2 && (isExportingScope(enclosingDeclaration2) || isModuleDeclaration(enclosingDeclaration2)) && canHaveExportModifier(node)) { - newModifierFlags |= 1 /* Export */; + if (additionalModifierFlags & 32 /* Export */ && enclosingDeclaration2 && (isExportingScope(enclosingDeclaration2) || isModuleDeclaration(enclosingDeclaration2)) && canHaveExportModifier(node)) { + newModifierFlags |= 32 /* Export */; } - if (addingDeclare && !(newModifierFlags & 1 /* Export */) && (!enclosingDeclaration2 || !(enclosingDeclaration2.flags & 33554432 /* Ambient */)) && (isEnumDeclaration(node) || isVariableStatement(node) || isFunctionDeclaration(node) || isClassDeclaration(node) || isModuleDeclaration(node))) { - newModifierFlags |= 2 /* Ambient */; + if (addingDeclare && !(newModifierFlags & 32 /* Export */) && (!enclosingDeclaration2 || !(enclosingDeclaration2.flags & 33554432 /* Ambient */)) && (isEnumDeclaration(node) || isVariableStatement(node) || isFunctionDeclaration(node) || isClassDeclaration(node) || isModuleDeclaration(node))) { + newModifierFlags |= 128 /* Ambient */; } - if (additionalModifierFlags & 1024 /* Default */ && (isClassDeclaration(node) || isInterfaceDeclaration(node) || isFunctionDeclaration(node))) { - newModifierFlags |= 1024 /* Default */; + if (additionalModifierFlags & 2048 /* Default */ && (isClassDeclaration(node) || isInterfaceDeclaration(node) || isFunctionDeclaration(node))) { + newModifierFlags |= 2048 /* Default */; } if (newModifierFlags) { - node = factory.updateModifiers(node, newModifierFlags | getEffectiveModifierFlags(node)); + node = factory.replaceModifiers(node, newModifierFlags | getEffectiveModifierFlags(node)); } } results.push(node); } function serializeTypeAlias(symbol, symbolName2, modifierFlags) { - var _a; + var _a2; const aliasType = getDeclaredTypeOfTypeAlias(symbol); const typeParams = getSymbolLinks(symbol).typeParameters; const typeParamDecls = map(typeParams, (p) => typeParameterToDeclaration(p, context)); - const jsdocAliasDecl = (_a = symbol.declarations) == null ? void 0 : _a.find(isJSDocTypeAlias); + const jsdocAliasDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isJSDocTypeAlias); const commentText = getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : void 0); const oldFlags = context.flags; context.flags |= 8388608 /* InTypeAlias */; const oldEnclosingDecl = context.enclosingDeclaration; context.enclosingDeclaration = jsdocAliasDecl; const typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); - addResult(setSyntheticLeadingComments( - factory.createTypeAliasDeclaration( - /*modifiers*/ - void 0, - getInternalSymbolName(symbol, symbolName2), - typeParamDecls, - typeNode + addResult( + setSyntheticLeadingComments( + factory.createTypeAliasDeclaration( + /*modifiers*/ + void 0, + getInternalSymbolName(symbol, symbolName2), + typeParamDecls, + typeNode + ), + !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }] ), - !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }] - ), modifierFlags); + modifierFlags + ); context.flags = oldFlags; context.enclosingDeclaration = oldEnclosingDecl; } @@ -52460,14 +52810,17 @@ ${lanes.join("\n")} const constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 180 /* ConstructSignature */); const indexSignatures = serializeIndexSignatures(interfaceType, baseType); const heritageClauses = !length(baseTypes) ? void 0 : [factory.createHeritageClause(96 /* ExtendsKeyword */, mapDefined(baseTypes, (b) => trySerializeAsTypeReference(b, 111551 /* Value */)))]; - addResult(factory.createInterfaceDeclaration( - /*modifiers*/ - void 0, - getInternalSymbolName(symbol, symbolName2), - typeParamDecls, - heritageClauses, - [...indexSignatures, ...constructSignatures, ...callSignatures, ...members] - ), modifierFlags); + addResult( + factory.createInterfaceDeclaration( + /*modifiers*/ + void 0, + getInternalSymbolName(symbol, symbolName2), + typeParamDecls, + heritageClauses, + [...indexSignatures, ...constructSignatures, ...callSignatures, ...members] + ), + modifierFlags + ); } function getNamespaceMembersForSerialization(symbol) { const exports = getExportsOfSymbol(symbol); @@ -52494,12 +52847,12 @@ ${lanes.join("\n")} /*isTypeOnly*/ false, factory.createNamedExports(mapDefined(filter(mergedMembers, (n) => n.escapedName !== "export=" /* ExportEquals */), (s) => { - var _a, _b; + var _a2, _b; const name = unescapeLeadingUnderscores(s.escapedName); const localName2 = getInternalSymbolName(s, name); const aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); if (containingFile && (aliasDecl ? containingFile !== getSourceFileOfNode(aliasDecl) : !some(s.declarations, (d) => getSourceFileOfNode(d) === containingFile))) { - (_b = (_a = context.tracker) == null ? void 0 : _a.reportNonlocalAugmentation) == null ? void 0 : _b.call(_a, containingFile, symbol, s); + (_b = (_a2 = context.tracker) == null ? void 0 : _a2.reportNonlocalAugmentation) == null ? void 0 : _b.call(_a2, containingFile, symbol, s); return void 0; } const target = aliasDecl && getTargetOfAliasDeclaration( @@ -52517,24 +52870,33 @@ ${lanes.join("\n")} ); })) )]); - addResult(factory.createModuleDeclaration( - /*modifiers*/ - void 0, - factory.createIdentifier(localName), - nsBody, - 32 /* Namespace */ - ), 0 /* None */); + addResult( + factory.createModuleDeclaration( + /*modifiers*/ + void 0, + factory.createIdentifier(localName), + nsBody, + 32 /* Namespace */ + ), + 0 /* None */ + ); } } function serializeEnum(symbol, symbolName2, modifierFlags) { - addResult(factory.createEnumDeclaration( - factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* Const */ : 0), - getInternalSymbolName(symbol, symbolName2), - map(filter(getPropertiesOfType(getTypeOfSymbol(symbol)), (p) => !!(p.flags & 8 /* EnumMember */)), (p) => { - const initializedValue = p.declarations && p.declarations[0] && isEnumMember(p.declarations[0]) ? getConstantValue2(p.declarations[0]) : void 0; - return factory.createEnumMember(unescapeLeadingUnderscores(p.escapedName), initializedValue === void 0 ? void 0 : typeof initializedValue === "string" ? factory.createStringLiteral(initializedValue) : factory.createNumericLiteral(initializedValue)); - }) - ), modifierFlags); + addResult( + factory.createEnumDeclaration( + factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 4096 /* Const */ : 0), + getInternalSymbolName(symbol, symbolName2), + map(filter(getPropertiesOfType(getTypeOfSymbol(symbol)), (p) => !!(p.flags & 8 /* EnumMember */)), (p) => { + const initializedValue = p.declarations && p.declarations[0] && isEnumMember(p.declarations[0]) ? getConstantValue2(p.declarations[0]) : void 0; + return factory.createEnumMember( + unescapeLeadingUnderscores(p.escapedName), + initializedValue === void 0 ? void 0 : typeof initializedValue === "string" ? factory.createStringLiteral(initializedValue) : factory.createNumericLiteral(initializedValue) + ); + }) + ), + modifierFlags + ); } function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) { const signatures = getSignaturesOfType(type, 0 /* Call */); @@ -52566,13 +52928,7 @@ ${lanes.join("\n")} } function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) { if (length(props)) { - const localVsRemoteMap = arrayToMultiMap( - props, - (p) => !length(p.declarations) || some( - p.declarations, - (d) => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration) - ) ? "local" : "remote" - ); + const localVsRemoteMap = arrayToMultiMap(props, (p) => !length(p.declarations) || some(p.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)) ? "local" : "remote"); const localProps = localVsRemoteMap.get("local") || emptyArray; let fakespace = parseNodeFactory.createModuleDeclaration( /*modifiers*/ @@ -52613,7 +52969,7 @@ ${lanes.join("\n")} factory.createIdentifier("default" /* Default */) )]) ) : d); - const exportModifierStripped = every(defaultReplaced, (d) => hasSyntacticModifier(d, 1 /* Export */)) ? map(defaultReplaced, removeExportModifier) : defaultReplaced; + const exportModifierStripped = every(defaultReplaced, (d) => hasSyntacticModifier(d, 32 /* Export */)) ? map(defaultReplaced, removeExportModifier) : defaultReplaced; fakespace = factory.updateModuleDeclaration( fakespace, fakespace.modifiers, @@ -52649,10 +53005,7 @@ ${lanes.join("\n")} } return cleanup(factory.createExpressionWithTypeArguments( expr, - map( - e.typeArguments, - (a) => serializeExistingTypeNode(context, a, includePrivateSymbol, bundled) || typeToTypeNodeHelper(getTypeFromTypeNode(a), context) - ) + map(e.typeArguments, (a) => serializeExistingTypeNode(context, a, includePrivateSymbol, bundled) || typeToTypeNodeHelper(getTypeFromTypeNode(a), context)) )); function cleanup(result2) { context.enclosingDeclaration = oldEnclosing; @@ -52665,8 +53018,8 @@ ${lanes.join("\n")} return void 0; } function serializeAsClass(symbol, localName, modifierFlags) { - var _a, _b; - const originalDecl = (_a = symbol.declarations) == null ? void 0 : _a.find(isClassLike); + var _a2, _b; + const originalDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isClassLike); const oldEnclosing = context.enclosingDeclaration; context.enclosingDeclaration = originalDecl || oldEnclosing; const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -52719,21 +53072,27 @@ ${lanes.join("\n")} ); const isNonConstructableClassLikeInJsFile = !isClass && !!symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && !some(getSignaturesOfType(staticType, 1 /* Construct */)); const constructors = isNonConstructableClassLikeInJsFile ? [factory.createConstructorDeclaration( - factory.createModifiersFromModifierFlags(8 /* Private */), + factory.createModifiersFromModifierFlags(2 /* Private */), [], /*body*/ void 0 )] : serializeSignatures(1 /* Construct */, staticType, staticBaseType, 176 /* Constructor */); const indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; - addResult(setTextRange(factory.createClassDeclaration( - /*modifiers*/ - void 0, - localName, - typeParamDecls, - heritageClauses, - [...indexSignatures, ...staticMembers, ...constructors, ...publicProperties, ...privateProperties] - ), symbol.declarations && filter(symbol.declarations, (d) => isClassDeclaration(d) || isClassExpression(d))[0]), modifierFlags); + addResult( + setTextRange( + factory.createClassDeclaration( + /*modifiers*/ + void 0, + localName, + typeParamDecls, + heritageClauses, + [...indexSignatures, ...staticMembers, ...constructors, ...publicProperties, ...privateProperties] + ), + symbol.declarations && filter(symbol.declarations, (d) => isClassDeclaration(d) || isClassExpression(d))[0] + ), + modifierFlags + ); } function getSomeTargetNameFromDeclarations(declarations) { return firstDefined(declarations, (d) => { @@ -52756,7 +53115,7 @@ ${lanes.join("\n")} }); } function serializeAsAlias(symbol, localName, modifierFlags) { - var _a, _b, _c, _d, _e; + var _a2, _b, _c, _d, _e; const node = getDeclarationOfAliasSymbol(symbol); if (!node) return Debug.fail(); @@ -52776,28 +53135,31 @@ ${lanes.join("\n")} includePrivateSymbol(target); switch (node.kind) { case 208 /* BindingElement */: - if (((_b = (_a = node.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.kind) === 260 /* VariableDeclaration */) { + if (((_b = (_a2 = node.parent) == null ? void 0 : _a2.parent) == null ? void 0 : _b.kind) === 260 /* VariableDeclaration */) { const specifier2 = getSpecifierForModuleSymbol(target.parent || target, context); const { propertyName } = node; - addResult(factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ + addResult( + factory.createImportDeclaration( + /*modifiers*/ void 0, - factory.createNamedImports([factory.createImportSpecifier( + factory.createImportClause( /*isTypeOnly*/ false, - propertyName && isIdentifier(propertyName) ? factory.createIdentifier(idText(propertyName)) : void 0, - factory.createIdentifier(localName) - )]) + /*name*/ + void 0, + factory.createNamedImports([factory.createImportSpecifier( + /*isTypeOnly*/ + false, + propertyName && isIdentifier(propertyName) ? factory.createIdentifier(idText(propertyName)) : void 0, + factory.createIdentifier(localName) + )]) + ), + factory.createStringLiteral(specifier2), + /*attributes*/ + void 0 ), - factory.createStringLiteral(specifier2), - /*assertClause*/ - void 0 - ), 0 /* None */); + 0 /* None */ + ); break; } Debug.failBadSyntaxKind(((_c = node.parent) == null ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization"); @@ -52815,22 +53177,28 @@ ${lanes.join("\n")} const initializer = node.initializer; const uniqueName = factory.createUniqueName(localName); const specifier2 = getSpecifierForModuleSymbol(target.parent || target, context); - addResult(factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - uniqueName, - factory.createExternalModuleReference(factory.createStringLiteral(specifier2)) - ), 0 /* None */); - addResult(factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createIdentifier(localName), - factory.createQualifiedName(uniqueName, initializer.name) - ), modifierFlags); + addResult( + factory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + uniqueName, + factory.createExternalModuleReference(factory.createStringLiteral(specifier2)) + ), + 0 /* None */ + ); + addResult( + factory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createIdentifier(localName), + factory.createQualifiedName(uniqueName, initializer.name) + ), + modifierFlags + ); break; } case 271 /* ImportEqualsDeclaration */: @@ -52839,20 +53207,23 @@ ${lanes.join("\n")} break; } const isLocalImport = !(target.flags & 512 /* ValueModule */) && !isVariableDeclaration(node); - addResult(factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createIdentifier(localName), - isLocalImport ? symbolToName( - target, - context, - 67108863 /* All */, - /*expectsIdentifier*/ - false - ) : factory.createExternalModuleReference(factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))) - ), isLocalImport ? modifierFlags : 0 /* None */); + addResult( + factory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createIdentifier(localName), + isLocalImport ? symbolToName( + target, + context, + 67108863 /* All */, + /*expectsIdentifier*/ + false + ) : factory.createExternalModuleReference(factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))) + ), + isLocalImport ? modifierFlags : 0 /* None */ + ); break; case 270 /* NamespaceExportDeclaration */: addResult(factory.createNamespaceExportDeclaration(idText(node.name)), 0 /* None */); @@ -52860,72 +53231,84 @@ ${lanes.join("\n")} case 273 /* ImportClause */: { const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); const specifier2 = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.moduleSpecifier; - addResult(factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - factory.createIdentifier(localName), - /*namedBindings*/ - void 0 + addResult( + factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause( + /*isTypeOnly*/ + false, + factory.createIdentifier(localName), + /*namedBindings*/ + void 0 + ), + specifier2, + node.parent.attributes ), - specifier2, - node.parent.assertClause - ), 0 /* None */); + 0 /* None */ + ); break; } case 274 /* NamespaceImport */: { const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); const specifier2 = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.moduleSpecifier; - addResult(factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ + addResult( + factory.createImportDeclaration( + /*modifiers*/ void 0, - factory.createNamespaceImport(factory.createIdentifier(localName)) + factory.createImportClause( + /*isTypeOnly*/ + false, + /*name*/ + void 0, + factory.createNamespaceImport(factory.createIdentifier(localName)) + ), + specifier2, + node.parent.attributes ), - specifier2, - node.parent.parent.assertClause - ), 0 /* None */); + 0 /* None */ + ); break; } case 280 /* NamespaceExport */: - addResult(factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamespaceExport(factory.createIdentifier(localName)), - factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)) - ), 0 /* None */); + addResult( + factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamespaceExport(factory.createIdentifier(localName)), + factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)) + ), + 0 /* None */ + ); break; case 276 /* ImportSpecifier */: { const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); const specifier2 = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.parent.moduleSpecifier; - addResult(factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ + addResult( + factory.createImportDeclaration( + /*modifiers*/ void 0, - factory.createNamedImports([ - factory.createImportSpecifier( - /*isTypeOnly*/ - false, - localName !== verbatimTargetName ? factory.createIdentifier(verbatimTargetName) : void 0, - factory.createIdentifier(localName) - ) - ]) + factory.createImportClause( + /*isTypeOnly*/ + false, + /*name*/ + void 0, + factory.createNamedImports([ + factory.createImportSpecifier( + /*isTypeOnly*/ + false, + localName !== verbatimTargetName ? factory.createIdentifier(verbatimTargetName) : void 0, + factory.createIdentifier(localName) + ) + ]) + ), + specifier2, + node.parent.parent.parent.attributes ), - specifier2, - node.parent.parent.parent.assertClause - ), 0 /* None */); + 0 /* None */ + ); break; } case 281 /* ExportSpecifier */: @@ -52953,22 +53336,25 @@ ${lanes.join("\n")} } } function serializeExportSpecifier(localName, targetName, specifier) { - addResult(factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports([factory.createExportSpecifier( + addResult( + factory.createExportDeclaration( + /*modifiers*/ + void 0, /*isTypeOnly*/ false, - localName !== targetName ? targetName : void 0, - localName - )]), - specifier - ), 0 /* None */); + factory.createNamedExports([factory.createExportSpecifier( + /*isTypeOnly*/ + false, + localName !== targetName ? targetName : void 0, + localName + )]), + specifier + ), + 0 /* None */ + ); } function serializeMaybeAliasAssignment(symbol) { - var _a; + var _a2; if (symbol.flags & 4194304 /* Prototype */) { return false; } @@ -53013,20 +53399,23 @@ ${lanes.join("\n")} serializeExportSpecifier(name, getInternalSymbolName(target, symbolName(target))); } else { const varName = getUnusedName(name, symbol); - addResult(factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createIdentifier(varName), - symbolToName( - target, - context, - 67108863 /* All */, - /*expectsIdentifier*/ - false - ) - ), 0 /* None */); + addResult( + factory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createIdentifier(varName), + symbolToName( + target, + context, + 67108863 /* All */, + /*expectsIdentifier*/ + false + ) + ), + 0 /* None */ + ); serializeExportSpecifier(name, varName); } } @@ -53036,8 +53425,9 @@ ${lanes.join("\n")} const varName = getUnusedName(name, symbol); const typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol))); if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) { - serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignmentCompatibleSymbolName ? 0 /* None */ : 1 /* Export */); + serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignmentCompatibleSymbolName ? 0 /* None */ : 32 /* Export */); } else { + const flags = ((_a2 = context.enclosingDeclaration) == null ? void 0 : _a2.kind) === 267 /* ModuleDeclaration */ && (!(symbol.flags & 98304 /* Accessor */) || symbol.flags & 65536 /* SetAccessor */) ? 1 /* Let */ : 2 /* Const */; const statement = factory.createVariableStatement( /*modifiers*/ void 0, @@ -53048,11 +53438,11 @@ ${lanes.join("\n")} void 0, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled) ) - ], ((_a = context.enclosingDeclaration) == null ? void 0 : _a.kind) === 267 /* ModuleDeclaration */ ? 1 /* Let */ : 2 /* Const */) + ], flags) ); addResult( statement, - target && target.flags & 4 /* Property */ && target.escapedName === "export=" /* ExportEquals */ ? 2 /* Ambient */ : name === varName ? 1 /* Export */ : 0 /* None */ + target && target.flags & 4 /* Property */ && target.escapedName === "export=" /* ExportEquals */ ? 128 /* Ambient */ : name === varName ? 32 /* Export */ : 0 /* None */ ); } if (isExportAssignmentCompatibleSymbolName) { @@ -53074,79 +53464,114 @@ ${lanes.join("\n")} const ctxSrc = getSourceFileOfNode(context.enclosingDeclaration); return getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) && !length(getIndexInfosOfType(typeToSerialize)) && !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class !!(length(filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK - !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && some(typeToSerialize.symbol.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && !some(getPropertiesOfType(typeToSerialize), (p) => isLateBoundName(p.escapedName)) && !some(getPropertiesOfType(typeToSerialize), (p) => some(p.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && every(getPropertiesOfType(typeToSerialize), (p) => isIdentifierText(symbolName(p), languageVersion)); + !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && some(typeToSerialize.symbol.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && !some(getPropertiesOfType(typeToSerialize), (p) => isLateBoundName(p.escapedName)) && !some(getPropertiesOfType(typeToSerialize), (p) => some(p.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && every(getPropertiesOfType(typeToSerialize), (p) => { + if (!isIdentifierText(symbolName(p), languageVersion)) { + return false; + } + if (!(p.flags & 98304 /* Accessor */)) { + return true; + } + return getNonMissingTypeOfSymbol(p) === getWriteTypeOfSymbol(p); + }); } function makeSerializePropertySymbol(createProperty2, methodKind, useAccessors) { return function serializePropertySymbol(p, isStatic2, baseType) { - var _a, _b, _c, _d, _e; + var _a2, _b, _c, _d, _e; const modifierFlags = getDeclarationModifierFlagsFromSymbol(p); - const isPrivate = !!(modifierFlags & 8 /* Private */); + const isPrivate = !!(modifierFlags & 2 /* Private */); if (isStatic2 && p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) { return []; } if (p.flags & 4194304 /* Prototype */ || p.escapedName === "constructor" || baseType && getPropertyOfType(baseType, p.escapedName) && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName))) { return []; } - const flag = modifierFlags & ~512 /* Async */ | (isStatic2 ? 32 /* Static */ : 0); + const flag = modifierFlags & ~1024 /* Async */ | (isStatic2 ? 256 /* Static */ : 0); const name = getPropertyNameNodeForSymbol(p, context); - const firstPropertyLikeDecl = (_a = p.declarations) == null ? void 0 : _a.find(or(isPropertyDeclaration, isAccessor, isVariableDeclaration, isPropertySignature, isBinaryExpression, isPropertyAccessExpression)); + const firstPropertyLikeDecl = (_a2 = p.declarations) == null ? void 0 : _a2.find(or(isPropertyDeclaration, isAccessor, isVariableDeclaration, isPropertySignature, isBinaryExpression, isPropertyAccessExpression)); if (p.flags & 98304 /* Accessor */ && useAccessors) { const result = []; if (p.flags & 65536 /* SetAccessor */) { - result.push(setTextRange(factory.createSetAccessorDeclaration( - factory.createModifiersFromModifierFlags(flag), - name, - [factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "arg", - /*questionToken*/ - void 0, - isPrivate ? void 0 : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled) - )], - /*body*/ - void 0 - ), ((_b = p.declarations) == null ? void 0 : _b.find(isSetAccessor)) || firstPropertyLikeDecl)); + const setter = p.declarations && forEach(p.declarations, (d) => { + if (d.kind === 178 /* SetAccessor */) { + return d; + } + if (isCallExpression(d) && isBindableObjectDefinePropertyCall(d)) { + return forEach(d.arguments[2].properties, (propDecl) => { + const id = getNameOfDeclaration(propDecl); + if (!!id && isIdentifier(id) && idText(id) === "set") { + return propDecl; + } + }); + } + }); + Debug.assert(!!setter); + const paramSymbol = isFunctionLikeDeclaration(setter) ? getSignatureFromDeclaration(setter).parameters[0] : void 0; + result.push(setTextRange( + factory.createSetAccessorDeclaration( + factory.createModifiersFromModifierFlags(flag), + name, + [factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + paramSymbol ? parameterToParameterDeclarationName(paramSymbol, getEffectiveParameterDeclaration(paramSymbol), context) : "value", + /*questionToken*/ + void 0, + isPrivate ? void 0 : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled) + )], + /*body*/ + void 0 + ), + ((_b = p.declarations) == null ? void 0 : _b.find(isSetAccessor)) || firstPropertyLikeDecl + )); } if (p.flags & 32768 /* GetAccessor */) { - const isPrivate2 = modifierFlags & 8 /* Private */; - result.push(setTextRange(factory.createGetAccessorDeclaration( - factory.createModifiersFromModifierFlags(flag), - name, - [], - isPrivate2 ? void 0 : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), - /*body*/ - void 0 - ), ((_c = p.declarations) == null ? void 0 : _c.find(isGetAccessor)) || firstPropertyLikeDecl)); + const isPrivate2 = modifierFlags & 2 /* Private */; + result.push(setTextRange( + factory.createGetAccessorDeclaration( + factory.createModifiersFromModifierFlags(flag), + name, + [], + isPrivate2 ? void 0 : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + /*body*/ + void 0 + ), + ((_c = p.declarations) == null ? void 0 : _c.find(isGetAccessor)) || firstPropertyLikeDecl + )); } return result; } else if (p.flags & (4 /* Property */ | 3 /* Variable */ | 98304 /* Accessor */)) { - return setTextRange(createProperty2( - factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), - name, - p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, - isPrivate ? void 0 : serializeTypeForDeclaration(context, getWriteTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), - // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 - // interface members can't have initializers, however class members _can_ - /*initializer*/ - void 0 - ), ((_d = p.declarations) == null ? void 0 : _d.find(or(isPropertyDeclaration, isVariableDeclaration))) || firstPropertyLikeDecl); + return setTextRange( + createProperty2( + factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 8 /* Readonly */ : 0) | flag), + name, + p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, + isPrivate ? void 0 : serializeTypeForDeclaration(context, getWriteTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 + // interface members can't have initializers, however class members _can_ + /*initializer*/ + void 0 + ), + ((_d = p.declarations) == null ? void 0 : _d.find(or(isPropertyDeclaration, isVariableDeclaration))) || firstPropertyLikeDecl + ); } if (p.flags & (8192 /* Method */ | 16 /* Function */)) { const type = getTypeOfSymbol(p); const signatures = getSignaturesOfType(type, 0 /* Call */); - if (flag & 8 /* Private */) { - return setTextRange(createProperty2( - factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), - name, - p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ), ((_e = p.declarations) == null ? void 0 : _e.find(isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); + if (flag & 2 /* Private */) { + return setTextRange( + createProperty2( + factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 8 /* Readonly */ : 0) | flag), + name, + p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + ), + ((_e = p.declarations) == null ? void 0 : _e.find(isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0] + ); } const results2 = []; for (const sig of signatures) { @@ -53213,17 +53638,20 @@ ${lanes.join("\n")} let privateProtected = 0; for (const s of signatures) { if (s.declaration) { - privateProtected |= getSelectedEffectiveModifierFlags(s.declaration, 8 /* Private */ | 16 /* Protected */); + privateProtected |= getSelectedEffectiveModifierFlags(s.declaration, 2 /* Private */ | 4 /* Protected */); } } if (privateProtected) { - return [setTextRange(factory.createConstructorDeclaration( - factory.createModifiersFromModifierFlags(privateProtected), - /*parameters*/ - [], - /*body*/ - void 0 - ), signatures[0].declaration)]; + return [setTextRange( + factory.createConstructorDeclaration( + factory.createModifiersFromModifierFlags(privateProtected), + /*parameters*/ + [], + /*body*/ + void 0 + ), + signatures[0].declaration + )]; } } const results2 = []; @@ -53305,7 +53733,7 @@ ${lanes.join("\n")} } } function getUnusedName(input, symbol) { - var _a, _b; + var _a2, _b; const id = symbol ? getSymbolId(symbol) : void 0; if (id) { if (context.remappedSymbolNames.has(id)) { @@ -53317,7 +53745,7 @@ ${lanes.join("\n")} } let i = 0; const original = input; - while ((_a = context.usedSymbolNames) == null ? void 0 : _a.has(input)) { + while ((_a2 = context.usedSymbolNames) == null ? void 0 : _a2.has(input)) { i++; input = `${original}_${i}`; } @@ -53403,10 +53831,10 @@ ${lanes.join("\n")} return result || types; } function visibilityToString(flags) { - if (flags === 8 /* Private */) { + if (flags === 2 /* Private */) { return "private"; } - if (flags === 16 /* Protected */) { + if (flags === 4 /* Protected */) { return "protected"; } return "public"; @@ -53445,6 +53873,10 @@ ${lanes.join("\n")} } } function getNameOfSymbolAsWritten(symbol, context) { + var _a; + if ((_a = context == null ? void 0 : context.remappedSymbolReferences) == null ? void 0 : _a.has(getSymbolId(symbol))) { + symbol = context.remappedSymbolReferences.get(getSymbolId(symbol)); + } if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && // If it's not the first part of an entity name, it must print as `default` (!(context.flags & 16777216 /* InInitialEntityName */) || // if the symbol is synthesized, it will only be referenced externally it must print as `default` !symbol.declarations || // if not in the same binding context (source file, module declaration), it must print as `default` @@ -53520,7 +53952,7 @@ ${lanes.join("\n")} return true; } const parent2 = getDeclarationContainer(node); - if (!(getCombinedModifierFlagsCached(node) & 1 /* Export */) && !(node.kind !== 271 /* ImportEqualsDeclaration */ && parent2.kind !== 312 /* SourceFile */ && parent2.flags & 33554432 /* Ambient */)) { + if (!(getCombinedModifierFlagsCached(node) & 32 /* Export */) && !(node.kind !== 271 /* ImportEqualsDeclaration */ && parent2.kind !== 312 /* SourceFile */ && parent2.flags & 33554432 /* Ambient */)) { return isGlobalSourceFile(parent2); } return isDeclarationVisible(parent2); @@ -53530,7 +53962,7 @@ ${lanes.join("\n")} case 178 /* SetAccessor */: case 174 /* MethodDeclaration */: case 173 /* MethodSignature */: - if (hasEffectiveModifier(node, 8 /* Private */ | 16 /* Protected */)) { + if (hasEffectiveModifier(node, 2 /* Private */ | 4 /* Protected */)) { return false; } case 176 /* Constructor */: @@ -53702,10 +54134,6 @@ ${lanes.join("\n")} const prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : void 0; } - function getTypeOfPropertyOrIndexSignature(type, name) { - var _a; - return getTypeOfPropertyOfType(type, name) || ((_a = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a.type) || unknownType; - } function getTypeOfPropertyOrIndexSignatureOfType(type, name) { var _a; let propType; @@ -53753,7 +54181,7 @@ ${lanes.join("\n")} const unspreadableToRestKeys = []; for (const prop of getPropertiesOfType(source)) { const literalTypeFromProperty = getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */); - if (!isTypeAssignableTo(literalTypeFromProperty, omitKeyType) && !(getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) && isSpreadableProperty(prop)) { + if (!isTypeAssignableTo(literalTypeFromProperty, omitKeyType) && !(getDeclarationModifierFlagsFromSymbol(prop) & (2 /* Private */ | 4 /* Protected */)) && isSpreadableProperty(prop)) { spreadableProperties.push(prop); } else { unspreadableToRestKeys.push(literalTypeFromProperty); @@ -53842,18 +54270,23 @@ ${lanes.join("\n")} return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : void 0; } function getTypeForBindingElement(declaration) { - const checkMode = declaration.dotDotDotToken ? 64 /* RestBindingElement */ : 0 /* Normal */; + const checkMode = declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */; const parentType = getTypeForBindingElementParent(declaration.parent.parent, checkMode); - return parentType && getBindingElementTypeFromParentType(declaration, parentType); + return parentType && getBindingElementTypeFromParentType( + declaration, + parentType, + /*noTupleBoundsCheck*/ + false + ); } - function getBindingElementTypeFromParentType(declaration, parentType) { + function getBindingElementTypeFromParentType(declaration, parentType, noTupleBoundsCheck) { if (isTypeAny(parentType)) { return parentType; } const pattern = declaration.parent; if (strictNullChecks && declaration.flags & 33554432 /* Ambient */ && isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); - } else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) { + } else if (strictNullChecks && pattern.parent.initializer && !hasTypeFacts(getTypeOfInitializer(pattern.parent.initializer), 65536 /* EQUndefined */)) { parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); } let type; @@ -53885,7 +54318,7 @@ ${lanes.join("\n")} type = everyType(baseConstraint, isTupleType) ? mapType(baseConstraint, (t) => sliceTupleType(t, index)) : createArrayType(elementType); } else if (isArrayLikeType(parentType)) { const indexType = getNumberLiteralType(index); - const accessFlags = 32 /* ExpressionPosition */ | (hasDefaultValue(declaration) ? 16 /* NoTupleBoundsCheck */ : 0); + const accessFlags = 32 /* ExpressionPosition */ | (noTupleBoundsCheck || hasDefaultValue(declaration) ? 16 /* NoTupleBoundsCheck */ : 0); const declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, accessFlags, declaration.name) || errorType; type = getFlowTypeOfDestructuring(declaration, declaredType); } else { @@ -53896,7 +54329,7 @@ ${lanes.join("\n")} return type; } if (getEffectiveTypeAnnotationNode(walkUpBindingElementsAndPatterns(declaration))) { - return strictNullChecks && !(getTypeFacts(checkDeclarationInitializer(declaration, 0 /* Normal */)) & 16777216 /* IsUndefined */) ? getNonUndefinedType(type) : type; + return strictNullChecks && !hasTypeFacts(checkDeclarationInitializer(declaration, 0 /* Normal */), 16777216 /* IsUndefined */) ? getNonUndefinedType(type) : type; } return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* Normal */)], 2 /* Subtype */)); } @@ -53954,7 +54387,7 @@ ${lanes.join("\n")} if (declaredType) { return addOptionality(declaredType, isProperty, isOptional); } - if ((noImplicitAny || isInJSFile(declaration)) && isVariableDeclaration(declaration) && !isBindingPattern(declaration.name) && !(getCombinedModifierFlagsCached(declaration) & 1 /* Export */) && !(declaration.flags & 33554432 /* Ambient */)) { + if ((noImplicitAny || isInJSFile(declaration)) && isVariableDeclaration(declaration) && !isBindingPattern(declaration.name) && !(getCombinedModifierFlagsCached(declaration) & 32 /* Export */) && !(declaration.flags & 33554432 /* Ambient */)) { if (!(getCombinedNodeFlagsCached(declaration) & 6 /* Constant */) && (!declaration.initializer || isNullOrUndefined3(declaration.initializer))) { return autoType; } @@ -54002,7 +54435,7 @@ ${lanes.join("\n")} if (isPropertyDeclaration(declaration) && (noImplicitAny || isInJSFile(declaration))) { if (!hasStaticModifier(declaration)) { const constructor = findConstructorDeclaration(declaration.parent); - const type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : getEffectiveModifierFlags(declaration) & 2 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0; + const type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : getEffectiveModifierFlags(declaration) & 128 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0; return type && addOptionality( type, /*isProperty*/ @@ -54011,7 +54444,7 @@ ${lanes.join("\n")} ); } else { const staticBlocks = filter(declaration.parent.members, isClassStaticBlockDeclaration); - const type = staticBlocks.length ? getFlowTypeInStaticBlocks(declaration.symbol, staticBlocks) : getEffectiveModifierFlags(declaration) & 2 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0; + const type = staticBlocks.length ? getFlowTypeInStaticBlocks(declaration.symbol, staticBlocks) : getEffectiveModifierFlags(declaration) & 128 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0; return type && addOptionality( type, /*isProperty*/ @@ -54115,7 +54548,7 @@ ${lanes.join("\n")} return everyType(flowType, isNullableType) ? void 0 : convertAutoToAny(flowType); } function getFlowTypeOfProperty(reference, prop) { - const initialType = (prop == null ? void 0 : prop.valueDeclaration) && (!isAutoTypedProperty(prop) || getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + const initialType = (prop == null ? void 0 : prop.valueDeclaration) && (!isAutoTypedProperty(prop) || getEffectiveModifierFlags(prop.valueDeclaration) & 128 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType; return getFlowTypeOfReference(reference, autoType, initialType); } function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { @@ -54739,6 +55172,9 @@ ${lanes.join("\n")} function getTypeOfAlias(symbol) { const links = getSymbolLinks(symbol); if (!links.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } const targetSymbol = resolveAlias(symbol); const exportSymbol = symbol.declarations && getTargetOfAliasDeclaration( getDeclarationOfAliasSymbol(symbol), @@ -54747,6 +55183,10 @@ ${lanes.join("\n")} ); 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 : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; + if (!popTypeResolution()) { + reportCircularityError(exportSymbol ?? symbol); + return links.type = errorType; + } } return links.type; } @@ -54760,20 +55200,19 @@ ${lanes.join("\n")} } function reportCircularityError(symbol) { const declaration = symbol.valueDeclaration; - if (getEffectiveTypeAnnotationNode(declaration)) { - error2( - symbol.valueDeclaration, - Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, - symbolToString(symbol) - ); - return errorType; - } - if (noImplicitAny && (declaration.kind !== 169 /* Parameter */ || declaration.initializer)) { - error2( - symbol.valueDeclaration, - Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, - symbolToString(symbol) - ); + if (declaration) { + if (getEffectiveTypeAnnotationNode(declaration)) { + error2(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return errorType; + } + if (noImplicitAny && (declaration.kind !== 169 /* Parameter */ || declaration.initializer)) { + error2(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + } else if (symbol.flags & 2097152 /* Alias */) { + const node = getDeclarationOfAliasSymbol(symbol); + if (node) { + error2(node, Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } } return anyType; } @@ -54801,7 +55240,7 @@ ${lanes.join("\n")} return checkFlags & 2 /* SyntheticProperty */ ? checkFlags & 65536 /* DeferredType */ ? getWriteTypeOfSymbolWithDeferredType(symbol) || getTypeOfSymbolWithDeferredType(symbol) : ( // NOTE: cast to TransientSymbol should be safe because only TransientSymbols can have CheckFlags.SyntheticProperty symbol.links.writeType || symbol.links.type - ) : getTypeOfSymbol(symbol); + ) : removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & 16777216 /* Optional */)); } if (symbol.flags & 98304 /* Accessor */) { return checkFlags & 1 /* Instantiated */ ? getWriteTypeOfInstantiatedSymbol(symbol) : getWriteTypeOfAccessors(symbol); @@ -54984,10 +55423,7 @@ ${lanes.join("\n")} function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { const typeArgCount = length(typeArgumentNodes); const isJavascript = isInJSFile(location); - return filter( - getSignaturesOfType(type, 1 /* Construct */), - (sig) => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters) - ); + return filter(getSignaturesOfType(type, 1 /* Construct */), (sig) => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters)); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { const signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); @@ -55134,16 +55570,12 @@ ${lanes.join("\n")} return type.resolvedBaseTypes = emptyArray; } if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) { - error2( - type.symbol.valueDeclaration, - Diagnostics.Type_0_recursively_references_itself_as_a_base_type, - typeToString( - type, - /*enclosingDeclaration*/ - void 0, - 2 /* WriteArrayAsGenericType */ - ) - ); + error2(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString( + type, + /*enclosingDeclaration*/ + void 0, + 2 /* WriteArrayAsGenericType */ + )); return type.resolvedBaseTypes = emptyArray; } if (type.resolvedBaseTypes === resolvingEmptyArray) { @@ -55297,7 +55729,9 @@ ${lanes.join("\n")} if (hasBindableName(member)) { const memberSymbol = getSymbolOfDeclaration(member); const value = getEnumMemberValue(member); - const memberType = getFreshTypeOfLiteralType(value !== void 0 ? getEnumLiteralType(value, getSymbolId(symbol), memberSymbol) : createComputedEnumType(memberSymbol)); + const memberType = getFreshTypeOfLiteralType( + value !== void 0 ? getEnumLiteralType(value, getSymbolId(symbol), memberSymbol) : createComputedEnumType(memberSymbol) + ); getSymbolLinks(memberSymbol).declaredType = memberType; memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } @@ -55510,7 +55944,7 @@ ${lanes.join("\n")} if (!lateSymbol) lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */)); const earlySymbol = earlySymbols && earlySymbols.get(memberName); - if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { + if (!(parent2.flags & 32 /* Class */) && (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol)) { const declarations = earlySymbol ? concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; const name = !(type.flags & 8192 /* UniqueESSymbol */) && unescapeLeadingUnderscores(memberName) || declarationNameToString(declName); forEach(declarations, (declaration) => error2(getNameOfDeclaration(declaration) || declaration, Diagnostics.Property_0_was_also_declared_here, name)); @@ -55562,7 +55996,28 @@ ${lanes.join("\n")} } } } - links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols; + let resolved = combineSymbolTables(earlySymbols, lateSymbols); + if (symbol.flags & 33554432 /* Transient */ && links.cjsExportMerged && symbol.declarations) { + for (const decl of symbol.declarations) { + const original = getSymbolLinks(decl.symbol)[resolutionKind]; + if (!resolved) { + resolved = original; + continue; + } + if (!original) + continue; + original.forEach((s, name) => { + const existing = resolved.get(name); + if (!existing) + resolved.set(name, s); + else if (existing === s) + return; + else + resolved.set(name, mergeSymbol(existing, s)); + }); + } + } + links[resolutionKind] = resolved || emptySymbols; } return links[resolutionKind]; } @@ -55621,7 +56076,13 @@ ${lanes.join("\n")} const baseTypes = getBaseTypes(source); if (baseTypes.length) { if (source.symbol && members === getMembersOfSymbol(source.symbol)) { - members = createSymbolTable(source.declaredProperties); + const symbolTable = createSymbolTable(); + for (const symbol of members.values()) { + if (!(symbol.flags & 262144 /* TypeParameter */)) { + symbolTable.set(symbol.escapedName, symbol); + } + } + members = symbolTable; } setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos); const thisArgument = lastOrUndefined(typeArguments); @@ -55652,7 +56113,7 @@ ${lanes.join("\n")} resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { - const sig = new Signature15(checker, flags); + const sig = new Signature14(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -55705,10 +56166,7 @@ ${lanes.join("\n")} return signature.optionalCallSignatureCache[key] || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags)); } function createOptionalCallSignature(signature, callChainFlags) { - Debug.assert( - callChainFlags === 8 /* IsInnerCallChain */ || callChainFlags === 16 /* IsOuterCallChain */, - "An optional call signature can either be for an inner call chain or an outer call chain, but not both." - ); + Debug.assert(callChainFlags === 8 /* IsInnerCallChain */ || callChainFlags === 16 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both."); const result = cloneSignature(signature); result.flags |= callChainFlags; return result; @@ -55757,7 +56215,7 @@ ${lanes.join("\n")} const baseConstructorType = getBaseConstructorTypeOfClass(classType); const baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); const declaration = getClassLikeDeclarationOfSymbol(classType.symbol); - const isAbstract = !!declaration && hasSyntacticModifier(declaration, 256 /* Abstract */); + const isAbstract = !!declaration && hasSyntacticModifier(declaration, 64 /* Abstract */); if (baseSignatures.length === 0) { return [createSignature( /*declaration*/ @@ -55944,13 +56402,14 @@ ${lanes.join("\n")} const paramName = leftName === rightName ? leftName : !leftName ? rightName : !rightName ? leftName : void 0; const paramSymbol = createSymbol( 1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), - paramName || `arg${i}` + paramName || `arg${i}`, + isRestParam ? 32768 /* RestParameter */ : isOptional ? 16384 /* OptionalParameter */ : 0 ); paramSymbol.links.type = isRestParam ? createArrayType(unionParamType) : unionParamType; params[i] = paramSymbol; } if (needsExtraRestElement) { - const restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args"); + const restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args", 32768 /* RestParameter */); restParamSymbol.links.type = createArrayType(getTypeAtPosition(shorter, longestCount)); if (shorter === right) { restParamSymbol.links.type = instantiateType(restParamSymbol.links.type, mapper); @@ -55995,11 +56454,7 @@ ${lanes.join("\n")} for (const info of sourceInfos) { const indexType = info.keyType; if (every(types, (t) => !!getIndexInfoOfType(t, indexType))) { - result.push(createIndexInfo( - indexType, - getUnionType(map(types, (t) => getIndexTypeOfType(t, indexType))), - some(types, (t) => getIndexInfoOfType(t, indexType).isReadonly) - )); + result.push(createIndexInfo(indexType, getUnionType(map(types, (t) => getIndexTypeOfType(t, indexType))), some(types, (t) => getIndexInfoOfType(t, indexType).isReadonly))); } } return result; @@ -56091,11 +56546,7 @@ ${lanes.join("\n")} for (let i = 0; i < indexInfos.length; i++) { const info = indexInfos[i]; if (info.keyType === newInfo.keyType) { - indexInfos[i] = createIndexInfo( - info.keyType, - union ? getUnionType([info.type, newInfo.type]) : getIntersectionType([info.type, newInfo.type]), - union ? info.isReadonly || newInfo.isReadonly : info.isReadonly && newInfo.isReadonly - ); + indexInfos[i] = createIndexInfo(info.keyType, union ? getUnionType([info.type, newInfo.type]) : getIntersectionType([info.type, newInfo.type]), union ? info.isReadonly || newInfo.isReadonly : info.isReadonly && newInfo.isReadonly); return indexInfos; } } @@ -56175,20 +56626,23 @@ ${lanes.join("\n")} const classType = getDeclaredTypeOfClassOrInterface(symbol); let constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : emptyArray; if (symbol.flags & 16 /* Function */) { - constructSignatures = addRange(constructSignatures.slice(), mapDefined( - type.callSignatures, - (sig) => isJSConstructor(sig.declaration) ? createSignature( - sig.declaration, - sig.typeParameters, - sig.thisParameter, - sig.parameters, - classType, - /*resolvedTypePredicate*/ - void 0, - sig.minArgumentCount, - sig.flags & 167 /* PropagatingFlags */ - ) : void 0 - )); + constructSignatures = addRange( + constructSignatures.slice(), + mapDefined( + type.callSignatures, + (sig) => isJSConstructor(sig.declaration) ? createSignature( + sig.declaration, + sig.typeParameters, + sig.thisParameter, + sig.parameters, + classType, + /*resolvedTypePredicate*/ + void 0, + sig.minArgumentCount, + sig.flags & 167 /* PropagatingFlags */ + ) : void 0 + ) + ); } if (!constructSignatures.length) { constructSignatures = getDefaultConstructSignatures(classType); @@ -56310,11 +56764,7 @@ ${lanes.join("\n")} const isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp)); const stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */; const lateFlag = modifiersProp ? getIsLateCheckFlag(modifiersProp) : 0; - const prop = createSymbol( - 4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), - propName, - lateFlag | 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0) - ); + const prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, lateFlag | 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0)); prop.links.mappedType = type; prop.links.nameType = propNameType; prop.links.keyType = keyType; @@ -56327,7 +56777,9 @@ ${lanes.join("\n")} } else if (isValidIndexKeyType(propNameType) || propNameType.flags & (1 /* Any */ | 32 /* Enum */)) { const indexKeyType = propNameType.flags & (1 /* Any */ | 4 /* String */) ? stringType : propNameType.flags & (8 /* Number */ | 32 /* Enum */) ? numberType : propNameType; const propType = instantiateType(templateType, appendTypeMapping(type.mapper, typeParameter, keyType)); - const indexInfo = createIndexInfo(indexKeyType, propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + const modifiersIndexInfo = getApplicableIndexInfo(modifiersType, propNameType); + const isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && (modifiersIndexInfo == null ? void 0 : modifiersIndexInfo.isReadonly)); + const indexInfo = createIndexInfo(indexKeyType, propType, isReadonly); indexInfos = appendIndexInfo( indexInfos, indexInfo, @@ -56539,7 +56991,7 @@ ${lanes.join("\n")} } function isConstTypeVariable(type, depth = 0) { var _a; - return depth < 5 && !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 2048 /* Const */)) || type.flags & 1048576 /* Union */ && some(type.types, (t) => isConstTypeVariable(t, depth)) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType, depth + 1) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type), depth + 1) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType, depth) || isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t, depth)) >= 0)); + return depth < 5 && !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 4096 /* Const */)) || type.flags & 3145728 /* UnionOrIntersection */ && some(type.types, (t) => isConstTypeVariable(t, depth)) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType, depth + 1) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type), depth + 1) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType, depth) || isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t, depth)) >= 0)); } function getConstraintOfIndexedAccess(type) { return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : void 0; @@ -56865,7 +57317,7 @@ ${lanes.join("\n")} } else if (!isUnion && !isReadonlySymbol(prop)) { checkFlags &= ~8 /* Readonly */; } - checkFlags |= (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) | (modifiers & 16 /* Protected */ ? 512 /* ContainsProtected */ : 0) | (modifiers & 8 /* Private */ ? 1024 /* ContainsPrivate */ : 0) | (modifiers & 32 /* Static */ ? 2048 /* ContainsStatic */ : 0); + checkFlags |= (!(modifiers & 6 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) | (modifiers & 4 /* Protected */ ? 512 /* ContainsProtected */ : 0) | (modifiers & 2 /* Private */ ? 1024 /* ContainsPrivate */ : 0) | (modifiers & 256 /* Static */ ? 2048 /* ContainsStatic */ : 0); if (!isPrototypeProperty(prop)) { syntheticFlag = 2 /* SyntheticProperty */; } @@ -56921,7 +57373,8 @@ ${lanes.join("\n")} const writeType = getWriteTypeOfSymbol(prop); if (writeTypes || writeType !== type) { writeTypes = append(!writeTypes ? propTypes.slice() : writeTypes, writeType); - } else if (type !== firstType) { + } + if (type !== firstType) { checkFlags |= 64 /* HasNonUniformType */; } if (isLiteralType(type) || isPatternLiteralType(type)) { @@ -57035,31 +57488,21 @@ ${lanes.join("\n")} if (type.flags & 2097152 /* Intersection */ && getObjectFlags(type) & 33554432 /* IsNeverIntersection */) { const neverProp = find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { - return chainDiagnosticMessages( - errorInfo, - Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, - typeToString( - type, - /*enclosingDeclaration*/ - void 0, - 536870912 /* NoTypeReduction */ - ), - symbolToString(neverProp) - ); + return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString( + type, + /*enclosingDeclaration*/ + void 0, + 536870912 /* NoTypeReduction */ + ), symbolToString(neverProp)); } const privateProp = find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty); if (privateProp) { - return chainDiagnosticMessages( - errorInfo, - Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, - typeToString( - type, - /*enclosingDeclaration*/ - void 0, - 536870912 /* NoTypeReduction */ - ), - symbolToString(privateProp) - ); + return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString( + type, + /*enclosingDeclaration*/ + void 0, + 536870912 /* NoTypeReduction */ + ), symbolToString(privateProp)); } } return errorInfo; @@ -57144,16 +57587,12 @@ ${lanes.join("\n")} } } } - return applicableInfos ? createIndexInfo( - unknownType, - getIntersectionType(map(applicableInfos, (info) => info.type)), - reduceLeft( - applicableInfos, - (isReadonly, info) => isReadonly && info.isReadonly, - /*initial*/ - true - ) - ) : applicableInfo ? applicableInfo : stringIndexInfo && isApplicableIndexType(keyType, stringType) ? stringIndexInfo : void 0; + return applicableInfos ? createIndexInfo(unknownType, getIntersectionType(map(applicableInfos, (info) => info.type)), reduceLeft( + applicableInfos, + (isReadonly, info) => isReadonly && info.isReadonly, + /*initial*/ + true + )) : applicableInfo ? applicableInfo : stringIndexInfo && isApplicableIndexType(keyType, stringType) ? stringIndexInfo : void 0; } function isApplicableIndexType(source, target) { return isTypeAssignableTo(source, target) || target === stringType && isTypeAssignableTo(source, numberType) || target === numberType && (source === numericStringType || !!(source.flags & 128 /* StringLiteral */) && isNumericLiteralName(source.value)); @@ -57220,7 +57659,7 @@ ${lanes.join("\n")} } const iife = getImmediatelyInvokedFunctionExpression(node.parent); if (iife) { - return !node.type && !node.dotDotDotToken && node.parent.parameters.indexOf(node) >= iife.arguments.length; + return !node.type && !node.dotDotDotToken && node.parent.parameters.indexOf(node) >= getEffectiveCallArguments(iife).length; } return false; } @@ -57330,7 +57769,7 @@ ${lanes.join("\n")} if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { flags |= 1 /* HasRestParameter */; } - if (isConstructorTypeNode(declaration) && hasSyntacticModifier(declaration, 256 /* Abstract */) || isConstructorDeclaration(declaration) && hasSyntacticModifier(declaration.parent, 256 /* Abstract */)) { + if (isConstructorTypeNode(declaration) && hasSyntacticModifier(declaration, 64 /* Abstract */) || isConstructorDeclaration(declaration) && hasSyntacticModifier(declaration.parent, 64 /* Abstract */)) { flags |= 4 /* Abstract */; } links.resolvedSignature = createSignature( @@ -57505,12 +57944,7 @@ ${lanes.join("\n")} /*parameterIndex*/ void 0, type - ) : createTypePredicate( - node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, - parameterName.escapedText, - findIndex(signature.parameters, (p) => p.escapedName === parameterName.escapedText), - type - ); + ) : createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, findIndex(signature.parameters, (p) => p.escapedName === parameterName.escapedText), type); } function getUnionOrIntersectionType(types, kind, unionReduction) { return kind !== 2097152 /* Intersection */ ? getUnionType(types, unionReduction) : getIntersectionType(types); @@ -57705,12 +58139,7 @@ ${lanes.join("\n")} if (parameter.type) { forEachType(getTypeFromTypeNode(parameter.type), (keyType) => { if (isValidIndexKeyType(keyType) && !findIndexInfo(indexInfos, keyType)) { - indexInfos.push(createIndexInfo( - keyType, - declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, - hasEffectiveModifier(declaration, 64 /* Readonly */), - declaration - )); + indexInfos.push(createIndexInfo(keyType, declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, hasEffectiveModifier(declaration, 8 /* Readonly */), declaration)); } }); } @@ -57741,9 +58170,12 @@ ${lanes.join("\n")} if (index < typeParameters.length) { const declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); if (declaredConstraint) { - const mapper = makeDeferredTypeMapper(typeParameters, typeParameters.map((_, index2) => () => { - return getEffectiveTypeArgumentAtIndex(typeReference, typeParameters, index2); - })); + const mapper = makeDeferredTypeMapper( + typeParameters, + typeParameters.map((_, index2) => () => { + return getEffectiveTypeArgumentAtIndex(typeReference, typeParameters, index2); + }) + ); const constraint = instantiateType(declaredConstraint, mapper); if (constraint !== typeParameter) { inferences = append(inferences, constraint); @@ -57760,10 +58192,7 @@ ${lanes.join("\n")} } else if (grandParent.kind === 200 /* MappedType */ && grandParent.type && skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 194 /* ConditionalType */ && grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 200 /* MappedType */ && grandParent.parent.checkType.type) { const checkMappedType2 = grandParent.parent.checkType; const nodeType = getTypeFromTypeNode(checkMappedType2.type); - inferences = append(inferences, instantiateType( - nodeType, - makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(checkMappedType2.typeParameter)), checkMappedType2.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType2.typeParameter.constraint) : keyofConstraintType) - )); + inferences = append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(checkMappedType2.typeParameter)), checkMappedType2.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType2.typeParameter.constraint) : keyofConstraintType))); } } } @@ -57938,12 +58367,7 @@ ${lanes.join("\n")} const id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); let instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateTypeWithAlias( - type, - createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(symbol.valueDeclaration))), - aliasSymbol, - aliasTypeArguments - )); + links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); } return instantiation; } @@ -57953,7 +58377,13 @@ ${lanes.join("\n")} const id = getAliasId(symbol, typeArguments); let errorType2 = errorTypes.get(id); if (!errorType2) { - errorType2 = createIntrinsicType(1 /* Any */, "error"); + errorType2 = createIntrinsicType( + 1 /* Any */, + "error", + /*objectFlags*/ + void 0, + `alias ${id}` + ); errorType2.aliasSymbol = symbol; errorType2.aliasTypeArguments = typeArguments; errorTypes.set(id, errorType2); @@ -58758,8 +59188,7 @@ ${lanes.join("\n")} if (elementFlags.length === 1 && elementFlags[0] & 4 /* Rest */) { return readonly ? globalReadonlyArrayType : globalArrayType; } - const memberIds = mapDefined(namedMemberDeclarations, (node) => node ? getNodeId(node) : void 0); - const key = map(elementFlags, (f) => f & 1 /* Required */ ? "#" : f & 2 /* Optional */ ? "?" : f & 4 /* Rest */ ? "." : "*").join() + (readonly ? "R" : "") + (memberIds.length ? "," + memberIds.join(",") : ""); + const key = map(elementFlags, (f) => f & 1 /* Required */ ? "#" : f & 2 /* Optional */ ? "?" : f & 4 /* Rest */ ? "." : "*").join() + (readonly ? "R" : "") + (some(namedMemberDeclarations, (node) => !!node) ? "," + map(namedMemberDeclarations, (node) => node ? getNodeId(node) : "_").join(",") : ""); let type = tupleTypes.get(key); if (!type) { tupleTypes.set(key, type = createTupleTargetType(elementFlags, readonly, namedMemberDeclarations)); @@ -58779,11 +59208,7 @@ ${lanes.join("\n")} const flags = elementFlags[i]; combinedFlags |= flags; if (!(combinedFlags & 12 /* Variable */)) { - const property = createSymbol( - 4 /* Property */ | (flags & 2 /* Optional */ ? 16777216 /* Optional */ : 0), - "" + i, - readonly ? 8 /* Readonly */ : 0 - ); + const property = createSymbol(4 /* Property */ | (flags & 2 /* Optional */ ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0); property.links.tupleLabelDeclaration = namedMemberDeclarations == null ? void 0 : namedMemberDeclarations[i]; property.links.type = typeParameter; properties.push(property); @@ -58854,7 +59279,10 @@ ${lanes.join("\n")} } else if (isTupleType(type)) { const elements = getElementTypes(type); if (elements.length + expandedTypes.length >= 1e4) { - error2(currentNode, isPartOfTypeNode(currentNode) ? Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent : Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + error2( + currentNode, + isPartOfTypeNode(currentNode) ? Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent : Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent + ); return errorType; } forEach(elements, (t, n) => { @@ -58873,10 +59301,7 @@ ${lanes.join("\n")} expandedFlags[i] = 1 /* Required */; } if (firstRestIndex >= 0 && firstRestIndex < lastOptionalOrRestIndex) { - expandedTypes[firstRestIndex] = getUnionType(sameMap( - expandedTypes.slice(firstRestIndex, lastOptionalOrRestIndex + 1), - (t, i) => expandedFlags[firstRestIndex + i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t - )); + expandedTypes[firstRestIndex] = getUnionType(sameMap(expandedTypes.slice(firstRestIndex, lastOptionalOrRestIndex + 1), (t, i) => expandedFlags[firstRestIndex + i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t)); expandedTypes.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); expandedFlags.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); expandedDeclarations.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); @@ -58914,10 +59339,7 @@ ${lanes.join("\n")} ); } function getKnownKeysOfTupleType(type) { - return getUnionType(append( - arrayOf(type.target.fixedLength, (i) => getStringLiteralType("" + i)), - getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType) - )); + return getUnionType(append(arrayOf(type.target.fixedLength, (i) => getStringLiteralType("" + i)), getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType))); } function getStartElementCount(type, flags) { const index = findIndex(type.elementFlags, (f) => !(f & flags)); @@ -59223,12 +59645,7 @@ ${lanes.join("\n")} const links = getNodeLinks(node); if (!links.resolvedType) { const aliasSymbol = getAliasSymbolForTypeNode(node); - links.resolvedType = getUnionType( - map(node.types, getTypeFromTypeNode), - 1 /* Literal */, - aliasSymbol, - getTypeArgumentsForAliasSymbol(aliasSymbol) - ); + links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -59458,15 +59875,14 @@ ${lanes.join("\n")} function getConstituentCountOfTypes(types) { return reduceLeft(types, (n, t) => n + getConstituentCount(t), 0); } - function areIntersectedTypesAvoidingPrimitiveReduction(t1, t2) { - return !!(t1.flags & (4 /* String */ | 8 /* Number */ | 64 /* BigInt */)) && t2 === emptyTypeLiteralType; - } function getTypeFromIntersectionTypeNode(node) { const links = getNodeLinks(node); if (!links.resolvedType) { const aliasSymbol = getAliasSymbolForTypeNode(node); const types = map(node.types, getTypeFromTypeNode); - const noSupertypeReduction = types.length === 2 && (areIntersectedTypesAvoidingPrimitiveReduction(types[0], types[1]) || areIntersectedTypesAvoidingPrimitiveReduction(types[1], types[0])); + const emptyIndex = types.length === 2 ? types.indexOf(emptyTypeLiteralType) : -1; + const t = emptyIndex >= 0 ? types[1 - emptyIndex] : unknownType; + const noSupertypeReduction = !!(t.flags & (4 /* String */ | 8 /* Number */ | 64 /* BigInt */) || t.flags & 134217728 /* TemplateLiteral */ && isPatternLiteralType(t)); links.resolvedType = getIntersectionType(types, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol), noSupertypeReduction); } return links.resolvedType; @@ -59543,7 +59959,7 @@ ${lanes.join("\n")} return neverType; } function getLiteralTypeFromProperty(prop, include, includeNonPublic) { - if (includeNonPublic || !(getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { + if (includeNonPublic || !(getDeclarationModifierFlagsFromSymbol(prop) & 6 /* NonPublicAccessibilityModifier */)) { let type = getSymbolLinks(getLateBoundSymbol(prop)).nameType; if (!type) { const name = getNameOfDeclaration(prop.valueDeclaration); @@ -59577,11 +59993,7 @@ ${lanes.join("\n")} } function getIndexType(type, indexFlags = defaultIndexFlags) { type = getReducedType(type); - return shouldDeferIndexType(type, indexFlags) ? getIndexTypeForGenericType(type, indexFlags) : type.flags & 1048576 /* Union */ ? getIntersectionType(map(type.types, (t) => getIndexType(t, indexFlags))) : type.flags & 2097152 /* Intersection */ ? getUnionType(map(type.types, (t) => getIndexType(t, indexFlags))) : getObjectFlags(type) & 32 /* Mapped */ ? getIndexTypeForMappedType(type, indexFlags) : type === wildcardType ? wildcardType : type.flags & 2 /* Unknown */ ? neverType : type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType : getLiteralTypeFromProperties( - type, - (indexFlags & 2 /* NoIndexSignatures */ ? 128 /* StringLiteral */ : 402653316 /* StringLike */) | (indexFlags & 1 /* StringsOnly */ ? 0 : 296 /* NumberLike */ | 12288 /* ESSymbolLike */), - indexFlags === defaultIndexFlags - ); + return shouldDeferIndexType(type, indexFlags) ? getIndexTypeForGenericType(type, indexFlags) : type.flags & 1048576 /* Union */ ? getIntersectionType(map(type.types, (t) => getIndexType(t, indexFlags))) : type.flags & 2097152 /* Intersection */ ? getUnionType(map(type.types, (t) => getIndexType(t, indexFlags))) : getObjectFlags(type) & 32 /* Mapped */ ? getIndexTypeForMappedType(type, indexFlags) : type === wildcardType ? wildcardType : type.flags & 2 /* Unknown */ ? neverType : type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType : getLiteralTypeFromProperties(type, (indexFlags & 2 /* NoIndexSignatures */ ? 128 /* StringLiteral */ : 402653316 /* StringLike */) | (indexFlags & 1 /* StringsOnly */ ? 0 : 296 /* NumberLike */ | 12288 /* ESSymbolLike */), indexFlags === defaultIndexFlags); } function getExtractStringType(type) { if (keyofStringsOnly) { @@ -59682,11 +60094,6 @@ ${lanes.join("\n")} } function createTemplateLiteralType(texts, types) { const type = createType(134217728 /* TemplateLiteral */); - type.objectFlags = getPropagatingFlagsOfTypes( - types, - /*excludeKinds*/ - 98304 /* Nullable */ - ); type.texts = texts; type.types = types; return type; @@ -59809,7 +60216,7 @@ ${lanes.join("\n")} return autoType; } } - const propType = getTypeOfSymbol(prop); + const propType = accessFlags & 4 /* Writing */ ? getWriteTypeOfSymbol(prop) : getTypeOfSymbol(prop); return accessExpression && getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? getFlowTypeOfReference(accessExpression, propType) : accessNode && isIndexedAccessTypeNode(accessNode) && containsMissingType(propType) ? getUnionType([propType, undefinedType]) : propType; } if (everyType(objectType, isTupleType) && isNumericLiteralName(propName)) { @@ -59821,13 +60228,7 @@ ${lanes.join("\n")} error2(indexNode, Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value); return undefinedType; } - error2( - indexNode, - Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, - typeToString(objectType), - getTypeReferenceArity(objectType), - unescapeLeadingUnderscores(propName) - ); + error2(indexNode, Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), unescapeLeadingUnderscores(propName)); } else { error2(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); } @@ -59846,7 +60247,11 @@ ${lanes.join("\n")} if (indexInfo) { if (accessFlags & 2 /* NoIndexSignatures */ && indexInfo.keyType !== numberType) { if (accessExpression) { - error2(accessExpression, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType)); + if (accessFlags & 4 /* Writing */) { + error2(accessExpression, Diagnostics.Type_0_is_generic_and_can_only_be_indexed_for_reading, typeToString(originalObjectType)); + } else { + error2(accessExpression, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType)); + } } return void 0; } @@ -59985,7 +60390,15 @@ ${lanes.join("\n")} } function isPatternLiteralPlaceholderType(type) { if (type.flags & 2097152 /* Intersection */) { - return some(type.types, (t) => !!(t.flags & (2944 /* Literal */ | 65536 /* Null */ | 32768 /* Undefined */)) || isPatternLiteralPlaceholderType(t)); + let seenPlaceholder = false; + for (const t of type.types) { + if (t.flags & (2944 /* Literal */ | 98304 /* Nullable */) || isPatternLiteralPlaceholderType(t)) { + seenPlaceholder = true; + } else if (!(t.flags & 524288 /* Object */)) { + return false; + } + } + return seenPlaceholder; } return !!(type.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 64 /* BigInt */)) || isPatternLiteralType(type); } @@ -60002,7 +60415,7 @@ ${lanes.join("\n")} return !!(getGenericObjectFlags(type) & 8388608 /* IsGenericIndexType */); } function getGenericObjectFlags(type) { - if (type.flags & (3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */)) { + if (type.flags & 3145728 /* UnionOrIntersection */) { if (!(type.objectFlags & 2097152 /* IsGenericTypeComputed */)) { type.objectFlags |= 2097152 /* IsGenericTypeComputed */ | reduceLeft(type.types, (flags, t) => flags | getGenericObjectFlags(t), 0); } @@ -60014,7 +60427,7 @@ ${lanes.join("\n")} } return type.objectFlags & 12582912 /* IsGenericType */; } - return (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type) || isGenericTupleType(type) ? 4194304 /* IsGenericObjectType */ : 0) | (type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 268435456 /* StringMapping */) && !isPatternLiteralType(type) ? 8388608 /* IsGenericIndexType */ : 0); + return (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type) || isGenericTupleType(type) ? 4194304 /* IsGenericObjectType */ : 0) | (type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && !isPatternLiteralType(type) ? 8388608 /* IsGenericIndexType */ : 0); } function getSimplifiedType(type, writing) { return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) : type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) : type; @@ -60496,7 +60909,7 @@ ${lanes.join("\n")} function getAnonymousPartialType(type2) { const members = createSymbolTable(); for (const prop of getPropertiesOfType(type2)) { - if (getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) { + if (getDeclarationModifierFlagsFromSymbol(prop) & (2 /* Private */ | 4 /* Protected */)) { } else if (isSpreadableProperty(prop)) { const isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); const flags = 4 /* Property */ | 16777216 /* Optional */; @@ -60558,7 +60971,7 @@ ${lanes.join("\n")} const skippedPrivateMembers = /* @__PURE__ */ new Set(); const indexInfos = left === emptyObjectType ? getIndexInfosOfType(right) : getUnionIndexInfos([left, right]); for (const rightProp of getPropertiesOfType(right)) { - if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + if (getDeclarationModifierFlagsFromSymbol(rightProp) & (2 /* Private */ | 4 /* Protected */)) { skippedPrivateMembers.add(rightProp.escapedName); } else if (isSpreadableProperty(rightProp)) { members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly)); @@ -60980,7 +61393,12 @@ ${lanes.join("\n")} function instantiateSymbol(symbol, mapper) { const links = getSymbolLinks(symbol); if (links.type && !couldContainTypeVariables(links.type)) { - return symbol; + if (!(symbol.flags & 65536 /* SetAccessor */)) { + return symbol; + } + if (links.writeType && !couldContainTypeVariables(links.writeType)) { + return symbol; + } } if (getCheckFlags(symbol) & 1 /* Instantiated */) { symbol = links.target; @@ -61035,7 +61453,7 @@ ${lanes.join("\n")} result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); target.instantiations.set(id, result); const resultObjectFlags = getObjectFlags(result); - if (result.flags & 138117121 /* ObjectFlagsType */ && !(resultObjectFlags & 524288 /* CouldContainTypeVariablesComputed */)) { + if (result.flags & 3899393 /* ObjectFlagsType */ && !(resultObjectFlags & 524288 /* CouldContainTypeVariablesComputed */)) { const resultCouldContainTypeVariables = some(typeArguments, couldContainTypeVariables); if (!(getObjectFlags(result) & 524288 /* CouldContainTypeVariablesComputed */)) { if (resultObjectFlags & (32 /* Mapped */ | 16 /* Anonymous */ | 4 /* Reference */)) { @@ -61110,24 +61528,29 @@ ${lanes.join("\n")} if (typeVariable) { const mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapTypeWithAlias(getReducedType(mappedTypeVariable), (t) => { - if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && !isErrorType(t)) { - if (!type.declaration.nameType) { - let constraint; - if (isArrayType(t) || t.flags & 1 /* Any */ && findResolutionCycleStartIndex(typeVariable, 4 /* ImmediateBaseConstraint */) < 0 && (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, isArrayOrTupleType)) { - return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper)); - } - if (isGenericTupleType(t)) { - return instantiateMappedGenericTupleType(t, type, typeVariable, mapper); - } - if (isTupleType(t)) { - return instantiateMappedTupleType(t, type, prependTypeMapping(typeVariable, t, mapper)); + return mapTypeWithAlias( + getReducedType(mappedTypeVariable), + (t) => { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && !isErrorType(t)) { + if (!type.declaration.nameType) { + let constraint; + if (isArrayType(t) || t.flags & 1 /* Any */ && findResolutionCycleStartIndex(typeVariable, 4 /* ImmediateBaseConstraint */) < 0 && (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, isArrayOrTupleType)) { + return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper)); + } + if (isGenericTupleType(t)) { + return instantiateMappedGenericTupleType(t, type, typeVariable, mapper); + } + if (isTupleType(t)) { + return instantiateMappedTupleType(t, type, prependTypeMapping(typeVariable, t, mapper)); + } } + return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper)); } - return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper)); - } - return t; - }, aliasSymbol, aliasTypeArguments); + return t; + }, + aliasSymbol, + aliasTypeArguments + ); } } return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments); @@ -61521,10 +61944,13 @@ ${lanes.join("\n")} const resultObj = errorOutputContainer || {}; checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj); const diagnostic = resultObj.errors[resultObj.errors.length - 1]; - addRelatedInfo(diagnostic, createDiagnosticForNode( - node, - signatures === constructSignatures ? Diagnostics.Did_you_mean_to_use_new_with_this_expression : Diagnostics.Did_you_mean_to_call_this_expression - )); + addRelatedInfo( + diagnostic, + createDiagnosticForNode( + node, + signatures === constructSignatures ? Diagnostics.Did_you_mean_to_use_new_with_this_expression : Diagnostics.Did_you_mean_to_call_this_expression + ) + ); return true; } } @@ -61581,10 +62007,13 @@ ${lanes.join("\n")} ); if (resultObj.errors) { if (target.symbol && length(target.symbol.declarations)) { - addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], createDiagnosticForNode( - target.symbol.declarations[0], - Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature - )); + addRelatedInfo( + resultObj.errors[resultObj.errors.length - 1], + createDiagnosticForNode( + target.symbol.declarations[0], + Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature + ) + ); } if ((getFunctionFlags(node) & 2 /* Async */) === 0 && !getTypeOfPropertyOfType(sourceReturn, "then") && checkTypeRelatedTo( createPromiseType(sourceReturn), @@ -61593,10 +62022,13 @@ ${lanes.join("\n")} /*errorNode*/ void 0 )) { - addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], createDiagnosticForNode( - node, - Diagnostics.Did_you_mean_to_mark_this_function_as_async - )); + addRelatedInfo( + resultObj.errors[resultObj.errors.length - 1], + createDiagnosticForNode( + node, + Diagnostics.Did_you_mean_to_mark_this_function_as_async + ) + ); } return true; } @@ -61691,12 +62123,15 @@ ${lanes.join("\n")} if (!issuedElaboration && (targetProp && length(targetProp.declarations) || target.symbol && length(target.symbol.declarations))) { const targetNode = targetProp && length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; if (!getSourceFileOfNode(targetNode).hasNoDefaultLib) { - addRelatedInfo(reportedDiag, createDiagnosticForNode( - targetNode, - Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, - propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? unescapeLeadingUnderscores(propertyName) : typeToString(nameType), - typeToString(target) - )); + addRelatedInfo( + reportedDiag, + createDiagnosticForNode( + targetNode, + Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, + propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? unescapeLeadingUnderscores(propertyName) : typeToString(nameType), + typeToString(target) + ) + ); } } } @@ -61897,14 +62332,7 @@ ${lanes.join("\n")} const childrenPropName = childPropName === void 0 ? "children" : unescapeLeadingUnderscores(childPropName); const childrenTargetType = getIndexedAccessType(target, getStringLiteralType(childrenPropName)); const diagnostic = Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2; - invalidTextDiagnostic = { ...diagnostic, key: "!!ALREADY FORMATTED!!", message: formatMessage( - /*dummy*/ - void 0, - diagnostic, - tagNameText, - childrenPropName, - typeToString(childrenTargetType) - ) }; + invalidTextDiagnostic = { ...diagnostic, key: "!!ALREADY FORMATTED!!", message: formatMessage(diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) }; } return invalidTextDiagnostic; } @@ -62068,7 +62496,7 @@ ${lanes.join("\n")} if (sourceType && targetType) { const sourceSig = checkMode & 3 /* Callback */ ? void 0 : getSingleCallSignature(getNonNullableType(sourceType)); const targetSig = checkMode & 3 /* Callback */ ? void 0 : getSingleCallSignature(getNonNullableType(targetType)); - const callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && (getTypeFacts(sourceType) & 50331648 /* IsUndefinedOrNull */) === (getTypeFacts(targetType) & 50331648 /* IsUndefinedOrNull */); + const callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && getTypeFacts(sourceType, 50331648 /* IsUndefinedOrNull */) === getTypeFacts(targetType, 50331648 /* IsUndefinedOrNull */); let related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, checkMode & 8 /* StrictArity */ | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors2, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes( sourceType, targetType, @@ -62085,11 +62513,7 @@ ${lanes.join("\n")} } if (!related) { if (reportErrors2) { - errorReporter( - Diagnostics.Types_of_parameters_0_and_1_are_incompatible, - unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), - unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)) - ); + errorReporter(Diagnostics.Types_of_parameters_0_and_1_are_incompatible, unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); } return 0 /* False */; } @@ -62210,16 +62634,12 @@ ${lanes.join("\n")} const targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter( - Diagnostics.Property_0_is_missing_in_type_1, - symbolName(property), - typeToString( - getDeclaredTypeOfSymbol(targetSymbol), - /*enclosingDeclaration*/ - void 0, - 64 /* UseFullyQualifiedType */ - ) - ); + errorReporter(Diagnostics.Property_0_is_missing_in_type_1, symbolName(property), typeToString( + getDeclaredTypeOfSymbol(targetSymbol), + /*enclosingDeclaration*/ + void 0, + 64 /* UseFullyQualifiedType */ + )); enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */); } else { enumRelation.set(id, 2 /* Failed */); @@ -62367,8 +62787,10 @@ ${lanes.join("\n")} let expandingFlags = 0 /* None */; let overflow = false; let overrideNextErrorInfo = 0; + let skipParentCounter = 0; let lastSkippedInfo; let incompatibleStack; + let relationCount = 16e6 - relation.size >> 3; Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); const result = isRelatedTo( source, @@ -62382,8 +62804,19 @@ ${lanes.join("\n")} reportIncompatibleStack(); } if (overflow) { + const id = getRelationKey( + source, + target, + /*intersectionState*/ + 0 /* None */, + relation, + /*ignoreConstraints*/ + false + ); + relation.set(id, 4 /* Reported */ | 2 /* Failed */); (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: sourceDepth, targetDepth }); - const diag2 = error2(errorNode || currentNode, Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + const message = relationCount <= 0 ? Diagnostics.Excessive_complexity_comparing_types_0_and_1 : Diagnostics.Excessive_stack_depth_comparing_types_0_and_1; + const diag2 = error2(errorNode || currentNode, message, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2); } @@ -62432,6 +62865,7 @@ ${lanes.join("\n")} lastSkippedInfo = saved.lastSkippedInfo; incompatibleStack = saved.incompatibleStack; overrideNextErrorInfo = saved.overrideNextErrorInfo; + skipParentCounter = saved.skipParentCounter; relatedInfo = saved.relatedInfo; } function captureErrorCalculationState() { @@ -62440,6 +62874,7 @@ ${lanes.join("\n")} lastSkippedInfo, incompatibleStack: incompatibleStack == null ? void 0 : incompatibleStack.slice(), overrideNextErrorInfo, + skipParentCounter, relatedInfo: relatedInfo == null ? void 0 : relatedInfo.slice() }; } @@ -62544,7 +62979,15 @@ ${lanes.join("\n")} reportIncompatibleStack(); if (message.elidedInCompatabilityPyramid) return; - errorInfo = chainDiagnosticMessages(errorInfo, message, ...args); + if (skipParentCounter === 0) { + errorInfo = chainDiagnosticMessages(errorInfo, message, ...args); + } else { + skipParentCounter--; + } + } + function reportParentSkippedError(message, ...args) { + reportError(message, ...args); + skipParentCounter++; } function associateRelatedInfo(info) { Debug.assert(!!errorInfo); @@ -62881,18 +63324,9 @@ ${lanes.join("\n")} } } if (suggestion !== void 0) { - reportError( - Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, - symbolToString(prop), - typeToString(errorTarget), - suggestion - ); + reportParentSkippedError(Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion); } else { - reportError( - Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, - symbolToString(prop), - typeToString(errorTarget) - ); + reportParentSkippedError(Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget)); } } } @@ -62913,6 +63347,16 @@ ${lanes.join("\n")} } function unionOrIntersectionRelatedTo(source2, target2, reportErrors2, intersectionState) { if (source2.flags & 1048576 /* Union */) { + if (target2.flags & 1048576 /* Union */) { + const sourceOrigin = source2.origin; + if (sourceOrigin && sourceOrigin.flags & 2097152 /* Intersection */ && target2.aliasSymbol && contains(sourceOrigin.types, target2)) { + return -1 /* True */; + } + const targetOrigin = target2.origin; + if (targetOrigin && targetOrigin.flags & 1048576 /* Union */ && source2.aliasSymbol && contains(targetOrigin.types, source2)) { + return -1 /* True */; + } + } return relation === comparableRelation ? someTypeRelatedToType(source2, target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */), intersectionState) : eachTypeRelatedToType(source2, target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */), intersectionState); } if (target2.flags & 1048576 /* Union */) { @@ -63226,6 +63670,10 @@ ${lanes.join("\n")} return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; } } + if (relationCount <= 0) { + overflow = true; + return 0 /* False */; + } if (!maybeKeys) { maybeKeys = []; maybeKeysSet = /* @__PURE__ */ new Set(); @@ -63319,6 +63767,7 @@ ${lanes.join("\n")} } } else { relation.set(id, (reportErrors2 ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags); + relationCount--; resetMaybeStack( /*markAllAsSucceeded*/ false @@ -63330,6 +63779,7 @@ ${lanes.join("\n")} maybeKeysSet.delete(maybeKeys[i]); if (markAllAsSucceeded) { relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags); + relationCount--; } } maybeCount = maybeStart; @@ -64088,42 +64538,27 @@ ${lanes.join("\n")} function propertyRelatedTo(source2, target2, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors2, intersectionState, skipOptional) { const sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); const targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); - if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { + if (sourcePropFlags & 2 /* Private */ || targetPropFlags & 2 /* Private */) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors2) { - if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { + if (sourcePropFlags & 2 /* Private */ && targetPropFlags & 2 /* Private */) { reportError(Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); } else { - reportError( - Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, - symbolToString(targetProp), - typeToString(sourcePropFlags & 8 /* Private */ ? source2 : target2), - typeToString(sourcePropFlags & 8 /* Private */ ? target2 : source2) - ); + reportError(Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 2 /* Private */ ? source2 : target2), typeToString(sourcePropFlags & 2 /* Private */ ? target2 : source2)); } } return 0 /* False */; } - } else if (targetPropFlags & 16 /* Protected */) { + } else if (targetPropFlags & 4 /* Protected */) { if (!isValidOverrideOf(sourceProp, targetProp)) { if (reportErrors2) { - reportError( - Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, - symbolToString(targetProp), - typeToString(getDeclaringClass(sourceProp) || source2), - typeToString(getDeclaringClass(targetProp) || target2) - ); + reportError(Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source2), typeToString(getDeclaringClass(targetProp) || target2)); } return 0 /* False */; } - } else if (sourcePropFlags & 16 /* Protected */) { + } else if (sourcePropFlags & 4 /* Protected */) { if (reportErrors2) { - reportError( - Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, - symbolToString(targetProp), - typeToString(source2), - typeToString(target2) - ); + reportError(Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source2), typeToString(target2)); } return 0 /* False */; } @@ -64139,12 +64574,7 @@ ${lanes.join("\n")} } if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && targetProp.flags & 106500 /* ClassMember */ && !(targetProp.flags & 16777216 /* Optional */)) { if (reportErrors2) { - reportError( - Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, - symbolToString(targetProp), - typeToString(source2), - typeToString(target2) - ); + reportError(Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source2), typeToString(target2)); } return 0 /* False */; } @@ -64390,8 +64820,14 @@ ${lanes.join("\n")} } const sourceIsJSConstructor = source2.symbol && isJSConstructor(source2.symbol.valueDeclaration); const targetIsJSConstructor = target2.symbol && isJSConstructor(target2.symbol.valueDeclaration); - const sourceSignatures = getSignaturesOfType(source2, sourceIsJSConstructor && kind === 1 /* Construct */ ? 0 /* Call */ : kind); - const targetSignatures = getSignaturesOfType(target2, targetIsJSConstructor && kind === 1 /* Construct */ ? 0 /* Call */ : kind); + const sourceSignatures = getSignaturesOfType( + source2, + sourceIsJSConstructor && kind === 1 /* Construct */ ? 0 /* Call */ : kind + ); + const targetSignatures = getSignaturesOfType( + target2, + targetIsJSConstructor && kind === 1 /* Construct */ ? 0 /* Call */ : kind + ); if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { const sourceIsAbstract = !!(sourceSignatures[0].flags & 4 /* Abstract */); const targetIsAbstract = !!(targetSignatures[0].flags & 4 /* Abstract */); @@ -64465,18 +64901,14 @@ ${lanes.join("\n")} shouldElaborateErrors = false; } if (shouldElaborateErrors) { - reportError( - Diagnostics.Type_0_provides_no_match_for_the_signature_1, - typeToString(source2), - signatureToString( - t, - /*enclosingDeclaration*/ - void 0, - /*flags*/ - void 0, - kind - ) - ); + reportError(Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source2), signatureToString( + t, + /*enclosingDeclaration*/ + void 0, + /*flags*/ + void 0, + kind + )); } return 0 /* False */; } @@ -64509,16 +64941,7 @@ ${lanes.join("\n")} } function signatureRelatedTo(source2, target2, erase, reportErrors2, intersectionState, incompatibleReporter) { const checkMode = relation === subtypeRelation ? 16 /* StrictTopSignature */ : relation === strictSubtypeRelation ? 16 /* StrictTopSignature */ | 8 /* StrictArity */ : 0 /* None */; - return compareSignaturesRelated( - erase ? getErasedSignature(source2) : source2, - erase ? getErasedSignature(target2) : target2, - checkMode, - reportErrors2, - reportError, - incompatibleReporter, - isRelatedToWorker2, - reportUnreliableMapper - ); + return compareSignaturesRelated(erase ? getErasedSignature(source2) : source2, erase ? getErasedSignature(target2) : target2, checkMode, reportErrors2, reportError, incompatibleReporter, isRelatedToWorker2, reportUnreliableMapper); function isRelatedToWorker2(source3, target3, reportErrors3) { return isRelatedTo( source3, @@ -64663,15 +65086,15 @@ ${lanes.join("\n")} if (!sourceSignature.declaration || !targetSignature.declaration) { return true; } - const sourceAccessibility = getSelectedEffectiveModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */); - const targetAccessibility = getSelectedEffectiveModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */); - if (targetAccessibility === 8 /* Private */) { + const sourceAccessibility = getSelectedEffectiveModifierFlags(sourceSignature.declaration, 6 /* NonPublicAccessibilityModifier */); + const targetAccessibility = getSelectedEffectiveModifierFlags(targetSignature.declaration, 6 /* NonPublicAccessibilityModifier */); + if (targetAccessibility === 2 /* Private */) { return true; } - if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) { + if (targetAccessibility === 4 /* Protected */ && sourceAccessibility !== 2 /* Private */) { return true; } - if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) { + if (targetAccessibility !== 4 /* Protected */ && !sourceAccessibility) { return true; } if (reportErrors2) { @@ -64771,7 +65194,7 @@ ${lanes.join("\n")} const variances = []; for (const tp of typeParameters) { const modifiers = getTypeParameterModifiers(tp); - let variance = modifiers & 65536 /* Out */ ? modifiers & 32768 /* In */ ? 0 /* Invariant */ : 1 /* Covariant */ : modifiers & 32768 /* In */ ? 2 /* Contravariant */ : void 0; + let variance = modifiers & 16384 /* Out */ ? modifiers & 8192 /* In */ ? 0 /* Invariant */ : 1 /* Covariant */ : modifiers & 8192 /* In */ ? 2 /* Contravariant */ : void 0; if (variance === void 0) { let unmeasurable = false; let unreliable = false; @@ -64819,7 +65242,7 @@ ${lanes.join("\n")} } function getTypeParameterModifiers(tp) { var _a; - return reduceLeft((_a = tp.symbol) == null ? void 0 : _a.declarations, (modifiers, d) => modifiers | getEffectiveModifierFlags(d), 0 /* None */) & (32768 /* In */ | 65536 /* Out */ | 2048 /* Const */); + return reduceLeft((_a = tp.symbol) == null ? void 0 : _a.declarations, (modifiers, d) => modifiers | getEffectiveModifierFlags(d), 0 /* None */) & (8192 /* In */ | 16384 /* Out */ | 4096 /* Const */); } function hasCovariantVoidArgument(typeArguments, variances) { for (let i = 0; i < variances.length; i++) { @@ -64904,13 +65327,16 @@ ${lanes.join("\n")} }); } function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty2(targetProp, (tp) => getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false); + return !forEachProperty2(targetProp, (tp) => getDeclarationModifierFlagsFromSymbol(tp) & 4 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false); } function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { - return forEachProperty2(prop, (p) => getDeclarationModifierFlagsFromSymbol(p, writing) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false) ? void 0 : checkClass; + return forEachProperty2(prop, (p) => getDeclarationModifierFlagsFromSymbol(p, writing) & 4 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false) ? void 0 : checkClass; } function isDeeplyNestedType(type, stack, depth, maxDepth = 3) { if (depth >= maxDepth) { + if ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */) { + type = getMappedTargetWithSymbol(type); + } if (type.flags & 2097152 /* Intersection */) { return some(type.types, (t) => isDeeplyNestedType(t, stack, depth, maxDepth)); } @@ -64919,7 +65345,7 @@ ${lanes.join("\n")} let lastTypeId = 0; for (let i = 0; i < depth; i++) { const t = stack[i]; - if (t.flags & 2097152 /* Intersection */ ? some(t.types, (u) => getRecursionIdentity(u) === identity2) : getRecursionIdentity(t) === identity2) { + if (hasMatchingRecursionIdentity(t, identity2)) { if (t.id >= lastTypeId) { count++; if (count >= maxDepth) { @@ -64932,6 +65358,22 @@ ${lanes.join("\n")} } return false; } + function getMappedTargetWithSymbol(type) { + let target; + while ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */ && (target = getModifiersTypeFromMappedType(type)) && (target.symbol || target.flags & 2097152 /* Intersection */ && some(target.types, (t) => !!t.symbol))) { + type = target; + } + return type; + } + function hasMatchingRecursionIdentity(type, identity2) { + if ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */) { + type = getMappedTargetWithSymbol(type); + } + if (type.flags & 2097152 /* Intersection */) { + return some(type.types, (t) => hasMatchingRecursionIdentity(t, identity2)); + } + return getRecursionIdentity(type) === identity2; + } function getRecursionIdentity(type) { if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { if (getObjectFlags(type) & 4 /* Reference */ && type.node) { @@ -64965,8 +65407,8 @@ ${lanes.join("\n")} if (sourceProp === targetProp) { return -1 /* True */; } - const sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; - const targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + const sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 6 /* NonPublicAccessibilityModifier */; + const targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 6 /* NonPublicAccessibilityModifier */; if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -65104,6 +65546,9 @@ ${lanes.join("\n")} function isArrayLikeType(type) { return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } + function isMutableArrayLikeType(type) { + return isMutableArrayOrTuple(type) || !(type.flags & (1 /* Any */ | 98304 /* Nullable */)) && isTypeAssignableTo(type, anyArrayType); + } function getSingleBaseForNonAugmentingSubtype(type) { if (!(getObjectFlags(type) & 4 /* Reference */) || !(getObjectFlags(type.target) & 3 /* ClassOrInterface */)) { return void 0; @@ -65258,7 +65703,7 @@ ${lanes.join("\n")} return value.base10Value === "0"; } function removeDefinitelyFalsyTypes(type) { - return filterType(type, (t) => !!(getTypeFacts(t) & 4194304 /* Truthy */)); + return filterType(type, (t) => hasTypeFacts(t, 4194304 /* Truthy */)); } function extractDefinitelyFalsyTypes(type) { return mapType(type, getDefinitelyFalsyPartOfType); @@ -65427,13 +65872,7 @@ ${lanes.join("\n")} } } } - const result = createAnonymousType( - type.symbol, - members, - emptyArray, - emptyArray, - sameMap(getIndexInfosOfType(type), (info) => createIndexInfo(info.keyType, getWidenedType(info.type), info.isReadonly)) - ); + const result = createAnonymousType(type.symbol, members, emptyArray, emptyArray, sameMap(getIndexInfosOfType(type), (info) => createIndexInfo(info.keyType, getWidenedType(info.type), info.isReadonly))); result.objectFlags |= getObjectFlags(type) & (4096 /* JSLiteral */ | 262144 /* NonInferrableType */); return result; } @@ -65527,7 +65966,7 @@ ${lanes.join("\n")} const param = declaration; if (isIdentifier(param.name)) { const originalKeywordKind = identifierToKeywordKind(param.name); - if ((isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && param.parent.parameters.indexOf(param) > -1 && (resolveName( + if ((isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && param.parent.parameters.includes(param) && (resolveName( param, param.name.escapedText, 788968 /* Type */, @@ -65613,7 +66052,12 @@ ${lanes.join("\n")} callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } if (targetRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetRestType); + callback(getRestTypeAtPosition( + source, + paramCount, + /*readonly*/ + isConstTypeVariable(targetRestType) && !someType(targetRestType, isMutableArrayLikeType) + ), targetRestType); } } function applyToReturnTypes(source, target, callback) { @@ -65646,19 +66090,25 @@ ${lanes.join("\n")} return context; } function makeFixingMapperForContext(context) { - return makeDeferredTypeMapper(map(context.inferences, (i) => i.typeParameter), map(context.inferences, (inference, i) => () => { - if (!inference.isFixed) { - inferFromIntraExpressionSites(context); - clearCachedInferences(context.inferences); - inference.isFixed = true; - } - return getInferredType(context, i); - })); + return makeDeferredTypeMapper( + map(context.inferences, (i) => i.typeParameter), + map(context.inferences, (inference, i) => () => { + if (!inference.isFixed) { + inferFromIntraExpressionSites(context); + clearCachedInferences(context.inferences); + inference.isFixed = true; + } + return getInferredType(context, i); + }) + ); } function makeNonFixingMapperForContext(context) { - return makeDeferredTypeMapper(map(context.inferences, (i) => i.typeParameter), map(context.inferences, (_, i) => () => { - return getInferredType(context, i); - })); + return makeDeferredTypeMapper( + map(context.inferences, (i) => i.typeParameter), + map(context.inferences, (_, i) => () => { + return getInferredType(context, i); + }) + ); } function clearCachedInferences(inferences) { for (const inference of inferences) { @@ -65717,8 +66167,8 @@ ${lanes.join("\n")} if (objectFlags & 524288 /* CouldContainTypeVariablesComputed */) { return !!(objectFlags & 1048576 /* CouldContainTypeVariables */); } - const result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || some(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 4194304 /* ObjectRestType */ | 8388608 /* InstantiationExpressionType */)) || type.flags & (3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */) && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && some(type.types, couldContainTypeVariables)); - if (type.flags & 138117121 /* ObjectFlagsType */) { + const result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || some(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 4194304 /* ObjectRestType */ | 8388608 /* InstantiationExpressionType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && some(type.types, couldContainTypeVariables)); + if (type.flags & 3899393 /* ObjectFlagsType */) { type.objectFlags |= 524288 /* CouldContainTypeVariablesComputed */ | (result ? 1048576 /* CouldContainTypeVariables */ : 0); } return result; @@ -65915,6 +66365,9 @@ ${lanes.join("\n")} if (source === target || target.flags & (1 /* Any */ | 4 /* String */)) { return true; } + if (target.flags & 2097152 /* Intersection */) { + return every(target.types, (t) => t === emptyTypeLiteralType || isValidTypeForTemplateLiteralPlaceholder(source, t)); + } if (source.flags & 128 /* StringLiteral */) { const value = source.value; return !!(target.flags & 8 /* Number */ && isValidNumberString( @@ -65925,7 +66378,7 @@ ${lanes.join("\n")} value, /*roundTripOnly*/ false - ) || target.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) && value === target.intrinsicName || target.flags & 268435456 /* StringMapping */ && isMemberOfStringMapping(getStringLiteralType(value), target)); + ) || target.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) && value === target.intrinsicName || target.flags & 268435456 /* StringMapping */ && isMemberOfStringMapping(getStringLiteralType(value), target) || target.flags & 134217728 /* TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source, target)); } if (source.flags & 134217728 /* TemplateLiteral */) { const texts = source.texts; @@ -66000,7 +66453,6 @@ ${lanes.join("\n")} let bivariant = false; let propagationType; let inferencePriority = 2048 /* MaxValue */; - let allowComplexConstraintInference = true; let visited; let sourceStack; let targetStack; @@ -66010,7 +66462,7 @@ ${lanes.join("\n")} if (!couldContainTypeVariables(target)) { return; } - if (source === wildcardType) { + if (source === wildcardType || source === blockedStringType) { const savePropagationType = propagationType; propagationType = source; inferFromTypes(target, target); @@ -66067,6 +66519,10 @@ ${lanes.join("\n")} return; } if (!inference.isFixed) { + const candidate = propagationType || source; + if (candidate === blockedStringType) { + return; + } if (inference.priority === void 0 || priority < inference.priority) { inference.candidates = void 0; inference.contraCandidates = void 0; @@ -66074,7 +66530,6 @@ ${lanes.join("\n")} inference.priority = priority; } if (priority === inference.priority) { - const candidate = propagationType || source; if (contravariant && !bivariant) { if (!contains(inference.contraCandidates, candidate)) { inference.contraCandidates = append(inference.contraCandidates, candidate); @@ -66155,8 +66610,7 @@ ${lanes.join("\n")} source = getReducedType(source); if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { const apparentSource = getApparentType(source); - if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) { - allowComplexConstraintInference = false; + if (apparentSource !== source && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) { return inferFromTypes(apparentSource, target); } source = apparentSource; @@ -66405,11 +66859,7 @@ ${lanes.join("\n")} )) { allTypeFlags &= ~2112 /* BigIntLike */; } - const matchingType = reduceLeft( - constraintTypes, - (left, right) => !(right.flags & allTypeFlags) ? left : left.flags & 4 /* String */ ? left : right.flags & 4 /* String */ ? source2 : left.flags & 134217728 /* TemplateLiteral */ ? left : right.flags & 134217728 /* TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source2, right) ? source2 : left.flags & 268435456 /* StringMapping */ ? left : right.flags & 268435456 /* StringMapping */ && str === applyStringMapping(right.symbol, str) ? source2 : left.flags & 128 /* StringLiteral */ ? left : right.flags & 128 /* StringLiteral */ && right.value === str ? right : left.flags & 8 /* Number */ ? left : right.flags & 8 /* Number */ ? getNumberLiteralType(+str) : left.flags & 32 /* Enum */ ? left : right.flags & 32 /* Enum */ ? getNumberLiteralType(+str) : left.flags & 256 /* NumberLiteral */ ? left : right.flags & 256 /* NumberLiteral */ && right.value === +str ? right : left.flags & 64 /* BigInt */ ? left : right.flags & 64 /* BigInt */ ? parseBigIntLiteralType(str) : left.flags & 2048 /* BigIntLiteral */ ? left : right.flags & 2048 /* BigIntLiteral */ && pseudoBigIntToString(right.value) === str ? right : left.flags & 16 /* Boolean */ ? left : right.flags & 16 /* Boolean */ ? str === "true" ? trueType : str === "false" ? falseType : booleanType : left.flags & 512 /* BooleanLiteral */ ? left : right.flags & 512 /* BooleanLiteral */ && right.intrinsicName === str ? right : left.flags & 32768 /* Undefined */ ? left : right.flags & 32768 /* Undefined */ && right.intrinsicName === str ? right : left.flags & 65536 /* Null */ ? left : right.flags & 65536 /* Null */ && right.intrinsicName === str ? right : left, - neverType - ); + const matchingType = reduceLeft(constraintTypes, (left, right) => !(right.flags & allTypeFlags) ? left : left.flags & 4 /* String */ ? left : right.flags & 4 /* String */ ? source2 : left.flags & 134217728 /* TemplateLiteral */ ? left : right.flags & 134217728 /* TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source2, right) ? source2 : left.flags & 268435456 /* StringMapping */ ? left : right.flags & 268435456 /* StringMapping */ && str === applyStringMapping(right.symbol, str) ? source2 : left.flags & 128 /* StringLiteral */ ? left : right.flags & 128 /* StringLiteral */ && right.value === str ? right : left.flags & 8 /* Number */ ? left : right.flags & 8 /* Number */ ? getNumberLiteralType(+str) : left.flags & 32 /* Enum */ ? left : right.flags & 32 /* Enum */ ? getNumberLiteralType(+str) : left.flags & 256 /* NumberLiteral */ ? left : right.flags & 256 /* NumberLiteral */ && right.value === +str ? right : left.flags & 64 /* BigInt */ ? left : right.flags & 64 /* BigInt */ ? parseBigIntLiteralType(str) : left.flags & 2048 /* BigIntLiteral */ ? left : right.flags & 2048 /* BigIntLiteral */ && pseudoBigIntToString(right.value) === str ? right : left.flags & 16 /* Boolean */ ? left : right.flags & 16 /* Boolean */ ? str === "true" ? trueType : str === "false" ? falseType : booleanType : left.flags & 512 /* BooleanLiteral */ ? left : right.flags & 512 /* BooleanLiteral */ && right.intrinsicName === str ? right : left.flags & 32768 /* Undefined */ ? left : right.flags & 32768 /* Undefined */ && right.intrinsicName === str ? right : left.flags & 65536 /* Null */ ? left : right.flags & 65536 /* Null */ && right.intrinsicName === str ? right : left, neverType); if (!(matchingType.flags & 131072 /* Never */)) { inferFromTypes(matchingType, target2); continue; @@ -66455,10 +66905,7 @@ ${lanes.join("\n")} return; } const startLength = isTupleType(source) ? Math.min(source.target.fixedLength, target.target.fixedLength) : 0; - const endLength = Math.min( - isTupleType(source) ? getEndElementCount(source.target, 3 /* Fixed */) : 0, - target.target.hasRestElement ? getEndElementCount(target.target, 3 /* Fixed */) : 0 - ); + const endLength = Math.min(isTupleType(source) ? getEndElementCount(source.target, 3 /* Fixed */) : 0, target.target.hasRestElement ? getEndElementCount(target.target, 3 /* Fixed */) : 0); for (let i = 0; i < startLength; i++) { inferFromTypes(getTypeArguments(source)[i], elementTypes[i]); } @@ -66540,12 +66987,14 @@ ${lanes.join("\n")} } function inferFromSignatures(source, target, kind) { const sourceSignatures = getSignaturesOfType(source, kind); - const targetSignatures = getSignaturesOfType(target, kind); const sourceLen = sourceSignatures.length; - const targetLen = targetSignatures.length; - const len = sourceLen < targetLen ? sourceLen : targetLen; - for (let i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); + if (sourceLen > 0) { + const targetSignatures = getSignaturesOfType(target, kind); + const targetLen = targetSignatures.length; + for (let i = 0; i < targetLen; i++) { + const sourceIndex = Math.max(sourceLen - targetLen + i, 0); + inferFromSignature(getBaseSignature(sourceSignatures[sourceIndex]), getErasedSignature(targetSignatures[i])); + } } } function inferFromSignature(source, target) { @@ -66652,7 +67101,7 @@ ${lanes.join("\n")} const constraint = getConstraintOfTypeParameter(inference.typeParameter); if (constraint) { const instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper); - if (!inferredType || inferredType === wildcardType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { inference.inferredType = fallbackType && context.compareTypes(fallbackType, getTypeWithThisArgument(instantiatedConstraint, fallbackType)) ? fallbackType : instantiatedConstraint; } } @@ -66960,7 +67409,7 @@ ${lanes.join("\n")} function hasMatchingArgument(expression, reference) { if (expression.arguments) { for (const argument of expression.arguments) { - if (isOrContainsMatchingReference(reference, argument)) { + if (isOrContainsMatchingReference(reference, argument) || optionalChainContainsReference(argument, reference)) { return true; } } @@ -67007,7 +67456,13 @@ ${lanes.join("\n")} const resolved = resolveStructuredTypeMembers(type); return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type) { + function getTypeFacts(type, mask2) { + return getTypeFactsWorker(type, mask2) & mask2; + } + function hasTypeFacts(type, mask2) { + return getTypeFacts(type, mask2) !== 0; + } + function getTypeFactsWorker(type, callerOnlyNeeds) { if (type.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */)) { type = getBaseConstraintOfType(type) || unknownType; } @@ -67040,6 +67495,10 @@ ${lanes.join("\n")} return strictNullChecks ? type === falseType || type === regularFalseType ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : type === falseType || type === regularFalseType ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } if (flags & 524288 /* Object */) { + const possibleFacts = strictNullChecks ? 83427327 /* EmptyObjectStrictFacts */ | 7880640 /* FunctionStrictFacts */ | 7888800 /* ObjectStrictFacts */ : 83886079 /* EmptyObjectFacts */ | 16728e3 /* FunctionFacts */ | 16736160 /* ObjectFacts */; + if ((callerOnlyNeeds & possibleFacts) === 0) { + return 0; + } return getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 83427327 /* EmptyObjectStrictFacts */ : 83886079 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728e3 /* FunctionFacts */ : strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } if (flags & 16384 /* Void */) { @@ -67061,20 +67520,20 @@ ${lanes.join("\n")} return 0 /* None */; } if (flags & 1048576 /* Union */) { - return reduceLeft(type.types, (facts, t) => facts | getTypeFacts(t), 0 /* None */); + return reduceLeft(type.types, (facts, t) => facts | getTypeFactsWorker(t, callerOnlyNeeds), 0 /* None */); } if (flags & 2097152 /* Intersection */) { - return getIntersectionTypeFacts(type); + return getIntersectionTypeFacts(type, callerOnlyNeeds); } return 83886079 /* UnknownFacts */; } - function getIntersectionTypeFacts(type) { + function getIntersectionTypeFacts(type, callerOnlyNeeds) { const ignoreObjects = maybeTypeOfKind(type, 402784252 /* Primitive */); let oredFacts = 0 /* None */; let andedFacts = 134217727 /* All */; for (const t of type.types) { if (!(ignoreObjects && t.flags & 524288 /* Object */)) { - const f = getTypeFacts(t); + const f = getTypeFactsWorker(t, callerOnlyNeeds); oredFacts |= f; andedFacts &= f; } @@ -67082,19 +67541,19 @@ ${lanes.join("\n")} return oredFacts & 8256 /* OrFactsMask */ | andedFacts & 134209471 /* AndFactsMask */; } function getTypeWithFacts(type, include) { - return filterType(type, (t) => (getTypeFacts(t) & include) !== 0); + return filterType(type, (t) => hasTypeFacts(t, include)); } function getAdjustedTypeWithFacts(type, facts) { const reduced = recombineUnknownType(getTypeWithFacts(strictNullChecks && type.flags & 2 /* Unknown */ ? unknownUnionType : type, facts)); if (strictNullChecks) { switch (facts) { case 524288 /* NEUndefined */: - return mapType(reduced, (t) => getTypeFacts(t) & 65536 /* EQUndefined */ ? getIntersectionType([t, getTypeFacts(t) & 131072 /* EQNull */ && !maybeTypeOfKind(reduced, 65536 /* Null */) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]) : t); + return mapType(reduced, (t) => hasTypeFacts(t, 65536 /* EQUndefined */) ? getIntersectionType([t, hasTypeFacts(t, 131072 /* EQNull */) && !maybeTypeOfKind(reduced, 65536 /* Null */) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]) : t); case 1048576 /* NENull */: - return mapType(reduced, (t) => getTypeFacts(t) & 131072 /* EQNull */ ? getIntersectionType([t, getTypeFacts(t) & 65536 /* EQUndefined */ && !maybeTypeOfKind(reduced, 32768 /* Undefined */) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]) : t); + return mapType(reduced, (t) => hasTypeFacts(t, 131072 /* EQNull */) ? getIntersectionType([t, hasTypeFacts(t, 65536 /* EQUndefined */) && !maybeTypeOfKind(reduced, 32768 /* Undefined */) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]) : t); case 2097152 /* NEUndefinedOrNull */: case 4194304 /* Truthy */: - return mapType(reduced, (t) => getTypeFacts(t) & 262144 /* EQUndefinedOrNull */ ? getGlobalNonNullableTypeInstantiation(t) : t); + return mapType(reduced, (t) => hasTypeFacts(t, 262144 /* EQUndefinedOrNull */) ? getGlobalNonNullableTypeInstantiation(t) : t); } } return reduced; @@ -67380,7 +67839,9 @@ ${lanes.join("\n")} return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 131072 /* Never */ ? autoArrayType : createArrayType(elementType.flags & 1048576 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType); + return elementType.flags & 131072 /* Never */ ? autoArrayType : createArrayType( + elementType.flags & 1048576 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType + ); } function getFinalArrayType(evolvingArrayType) { return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); @@ -67491,7 +67952,10 @@ ${lanes.join("\n")} let signature = links.effectsSignature; if (signature === void 0) { let funcType; - if (node.parent.kind === 244 /* ExpressionStatement */) { + if (isBinaryExpression(node)) { + const rightType = checkNonNullExpression(node.right); + funcType = getSymbolHasInstanceMethodOfObjectType(rightType); + } else if (node.parent.kind === 244 /* ExpressionStatement */) { funcType = getTypeOfDottedName( node.expression, /*diagnostic*/ @@ -67781,7 +68245,10 @@ ${lanes.join("\n")} } function getInitialOrAssignedType(flow) { const node = flow.node; - return getNarrowableTypeForReference(node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */ ? getInitialType(node) : getAssignedType(node), reference); + return getNarrowableTypeForReference( + node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */ ? getInitialType(node) : getAssignedType(node), + reference + ); } function getTypeAtFlowAssignment(flow) { const node = flow.node; @@ -67800,10 +68267,11 @@ ${lanes.join("\n")} const assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 1048576 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow)); + const t = isInCompoundLikeAssignment(node) ? getBaseTypeOfLiteralType(declaredType) : declaredType; + if (t.flags & 1048576 /* Union */) { + return getAssignmentReducedType(t, getInitialOrAssignedType(flow)); } - return declaredType; + return t; } if (containsMatchingReference(reference, node)) { if (!isReachableFlowNode(flow)) { @@ -67909,31 +68377,21 @@ ${lanes.join("\n")} return createFlowType(narrowedType, isIncomplete(flowType)); } function getTypeAtSwitchClause(flow) { - const expr = flow.switchStatement.expression; + const expr = skipParentheses(flow.switchStatement.expression); const flowType = getTypeAtFlowNode(flow.antecedent); let type = getTypeFromFlowType(flowType); if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (expr.kind === 221 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowTypeBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } else if (expr.kind === 112 /* TrueKeyword */) { + type = narrowTypeBySwitchOnTrue(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { if (strictNullChecks) { if (optionalChainContainsReference(expr, reference)) { - type = narrowTypeBySwitchOptionalChainContainment( - type, - flow.switchStatement, - flow.clauseStart, - flow.clauseEnd, - (t) => !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)) - ); + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, (t) => !(t.flags & (32768 /* Undefined */ | 131072 /* Never */))); } else if (expr.kind === 221 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { - type = narrowTypeBySwitchOptionalChainContainment( - type, - flow.switchStatement, - flow.clauseStart, - flow.clauseEnd, - (t) => !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined") - ); + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, (t) => !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined")); } } const access = getDiscriminantPropertyAccess(expr, type); @@ -68087,13 +68545,15 @@ ${lanes.join("\n")} return void 0; } function getDiscriminantPropertyAccess(expr, computedType) { - const type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType; - if (type.flags & 1048576 /* Union */) { + if (declaredType.flags & 1048576 /* Union */ || computedType.flags & 1048576 /* Union */) { const access = getCandidateDiscriminantPropertyAccess(expr); if (access) { const name = getAccessedPropertyName(access); - if (name && isDiscriminantProperty(type, name)) { - return access; + if (name) { + const type = declaredType.flags & 1048576 /* Union */ && isTypeSubsetOf(computedType, declaredType) ? declaredType : computedType; + if (isDiscriminantProperty(type, name)) { + return access; + } } } } @@ -68113,7 +68573,7 @@ ${lanes.join("\n")} propType = removeNullable && optionalChain ? getOptionalType(propType) : propType; const narrowedPropType = narrowType2(propType); return filterType(type, (t) => { - const discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); + const discriminantType = getTypeOfPropertyOrIndexSignatureOfType(t, propName) || unknownType; return !(discriminantType.flags & 131072 /* Never */) && !(narrowedPropType.flags & 131072 /* Never */) && areTypesComparable(narrowedPropType, discriminantType); }); } @@ -68175,6 +68635,10 @@ ${lanes.join("\n")} } return type; } + function narrowTypeByBooleanComparison(type, expr, bool, operator, assumeTrue) { + assumeTrue = assumeTrue !== (bool.kind === 112 /* TrueKeyword */) !== (operator !== 38 /* ExclamationEqualsEqualsToken */ && operator !== 36 /* ExclamationEqualsToken */); + return narrowType(type, expr, assumeTrue); + } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { case 64 /* EqualsToken */: @@ -68222,6 +68686,12 @@ ${lanes.join("\n")} if (isMatchingConstructorReference(right)) { return narrowTypeByConstructor(type, operator, left, assumeTrue); } + if (isBooleanLiteral(right) && !isAccessExpression(left)) { + return narrowTypeByBooleanComparison(type, left, right, operator, assumeTrue); + } + if (isBooleanLiteral(left) && !isAccessExpression(right)) { + return narrowTypeByBooleanComparison(type, right, left, operator, assumeTrue); + } break; case 104 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); @@ -68437,14 +68907,14 @@ ${lanes.join("\n")} // the constituent based on its type facts. We use the strict subtype relation because it treats `object` // as a subtype of `{}`, and we need the type facts check because function types are subtypes of `object`, // but are classified as "function" according to `typeof`. - isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? getTypeFacts(t) & facts ? t : neverType : ( + isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? hasTypeFacts(t, facts) ? t : neverType : ( // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`. isTypeSubtypeOf(impliedType, t) ? impliedType : ( // Neither the constituent nor the implied type is a subtype of the other, however their domains may still // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate // possible overlap, we form an intersection. Otherwise, we eliminate the constituent. - getTypeFacts(t) & facts ? getIntersectionType([t, impliedType]) : neverType + hasTypeFacts(t, facts) ? getIntersectionType([t, impliedType]) : neverType ) ) )); @@ -68458,11 +68928,47 @@ ${lanes.join("\n")} const hasDefaultClause = clauseStart === clauseEnd || defaultIndex >= clauseStart && defaultIndex < clauseEnd; if (hasDefaultClause) { const notEqualFacts = getNotEqualFactsFromTypeofSwitch(clauseStart, clauseEnd, witnesses); - return filterType(type, (t) => (getTypeFacts(t) & notEqualFacts) === notEqualFacts); + return filterType(type, (t) => getTypeFacts(t, notEqualFacts) === notEqualFacts); } const clauseWitnesses = witnesses.slice(clauseStart, clauseEnd); return getUnionType(map(clauseWitnesses, (text) => text ? narrowTypeByTypeName(type, text) : neverType)); } + function narrowTypeBySwitchOnTrue(type, switchStatement, clauseStart, clauseEnd) { + const defaultIndex = findIndex(switchStatement.caseBlock.clauses, (clause) => clause.kind === 297 /* DefaultClause */); + const hasDefaultClause = clauseStart === clauseEnd || defaultIndex >= clauseStart && defaultIndex < clauseEnd; + for (let i = 0; i < clauseStart; i++) { + const clause = switchStatement.caseBlock.clauses[i]; + if (clause.kind === 296 /* CaseClause */) { + type = narrowType( + type, + clause.expression, + /*assumeTrue*/ + false + ); + } + } + if (hasDefaultClause) { + for (let i = clauseEnd; i < switchStatement.caseBlock.clauses.length; i++) { + const clause = switchStatement.caseBlock.clauses[i]; + if (clause.kind === 296 /* CaseClause */) { + type = narrowType( + type, + clause.expression, + /*assumeTrue*/ + false + ); + } + } + return type; + } + const clauses = switchStatement.caseBlock.clauses.slice(clauseStart, clauseEnd); + return getUnionType(map(clauses, (clause) => clause.kind === 296 /* CaseClause */ ? narrowType( + type, + clause.expression, + /*assumeTrue*/ + true + ) : neverType)); + } function isMatchingConstructorReference(expr) { return (isPropertyAccessExpression(expr) && idText(expr.name) === "constructor" || isElementAccessExpression(expr) && isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") && isMatchingReference(reference, expr.expression); } @@ -68502,7 +69008,22 @@ ${lanes.join("\n")} } return type; } - const rightType = getTypeOfExpression(expr.right); + const right = expr.right; + const rightType = getTypeOfExpression(right); + if (!isTypeDerivedFrom(rightType, globalObjectType)) { + return type; + } + const signature = getEffectsSignature(expr); + const predicate = signature && getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 1 /* Identifier */ && predicate.parameterIndex === 0) { + return getNarrowedType( + type, + predicate.type, + assumeTrue, + /*checkDerived*/ + true + ); + } if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } @@ -68556,7 +69077,10 @@ ${lanes.join("\n")} const narrowedType = mapType(candidate, (c) => { const discriminant = keyPropertyName && getTypeOfPropertyOfType(c, keyPropertyName); const matching = discriminant && getConstituentTypeForKeyType(type, discriminant); - const directlyRelated = mapType(matching || type, checkDerived ? (t) => isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType : (t) => isTypeStrictSubtypeOf(t, c) ? t : isTypeStrictSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : isTypeSubtypeOf(c, t) ? c : neverType); + const directlyRelated = mapType( + matching || type, + checkDerived ? (t) => isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType : (t) => isTypeStrictSubtypeOf(t, c) ? t : isTypeStrictSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : isTypeSubtypeOf(c, t) ? c : neverType + ); return directlyRelated.flags & 131072 /* Never */ ? mapType(type, (t) => maybeTypeOfKind(t, 465829888 /* Instantiable */) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType) : directlyRelated; }); return !(narrowedType.flags & 131072 /* Never */) ? narrowedType : isTypeSubtypeOf(candidate, type) ? candidate : isTypeAssignableTo(type, candidate) ? type : isTypeAssignableTo(candidate, type) ? candidate : getIntersectionType([type, candidate]); @@ -68593,7 +69117,7 @@ ${lanes.join("\n")} false ); } - if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { + if (strictNullChecks && optionalChainContainsReference(predicateArgument, reference) && (assumeTrue && !hasTypeFacts(predicate.type, 65536 /* EQUndefined */) || !assumeTrue && everyType(predicate.type, isNullableType))) { type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } const access = getDiscriminantPropertyAccess(predicateArgument, type); @@ -68666,7 +69190,15 @@ ${lanes.join("\n")} location = location.parent; } if (isExpressionNode(location) && (!isAssignmentTarget(location) || isWriteAccess(location))) { - const type = removeOptionalTypeMarker(getTypeOfExpression(location)); + const type = removeOptionalTypeMarker( + isWriteAccess(location) && location.kind === 211 /* PropertyAccessExpression */ ? checkPropertyAccessExpression( + location, + /*checkMode*/ + void 0, + /*writeOnly*/ + true + ) : getTypeOfExpression(location) + ); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } @@ -68675,7 +69207,7 @@ ${lanes.join("\n")} if (isDeclarationName(location) && isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { return getWriteTypeOfAccessors(location.parent.symbol); } - return getNonMissingTypeOfSymbol(symbol); + return isRightSideOfAccessExpression(location) && isWriteAccess(location.parent) ? getWriteTypeOfSymbol(symbol) : getNonMissingTypeOfSymbol(symbol); } function getControlFlowContainer(node) { return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 268 /* ModuleBlock */ || node2.kind === 312 /* SourceFile */ || node2.kind === 172 /* PropertyDeclaration */); @@ -68719,7 +69251,7 @@ ${lanes.join("\n")} reportCircularityError(declaration.symbol); return true; } - const containsUndefined = !!(getTypeFacts(checkDeclarationInitializer(declaration, 0 /* Normal */)) & 16777216 /* IsUndefined */); + const containsUndefined = !!hasTypeFacts(checkDeclarationInitializer(declaration, 0 /* Normal */), 16777216 /* IsUndefined */); if (!popTypeResolution()) { reportCircularityError(declaration.symbol); return true; @@ -68729,7 +69261,7 @@ ${lanes.join("\n")} return links.parameterInitializerContainsUndefined; } function removeOptionalityFromDeclaredType(declaredType, declaration) { - const removeUndefined = strictNullChecks && declaration.kind === 169 /* Parameter */ && declaration.initializer && getTypeFacts(declaredType) & 16777216 /* IsUndefined */ && !parameterInitializerContainsUndefined(declaration); + const removeUndefined = strictNullChecks && declaration.kind === 169 /* Parameter */ && declaration.initializer && hasTypeFacts(declaredType, 16777216 /* IsUndefined */) && !parameterInitializerContainsUndefined(declaration); return removeUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; } function isConstraintPosition(type, node) { @@ -68743,7 +69275,7 @@ ${lanes.join("\n")} return type.flags & 2097152 /* Intersection */ ? some(type.types, isGenericTypeWithoutNullableConstraint) : !!(type.flags & 465829888 /* Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* Nullable */)); } function hasContextualTypeWithNoGenericTypes(node, checkMode) { - const contextualType = (isIdentifier(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node)) && !((isJsxOpeningElement(node.parent) || isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 64 /* RestBindingElement */ ? getContextualType2(node, 8 /* SkipBindingPatterns */) : getContextualType2( + const contextualType = (isIdentifier(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node)) && !((isJsxOpeningElement(node.parent) || isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 32 /* RestBindingElement */ ? getContextualType2(node, 8 /* SkipBindingPatterns */) : getContextualType2( node, /*contextFlags*/ void 0 @@ -68819,7 +69351,12 @@ ${lanes.join("\n")} if (narrowedType.flags & 131072 /* Never */) { return neverType; } - return getBindingElementTypeFromParentType(declaration, narrowedType); + return getBindingElementTypeFromParentType( + declaration, + narrowedType, + /*noTupleBoundsCheck*/ + true + ); } } } @@ -68865,7 +69402,7 @@ ${lanes.join("\n")} if (languageVersion < 2 /* ES2015 */) { if (container.kind === 219 /* ArrowFunction */) { error2(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); - } else if (hasSyntacticModifier(container, 512 /* Async */)) { + } else if (hasSyntacticModifier(container, 1024 /* Async */)) { error2(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); } } @@ -68927,7 +69464,7 @@ ${lanes.join("\n")} const isAlias = localOrExportSymbol.flags & 2097152 /* Alias */; if (localOrExportSymbol.flags & 3 /* Variable */) { if (assignmentKind === 1 /* Definite */) { - return type; + return isInCompoundLikeAssignment(node) ? getBaseTypeOfLiteralType(type) : type; } } else if (isAlias) { declaration = getDeclarationOfAliasSymbol(symbol); @@ -69281,7 +69818,7 @@ ${lanes.join("\n")} let inAsyncFunction = false; if (!isCallExpression2) { while (container && container.kind === 219 /* ArrowFunction */) { - if (hasSyntacticModifier(container, 512 /* Async */)) + if (hasSyntacticModifier(container, 1024 /* Async */)) inAsyncFunction = true; container = getSuperContainer( container, @@ -69290,7 +69827,7 @@ ${lanes.join("\n")} ); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } - if (container && hasSyntacticModifier(container, 512 /* Async */)) + if (container && hasSyntacticModifier(container, 1024 /* Async */)) inAsyncFunction = true; } let nodeCheckFlag = 0; @@ -69346,6 +69883,9 @@ ${lanes.join("\n")} error2(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class); return errorType; } + if (classDeclarationExtendsNull(classLikeDeclaration)) { + return isCallExpression2 ? errorType : nullWideningType; + } const classType = getDeclaredTypeOfSymbol(getSymbolOfDeclaration(classLikeDeclaration)); const baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) { @@ -69430,7 +69970,7 @@ ${lanes.join("\n")} return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral)); } const parent2 = walkUpParenthesizedExpressions(func.parent); - if (parent2.kind === 226 /* BinaryExpression */ && parent2.operatorToken.kind === 64 /* EqualsToken */) { + if (isAssignmentExpression(parent2)) { const target = parent2.left; if (isAccessExpression(target)) { const { expression } = target; @@ -69498,7 +70038,7 @@ ${lanes.join("\n")} function getContextualTypeForBindingElement(declaration, contextFlags) { const parent2 = declaration.parent.parent; const name = declaration.propertyName || declaration.name; - const parentType = getContextualTypeForVariableLikeDeclaration(parent2, contextFlags) || parent2.kind !== 208 /* BindingElement */ && parent2.initializer && checkDeclarationInitializer(parent2, declaration.dotDotDotToken ? 64 /* RestBindingElement */ : 0 /* Normal */); + const parentType = getContextualTypeForVariableLikeDeclaration(parent2, contextFlags) || parent2.kind !== 208 /* BindingElement */ && parent2.initializer && checkDeclarationInitializer(parent2, declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */); if (!parentType || isBindingPattern(name) || isComputedNonLiteralName(name)) return void 0; if (parent2.name.kind === 207 /* ArrayBindingPattern */) { @@ -69619,7 +70159,24 @@ ${lanes.join("\n")} } const signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); if (signature && !isResolvingReturnTypeOfSignature(signature)) { - return getReturnTypeOfSignature(signature); + const returnType2 = getReturnTypeOfSignature(signature); + const functionFlags = getFunctionFlags(functionDecl); + if (functionFlags & 1 /* Generator */) { + return filterType(returnType2, (t) => { + return !!(t.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 58982400 /* InstantiableNonPrimitive */)) || checkGeneratorInstantiationAssignabilityToReturnType( + t, + functionFlags, + /*errorNode*/ + void 0 + ); + }); + } + if (functionFlags & 2 /* Async */) { + return filterType(returnType2, (t) => { + return !!(t.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 58982400 /* InstantiableNonPrimitive */)) || !!getAwaitedTypeOfPromise(t); + }); + } + return returnType2; } const iife = getImmediatelyInvokedFunctionExpression(functionDecl); if (iife) { @@ -69842,7 +70399,7 @@ ${lanes.join("\n")} } else if (t.flags & 3670016 /* StructuredType */) { const prop = getPropertyOfType(t, name); if (prop) { - return isCircularMappedProperty(prop) ? void 0 : getTypeOfSymbol(prop); + return isCircularMappedProperty(prop) ? void 0 : removeMissingType(getTypeOfSymbol(prop), !!(prop && prop.flags & 16777216 /* Optional */)); } if (isTupleType(t) && isNumericLiteralName(name) && +name >= 0) { const restType = getElementTypeOfSliceOfTupleType( @@ -69927,7 +70484,7 @@ ${lanes.join("\n")} (t) => { if (isTupleType(t)) { if ((firstSpreadIndex === void 0 || index < firstSpreadIndex) && index < t.target.fixedLength) { - return getTypeArguments(t)[index]; + return removeMissingType(getTypeArguments(t)[index], !!(t.target.elementFlags[index] && 2 /* Optional */)); } const offset = length2 !== void 0 && (lastSpreadIndex === void 0 || index > lastSpreadIndex) ? length2 - index : 0; const fixedEndLength = offset > 0 && t.target.hasRestElement ? getEndElementCount(t.target, 3 /* Fixed */) : 0; @@ -70025,8 +70582,19 @@ ${lanes.join("\n")} contextualType, concatenate( map( - filter(node.properties, (p) => !!p.symbol && p.kind === 303 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName)), - (prop) => [() => getContextFreeTypeOfExpression(prop.initializer), prop.symbol.escapedName] + filter(node.properties, (p) => { + if (!p.symbol) { + return false; + } + if (p.kind === 303 /* PropertyAssignment */) { + return isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); + } + if (p.kind === 304 /* ShorthandPropertyAssignment */) { + return isDiscriminantProperty(contextualType, p.symbol.escapedName); + } + return false; + }), + (prop) => [() => getContextFreeTypeOfExpression(prop.kind === 303 /* PropertyAssignment */ ? prop.initializer : prop.name), prop.symbol.escapedName] ), map( filter(getPropertiesOfType(contextualType), (s) => { @@ -70574,10 +71142,13 @@ ${lanes.join("\n")} elementTypes, elementFlags, /*readonly*/ - inConstContext + inConstContext && !(contextualType && someType(contextualType, isMutableArrayLikeType)) )); } - return createArrayLiteralType(createArrayType(elementTypes.length ? getUnionType(sameMap(elementTypes, (t, i) => elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t), 2 /* Subtype */) : strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext)); + return createArrayLiteralType(createArrayType( + elementTypes.length ? getUnionType(sameMap(elementTypes, (t, i) => elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t), 2 /* Subtype */) : strictNullChecks ? implicitNeverType : undefinedWideningType, + inConstContext + )); } function createArrayLiteralType(type) { if (!(getObjectFlags(type) & 4 /* Reference */)) { @@ -70730,12 +71301,7 @@ ${lanes.join("\n")} if (impliedProp) { prop.flags |= impliedProp.flags & 16777216 /* Optional */; } else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, stringType)) { - error2( - memberDecl.name, - Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, - symbolToString(member), - typeToString(contextualType) - ); + error2(memberDecl.name, Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); } } prop.declarations = member.declarations; @@ -70805,22 +71371,13 @@ ${lanes.join("\n")} } popContextualType(); if (contextualTypeHasPattern) { - const rootPatternParent = findAncestor( - contextualType.pattern.parent, - (n) => n.kind === 260 /* VariableDeclaration */ || n.kind === 226 /* BinaryExpression */ || n.kind === 169 /* Parameter */ - ); - const spreadOrOutsideRootObject = findAncestor( - node, - (n) => n === rootPatternParent || n.kind === 305 /* SpreadAssignment */ - ); + const rootPatternParent = findAncestor(contextualType.pattern.parent, (n) => n.kind === 260 /* VariableDeclaration */ || n.kind === 226 /* BinaryExpression */ || n.kind === 169 /* Parameter */); + const spreadOrOutsideRootObject = findAncestor(node, (n) => n === rootPatternParent || n.kind === 305 /* SpreadAssignment */); if (spreadOrOutsideRootObject.kind !== 305 /* SpreadAssignment */) { for (const prop of getPropertiesOfType(contextualType)) { if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { if (!(prop.flags & 16777216 /* Optional */)) { - error2( - prop.valueDeclaration || ((_a = tryCast(prop, isTransientSymbol)) == null ? void 0 : _a.links.bindingElement), - Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value - ); + error2(prop.valueDeclaration || ((_a = tryCast(prop, isTransientSymbol)) == null ? void 0 : _a.links.bindingElement), Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } propertiesTable.set(prop.escapedName, prop); propertiesArray.push(prop); @@ -70892,13 +71449,16 @@ ${lanes.join("\n")} checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); const nodeSourceFile = getSourceFileOfNode(node); if (getJSXTransformEnabled(compilerOptions) && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx")) && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag")) { - error2(node, compilerOptions.jsxFactory ? Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option : Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments); + error2( + node, + compilerOptions.jsxFactory ? Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option : Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments + ); } checkJsxChildren(node); return getJsxElementTypeAt(node) || anyType; } function isHyphenatedJsxName(name) { - return stringContains(name, "-"); + return name.includes("-"); } function isJsxIntrinsicTagName(tagName) { return isIdentifier(tagName) && isIntrinsicJsxName(tagName.escapedText) || isJsxNamespacedName(tagName); @@ -70995,7 +71555,7 @@ ${lanes.join("\n")} } } const parent2 = openingLikeElement.parent.kind === 284 /* JsxElement */ ? openingLikeElement.parent : void 0; - if (parent2 && parent2.openingElement === openingLikeElement && parent2.children.length > 0) { + if (parent2 && parent2.openingElement === openingLikeElement && getSemanticJsxChildren(parent2.children).length > 0) { const childrenTypes = checkJsxChildren(parent2, checkMode); if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { if (explicitlySpecifyChildrenAttribute) { @@ -71088,13 +71648,18 @@ ${lanes.join("\n")} if (!isErrorType(intrinsicElementsType)) { if (!isIdentifier(node.tagName) && !isJsxNamespacedName(node.tagName)) return Debug.fail(); - const intrinsicProp = getPropertyOfType(intrinsicElementsType, isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText); + const propName = isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText; + const intrinsicProp = getPropertyOfType(intrinsicElementsType, propName); if (intrinsicProp) { links.jsxFlags |= 1 /* IntrinsicNamedElement */; return links.resolvedSymbol = intrinsicProp; } - const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, stringType); - if (indexSignatureType) { + const indexSymbol = getApplicableIndexSymbol(intrinsicElementsType, getStringLiteralType(unescapeLeadingUnderscores(propName))); + if (indexSymbol) { + links.jsxFlags |= 2 /* IntrinsicIndexedElement */; + return links.resolvedSymbol = indexSymbol; + } + if (getTypeOfPropertyOrIndexSignatureOfType(intrinsicElementsType, propName)) { links.jsxFlags |= 2 /* IntrinsicIndexedElement */; return links.resolvedSymbol = intrinsicElementsType.symbol; } @@ -71272,6 +71837,7 @@ ${lanes.join("\n")} } } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { + var _a; Debug.assert(isJsxIntrinsicTagName(node.tagName)); const links = getNodeLinks(node); if (!links.resolvedJsxElementAttributesType) { @@ -71279,7 +71845,8 @@ ${lanes.join("\n")} if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol) || errorType; } else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { - return links.resolvedJsxElementAttributesType = getIndexTypeOfType(getJsxType(JsxNames.IntrinsicElements, node), stringType) || errorType; + const propName = isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText; + return links.resolvedJsxElementAttributesType = ((_a = getApplicableIndexInfoForName(getJsxType(JsxNames.IntrinsicElements, node), propName)) == null ? void 0 : _a.type) || errorType; } else { return links.resolvedJsxElementAttributesType = errorType; } @@ -71454,6 +72021,7 @@ ${lanes.join("\n")} return checkPropertyAccessibilityAtLocation(node, isSuper, writing, type, prop, errorNode); } function checkPropertyAccessibilityAtLocation(location, isSuper, writing, containingType, prop, errorNode) { + var _a; const flags = getDeclarationModifierFlagsFromSymbol(prop, writing); if (isSuper) { if (languageVersion < 2 /* ES2015 */) { @@ -71464,45 +72032,36 @@ ${lanes.join("\n")} return false; } } - if (flags & 256 /* Abstract */) { + if (flags & 64 /* Abstract */) { if (errorNode) { - error2( - errorNode, - Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, - symbolToString(prop), - typeToString(getDeclaringClass(prop)) - ); + error2(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } + return false; + } + if (!(flags & 256 /* Static */) && ((_a = prop.declarations) == null ? void 0 : _a.some(isClassInstanceProperty))) { + if (errorNode) { + error2(errorNode, Diagnostics.Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super, symbolToString(prop)); } return false; } } - if (flags & 256 /* Abstract */ && symbolHasNonMethodDeclaration(prop) && (isThisProperty(location) || isThisInitializedObjectBindingExpression(location) || isObjectBindingPattern(location.parent) && isThisInitializedDeclaration(location.parent.parent))) { + if (flags & 64 /* Abstract */ && symbolHasNonMethodDeclaration(prop) && (isThisProperty(location) || isThisInitializedObjectBindingExpression(location) || isObjectBindingPattern(location.parent) && isThisInitializedDeclaration(location.parent.parent))) { const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(location)) { if (errorNode) { - error2( - errorNode, - Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, - symbolToString(prop), - getTextOfIdentifierOrLiteral(declaringClassDeclaration.name) - ); + error2(errorNode, Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); } return false; } } - if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { + if (!(flags & 6 /* NonPublicAccessibilityModifier */)) { return true; } - if (flags & 8 /* Private */) { + if (flags & 2 /* Private */) { const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(location, declaringClassDeclaration)) { if (errorNode) { - error2( - errorNode, - Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, - symbolToString(prop), - typeToString(getDeclaringClass(prop)) - ); + error2(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); } return false; } @@ -71518,19 +72077,14 @@ ${lanes.join("\n")} if (!enclosingClass) { enclosingClass = getEnclosingClassFromThisParameter(location); enclosingClass = enclosingClass && isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing); - if (flags & 32 /* Static */ || !enclosingClass) { + if (flags & 256 /* Static */ || !enclosingClass) { if (errorNode) { - error2( - errorNode, - Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, - symbolToString(prop), - typeToString(getDeclaringClass(prop) || containingType) - ); + error2(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || containingType)); } return false; } } - if (flags & 32 /* Static */) { + if (flags & 256 /* Static */) { return true; } if (containingType.flags & 262144 /* TypeParameter */) { @@ -71538,13 +72092,7 @@ ${lanes.join("\n")} } if (!containingType || !hasBaseType(containingType, enclosingClass)) { if (errorNode) { - error2( - errorNode, - Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, - symbolToString(prop), - typeToString(enclosingClass), - typeToString(containingType) - ); + error2(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(containingType)); } return false; } @@ -71578,7 +72126,7 @@ ${lanes.join("\n")} return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { - return !!(getTypeFacts(type) & 50331648 /* IsUndefinedOrNull */); + return hasTypeFacts(type, 50331648 /* IsUndefinedOrNull */); } function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; @@ -71624,7 +72172,7 @@ ${lanes.join("\n")} error2(node, Diagnostics.Object_is_of_type_unknown); return errorType; } - const facts = getTypeFacts(type); + const facts = getTypeFacts(type, 50331648 /* IsUndefinedOrNull */); if (facts & 50331648 /* IsUndefinedOrNull */) { reportError(node, facts); const t = getNonNullableType(type); @@ -71839,7 +72387,7 @@ ${lanes.join("\n")} apparentType, right.escapedText, /*skipObjectFunctionPropertyAugment*/ - false, + isConstEnumObjectType(apparentType), /*includeTypeOnlyMembers*/ node.kind === 166 /* QualifiedName */ ); @@ -71904,11 +72452,17 @@ ${lanes.join("\n")} return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode); } function isUncheckedJSSuggestion(node, suggestion, excludeClasses) { + var _a; const file = getSourceFileOfNode(node); if (file) { if (compilerOptions.checkJs === void 0 && file.checkJsDirective === void 0 && (file.scriptKind === 1 /* JS */ || file.scriptKind === 2 /* JSX */)) { const declarationFile = forEach(suggestion == null ? void 0 : suggestion.declarations, getSourceFileOfNode); - return !(file !== declarationFile && !!declarationFile && isGlobalSourceFile(declarationFile)) && !(excludeClasses && suggestion && suggestion.flags & 32 /* Class */) && !(!!node && excludeClasses && isPropertyAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */); + const suggestionHasNoExtendsOrDecorators = !(suggestion == null ? void 0 : suggestion.valueDeclaration) || !isClassLike(suggestion.valueDeclaration) || ((_a = suggestion.valueDeclaration.heritageClauses) == null ? void 0 : _a.length) || classOrConstructorParameterIsDecorated( + /*useLegacyDecorators*/ + false, + suggestion.valueDeclaration + ); + return !(file !== declarationFile && !!declarationFile && isGlobalSourceFile(declarationFile)) && !(excludeClasses && suggestion && suggestion.flags & 32 /* Class */ && suggestionHasNoExtendsOrDecorators) && !(!!node && excludeClasses && isPropertyAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ && suggestionHasNoExtendsOrDecorators); } } return false; @@ -71953,16 +72507,13 @@ ${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 */) && (useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { + if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & 256 /* 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); } if (diagnosticMessage) { - addRelatedInfo( - diagnosticMessage, - createDiagnosticForNode(valueDeclaration, Diagnostics._0_is_declared_here, declarationName) - ); + addRelatedInfo(diagnosticMessage, createDiagnosticForNode(valueDeclaration, Diagnostics._0_is_declared_here, declarationName)); } } function isInPropertyInitializerOrClassStaticBlock(node) { @@ -72210,7 +72761,7 @@ ${lanes.join("\n")} if (!valueDeclaration) { return; } - const hasPrivateModifier = hasEffectiveModifier(valueDeclaration, 8 /* Private */); + const hasPrivateModifier = hasEffectiveModifier(valueDeclaration, 2 /* Private */); const hasPrivateIdentifier = prop.valueDeclaration && isNamedDeclaration(prop.valueDeclaration) && isPrivateIdentifier(prop.valueDeclaration.name); if (!hasPrivateModifier && !hasPrivateIdentifier) { return; @@ -72353,7 +72904,9 @@ ${lanes.join("\n")} checkExpression(node.template); } else if (isJsxOpeningLikeElement(node)) { checkExpression(node.attributes); - } else if (node.kind !== 170 /* Decorator */) { + } else if (isBinaryExpression(node)) { + checkExpression(node.left); + } else if (isCallOrNewExpression(node)) { forEach(node.arguments, (argument) => { checkExpression(argument); }); @@ -72426,6 +72979,8 @@ ${lanes.join("\n")} } } else if (node.kind === 170 /* Decorator */) { argCount = getDecoratorArgumentCount(node, signature); + } else if (node.kind === 226 /* BinaryExpression */) { + argCount = 1; } else if (isJsxOpeningLikeElement(node)) { callIsIncomplete = node.attributes.end === node.end; if (callIsIncomplete) { @@ -72525,13 +73080,13 @@ ${lanes.join("\n")} return voidType; } const thisArgumentType = checkExpression(thisArgumentNode); - return isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : thisArgumentType; + return isRightSideOfInstanceofExpression(thisArgumentNode) ? thisArgumentType : isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : thisArgumentType; } function inferTypeArguments(node, signature, args, checkMode, context) { if (isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); } - if (node.kind !== 170 /* Decorator */) { + if (node.kind !== 170 /* Decorator */ && node.kind !== 226 /* BinaryExpression */) { const skipBindingPatterns = every(signature.typeParameters, (p) => !!getDefaultFromTypeParameter(p)); const contextualType = getContextualType2(node, skipBindingPatterns ? 8 /* SkipBindingPatterns */ : 0 /* None */); if (contextualType) { @@ -72626,9 +73181,11 @@ ${lanes.join("\n")} } if (arg.kind === 237 /* SyntheticExpression */ && arg.tupleNameSource) { names.push(arg.tupleNameSource); + } else { + names.push(void 0); } } - return createTupleType(types, flags, inConstContext, length(names) === length(types) ? names : void 0); + return createTupleType(types, flags, inConstContext && !someType(restType, isMutableArrayLikeType), names); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors2, headMessage) { const isJavascript = isInJSFile(signature.declaration); @@ -72860,6 +73417,9 @@ ${lanes.join("\n")} } } function getThisArgumentOfCall(node) { + if (node.kind === 226 /* BinaryExpression */) { + return node.right; + } 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); @@ -72888,6 +73448,9 @@ ${lanes.join("\n")} if (node.kind === 170 /* Decorator */) { return getEffectiveDecoratorArguments(node); } + if (node.kind === 226 /* BinaryExpression */) { + return [node.left]; + } if (isJsxOpeningLikeElement(node)) { return node.attributes.properties.length > 0 || isJsxOpeningElement(node) && node.parent.children.length > 0 ? [node.attributes] : emptyArray; } @@ -72902,12 +73465,7 @@ ${lanes.join("\n")} forEach(getElementTypes(spreadType), (t, i2) => { var _a; const flags = spreadType.target.elementFlags[i2]; - const syntheticArg = createSyntheticExpression( - arg, - flags & 4 /* Rest */ ? createArrayType(t) : t, - !!(flags & 12 /* Variable */), - (_a = spreadType.target.labeledElementDeclarations) == null ? void 0 : _a[i2] - ); + const syntheticArg = createSyntheticExpression(arg, flags & 4 /* Rest */ ? createArrayType(t) : t, !!(flags & 12 /* Variable */), (_a = spreadType.target.labeledElementDeclarations) == null ? void 0 : _a[i2]); effectiveArgs.push(syntheticArg); }); } else { @@ -73162,9 +73720,10 @@ ${lanes.join("\n")} const isTaggedTemplate = node.kind === 215 /* TaggedTemplateExpression */; const isDecorator2 = node.kind === 170 /* Decorator */; const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node); + const isInstanceof = node.kind === 226 /* BinaryExpression */; const reportErrors2 = !isInferencePartiallyBlocked && !candidatesOutArray; let typeArguments; - if (!isDecorator2 && !isSuperCall(node)) { + if (!isDecorator2 && !isInstanceof && !isSuperCall(node)) { typeArguments = node.typeArguments; if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 108 /* SuperKeyword */) { forEach(typeArguments, checkSourceElement); @@ -73193,6 +73752,9 @@ ${lanes.join("\n")} result = getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); getNodeLinks(node).resolvedSignature = result; if (reportErrors2) { + if (!headMessage && isInstanceof) { + headMessage = Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_hand_side_s_Symbol_hasInstance_method; + } if (candidatesForArgumentError) { if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) { const last2 = candidatesForArgumentError[candidatesForArgumentError.length - 1]; @@ -73644,7 +74206,7 @@ ${lanes.join("\n")} return resolveErrorCall(node); } const valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && hasSyntacticModifier(valueDecl, 256 /* Abstract */)) { + if (valueDecl && hasSyntacticModifier(valueDecl, 64 /* Abstract */)) { error2(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } @@ -73707,7 +74269,7 @@ ${lanes.join("\n")} return true; } const declaration = signature.declaration; - const modifiers = getSelectedEffectiveModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); + const modifiers = getSelectedEffectiveModifierFlags(declaration, 6 /* NonPublicAccessibilityModifier */); if (!modifiers || declaration.kind !== 176 /* Constructor */) { return true; } @@ -73715,16 +74277,16 @@ ${lanes.join("\n")} const declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { const containingClass = getContainingClass(node); - if (containingClass && modifiers & 16 /* Protected */) { + if (containingClass && modifiers & 4 /* Protected */) { const containingType = getTypeOfNode(containingClass); if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { return true; } } - if (modifiers & 8 /* Private */) { + if (modifiers & 2 /* Private */) { error2(node, Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } - if (modifiers & 16 /* Protected */) { + if (modifiers & 4 /* Protected */) { error2(node, Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } return false; @@ -73825,10 +74387,7 @@ ${lanes.join("\n")} const sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); if (!sigs || !sigs.length) return; - addRelatedInfo( - diagnostic, - createDiagnosticForNode(importNode, Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead) - ); + addRelatedInfo(diagnostic, createDiagnosticForNode(importNode, Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); } } function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) { @@ -73982,6 +74541,30 @@ ${lanes.join("\n")} } return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */); } + function resolveInstanceofExpression(node, candidatesOutArray, checkMode) { + const rightType = checkExpression(node.right); + if (!isTypeAny(rightType)) { + const hasInstanceMethodType = getSymbolHasInstanceMethodOfObjectType(rightType); + if (hasInstanceMethodType) { + const apparentType = getApparentType(hasInstanceMethodType); + if (isErrorType(apparentType)) { + return resolveErrorCall(node); + } + const callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + const constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + if (isUntypedFunctionCall(hasInstanceMethodType, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + if (callSignatures.length) { + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); + } + } else if (!(typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { + error2(node.right, Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_type_assignable_to_the_Function_interface_type_or_an_object_type_with_a_Symbol_hasInstance_method); + return resolveErrorCall(node); + } + } + return anySignature; + } function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && every(signatures, (signature) => signature.minArgumentCount === 0 && !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature)); } @@ -73998,6 +74581,8 @@ ${lanes.join("\n")} case 286 /* JsxOpeningElement */: case 285 /* JsxSelfClosingElement */: return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode); + case 226 /* BinaryExpression */: + return resolveInstanceofExpression(node, candidatesOutArray, checkMode); } Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -74455,12 +75040,7 @@ ${lanes.join("\n")} addLazyDiagnostic(() => { const widenedType = getWidenedType(exprType); if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo( - exprType, - targetType, - errNode, - Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first - ); + checkTypeComparableTo(exprType, targetType, errNode, Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); } }); } @@ -74617,14 +75197,14 @@ ${lanes.join("\n")} return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType; } function getTypeOfParameter(symbol) { - const type = getTypeOfSymbol(symbol); - if (strictNullChecks) { - const declaration = symbol.valueDeclaration; - if (declaration && hasInitializer(declaration)) { - return getOptionalType(type); - } - } - return type; + const declaration = symbol.valueDeclaration; + return addOptionality( + getTypeOfSymbol(symbol), + /*isProperty*/ + false, + /*isOptional*/ + !!declaration && (hasInitializer(declaration) || isOptionalDeclaration(declaration)) + ); } function getTupleElementLabel(d, index, restParameterName = "arg") { if (!d) { @@ -74722,7 +75302,7 @@ ${lanes.join("\n")} } return void 0; } - function getRestTypeAtPosition(source, pos) { + function getRestTypeAtPosition(source, pos, readonly) { const parameterCount = getParameterCount(source); const minArgumentCount = getMinArgumentCount(source); const restType = getEffectiveRestType(source); @@ -74740,18 +75320,9 @@ ${lanes.join("\n")} types.push(restType); flags.push(8 /* Variadic */); } - const name = getNameableDeclarationAtPosition(source, i); - if (name) { - names.push(name); - } + names.push(getNameableDeclarationAtPosition(source, i)); } - return createTupleType( - types, - flags, - /*readonly*/ - false, - length(names) === length(types) ? names : void 0 - ); + return createTupleType(types, flags, readonly, names); } function getParameterCount(signature) { const length2 = signature.parameters.length; @@ -74831,11 +75402,16 @@ ${lanes.join("\n")} const len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (let i = 0; i < len; i++) { const declaration = signature.parameters[i].valueDeclaration; - if (declaration.type) { - const typeNode = getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); - } + const typeNode = getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + const source = addOptionality( + getTypeFromTypeNode(typeNode), + /*isProperty*/ + false, + isOptionalDeclaration(declaration) + ); + const target = getTypeAtPosition(context, i); + inferTypes(inferenceContext.inferences, source, target); } } } @@ -74884,29 +75460,40 @@ ${lanes.join("\n")} assignParameterType(parameter); } } - function assignParameterType(parameter, type) { + function assignParameterType(parameter, contextualType) { const links = getSymbolLinks(parameter); if (!links.type) { const declaration = parameter.valueDeclaration; - links.type = type || (declaration ? getWidenedTypeForVariableLikeDeclaration( - declaration, - /*reportErrors*/ - true - ) : getTypeOfSymbol(parameter)); + links.type = addOptionality( + contextualType || (declaration ? getWidenedTypeForVariableLikeDeclaration( + declaration, + /*reportErrors*/ + true + ) : getTypeOfSymbol(parameter)), + /*isProperty*/ + false, + /*isOptional*/ + !!declaration && !declaration.initializer && isOptionalDeclaration(declaration) + ); if (declaration && declaration.name.kind !== 80 /* Identifier */) { if (links.type === unknownType) { links.type = getTypeFromBindingPattern(declaration.name); } assignBindingElementTypes(declaration.name, links.type); } - } else if (type) { - Debug.assertEqual(links.type, type, "Parameter symbol already has a cached type which differs from newly assigned type"); + } else if (contextualType) { + Debug.assertEqual(links.type, contextualType, "Parameter symbol already has a cached type which differs from newly assigned type"); } } function assignBindingElementTypes(pattern, parentType) { for (const element of pattern.elements) { if (!isOmittedExpression(element)) { - const type = getBindingElementTypeFromParentType(element, parentType); + const type = getBindingElementTypeFromParentType( + element, + parentType, + /*noTupleBoundsCheck*/ + false + ); if (element.name.kind === 80 /* Identifier */) { getSymbolLinks(getSymbolOfDeclaration(element)).type = type; } else { @@ -75177,13 +75764,19 @@ ${lanes.join("\n")} function createPromiseReturnType(func, promisedType) { const promiseType = createPromiseType(promisedType); if (promiseType === unknownType) { - error2(func, isImportCall(func) ? Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + error2( + func, + isImportCall(func) ? Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option + ); return errorType; } else if (!getGlobalPromiseConstructorSymbol( /*reportErrors*/ true )) { - error2(func, isImportCall(func) ? Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : 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( + func, + isImportCall(func) ? Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : 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 + ); } return promiseType; } @@ -75366,7 +75959,11 @@ ${lanes.join("\n")} function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) { const errorNode = node.expression || node; const yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType; - return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken ? Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + return !isAsync ? yieldedType : getAwaitedType( + yieldedType, + errorNode, + node.asteriskToken ? Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + ); } function getNotEqualFactsFromTypeofSwitch(start, end, witnesses) { let facts = 0 /* None */; @@ -75400,7 +75997,7 @@ ${lanes.join("\n")} if (operandConstraint.flags & 3 /* AnyOrUnknown */) { return (556800 /* AllTypeofNE */ & notEqualFacts) === 556800 /* AllTypeofNE */; } - return !someType(operandConstraint, (t) => (getTypeFacts(t) & notEqualFacts) === notEqualFacts); + return !someType(operandConstraint, (t) => getTypeFacts(t, notEqualFacts) === notEqualFacts); } const type = checkExpressionCached(node.expression); if (!isLiteralType(type)) { @@ -75421,8 +76018,20 @@ ${lanes.join("\n")} let hasReturnWithNoExpression = functionHasImplicitReturn(func); let hasReturnOfTypeNever = false; forEachReturnStatement(func.body, (returnStatement) => { - const expr = returnStatement.expression; + let expr = returnStatement.expression; if (expr) { + expr = skipParentheses( + expr, + /*excludeJSDocTypeAssertions*/ + true + ); + if (functionFlags & 2 /* Async */ && expr.kind === 223 /* AwaitExpression */) { + expr = skipParentheses( + expr.expression, + /*excludeJSDocTypeAssertions*/ + true + ); + } if (expr.kind === 213 /* CallExpression */ && expr.expression.kind === 80 /* Identifier */ && checkExpressionCached(expr.expression).symbol === func.symbol) { hasReturnOfTypeNever = true; return; @@ -75654,7 +76263,7 @@ ${lanes.join("\n")} return !setProp; } function isReadonlySymbol(symbol) { - return !!(getCheckFlags(symbol) & 8 /* Readonly */ || symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 6 /* Constant */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || symbol.flags & 8 /* EnumMember */ || some(symbol.declarations, isReadonlyAssignmentDeclaration)); + return !!(getCheckFlags(symbol) & 8 /* Readonly */ || symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 8 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 6 /* Constant */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || symbol.flags & 8 /* EnumMember */ || some(symbol.declarations, isReadonlyAssignmentDeclaration)); } function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) { var _a, _b; @@ -75718,14 +76327,15 @@ ${lanes.join("\n")} if (symbol) { if (isReadonlySymbol(symbol)) { error2(expr, Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } else { + checkDeleteExpressionMustBeOptional(expr, symbol); } - checkDeleteExpressionMustBeOptional(expr, symbol); } return booleanType; } function checkDeleteExpressionMustBeOptional(expr, symbol) { const type = getTypeOfSymbol(symbol); - if (strictNullChecks && !(type.flags & (3 /* AnyOrUnknown */ | 131072 /* Never */)) && !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* Optional */ : getTypeFacts(type) & 16777216 /* IsUndefined */)) { + if (strictNullChecks && !(type.flags & (3 /* AnyOrUnknown */ | 131072 /* Never */)) && !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* Optional */ : hasTypeFacts(type, 16777216 /* IsUndefined */))) { error2(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_optional); } } @@ -75734,7 +76344,7 @@ ${lanes.join("\n")} return typeofType; } function checkVoidExpression(node) { - checkExpression(node.expression); + checkNodeDeferred(node); return undefinedWideningType; } function checkAwaitGrammar(node) { @@ -75860,15 +76470,11 @@ ${lanes.join("\n")} return getUnaryResultType(operandType); case 54 /* ExclamationToken */: checkTruthinessOfType(operandType, node.operand); - const facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */); + const facts = getTypeFacts(operandType, 4194304 /* Truthy */ | 8388608 /* Falsy */); return facts === 4194304 /* Truthy */ ? falseType : facts === 8388608 /* Falsy */ ? trueType : booleanType; case 46 /* PlusPlusToken */: case 47 /* MinusMinusToken */: - const ok = checkArithmeticOperandType( - node.operand, - checkNonNullType(operandType, node.operand), - Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type - ); + const ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { checkReferenceExpression( node.operand, @@ -75944,16 +76550,35 @@ ${lanes.join("\n")} function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; } - function checkInstanceOfExpression(left, right, leftType, rightType) { + function getSymbolHasInstanceMethodOfObjectType(type) { + const hasInstancePropertyName = getPropertyNameForKnownSymbolName("hasInstance"); + const hasInstanceProperty = getPropertyOfObjectType(type, hasInstancePropertyName); + if (hasInstanceProperty) { + const hasInstancePropertyType = getTypeOfSymbol(hasInstanceProperty); + if (hasInstancePropertyType && getSignaturesOfType(hasInstancePropertyType, 0 /* Call */).length !== 0) { + return hasInstancePropertyType; + } + } + } + function checkInstanceOfExpression(left, right, leftType, rightType, checkMode) { if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } if (!isTypeAny(leftType) && allTypesAssignableToKind(leftType, 402784252 /* Primitive */)) { error2(left, Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } - if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { - error2(right, Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + Debug.assert(isInstanceOfExpression(left.parent)); + const signature = getResolvedSignature( + left.parent, + /*candidatesOutArray*/ + void 0, + checkMode + ); + if (signature === resolvingSignature) { + return silentNeverType; } + const returnType = getReturnTypeOfSignature(signature); + checkTypeAssignableTo(returnType, booleanType, right, Diagnostics.An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_hand_side_of_an_instanceof_expression); return booleanType; } function hasEmptyObjectIntersection(type) { @@ -76095,7 +76720,7 @@ ${lanes.join("\n")} if (exprOrAssignment.kind === 304 /* ShorthandPropertyAssignment */) { const prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { - if (strictNullChecks && !(getTypeFacts(checkExpression(prop.objectAssignmentInitializer)) & 16777216 /* IsUndefined */)) { + if (strictNullChecks && !hasTypeFacts(checkExpression(prop.objectAssignmentInitializer), 16777216 /* IsUndefined */)) { sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -76461,7 +77086,9 @@ ${lanes.join("\n")} } if (!resultType) { const closeEnoughKind = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 3 /* AnyOrUnknown */; - reportOperatorError((left2, right2) => isTypeAssignableToKind(left2, closeEnoughKind) && isTypeAssignableToKind(right2, closeEnoughKind)); + reportOperatorError( + (left2, right2) => isTypeAssignableToKind(left2, closeEnoughKind) && isTypeAssignableToKind(right2, closeEnoughKind) + ); return anyType; } if (operator === 65 /* PlusEqualsToken */) { @@ -76489,7 +77116,7 @@ ${lanes.join("\n")} case 36 /* ExclamationEqualsToken */: case 37 /* EqualsEqualsEqualsToken */: case 38 /* ExclamationEqualsEqualsToken */: - if (!(checkMode && checkMode & 128 /* TypeOnly */)) { + if (!(checkMode && checkMode & 64 /* TypeOnly */)) { if ((isLiteralExpressionOfObject(left) || isLiteralExpressionOfObject(right)) && // only report for === and !== in JS, not == or != (!isInJSFile(left) || (operator === 37 /* EqualsEqualsEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */))) { const eqType = operator === 35 /* EqualsEqualsToken */ || operator === 37 /* EqualsEqualsEqualsToken */; @@ -76500,12 +77127,12 @@ ${lanes.join("\n")} } return booleanType; case 104 /* InstanceOfKeyword */: - return checkInstanceOfExpression(left, right, leftType, rightType); + return checkInstanceOfExpression(left, right, leftType, rightType, checkMode); case 103 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); case 56 /* AmpersandAmpersandToken */: case 77 /* AmpersandAmpersandEqualsToken */: { - const resultType2 = getTypeFacts(leftType) & 4194304 /* Truthy */ ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; + const resultType2 = hasTypeFacts(leftType, 4194304 /* Truthy */) ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; if (operator === 77 /* AmpersandAmpersandEqualsToken */) { checkAssignmentOperator(rightType); } @@ -76513,7 +77140,7 @@ ${lanes.join("\n")} } case 57 /* BarBarToken */: case 76 /* BarBarEqualsToken */: { - const resultType2 = getTypeFacts(leftType) & 8388608 /* Falsy */ ? getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2 /* Subtype */) : leftType; + const resultType2 = hasTypeFacts(leftType, 8388608 /* Falsy */) ? getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2 /* Subtype */) : leftType; if (operator === 76 /* BarBarEqualsToken */) { checkAssignmentOperator(rightType); } @@ -76521,7 +77148,7 @@ ${lanes.join("\n")} } case 61 /* QuestionQuestionToken */: case 78 /* QuestionQuestionEqualsToken */: { - const resultType2 = getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ? getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) : leftType; + const resultType2 = hasTypeFacts(leftType, 262144 /* EQUndefinedOrNull */) ? getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) : leftType; if (operator === 78 /* QuestionQuestionEqualsToken */) { checkAssignmentOperator(rightType); } @@ -76625,11 +77252,7 @@ ${lanes.join("\n")} true ); } - if (checkReferenceExpression( - left, - Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access, - Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access - )) { + if (checkReferenceExpression(left, Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access, Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access)) { let headMessage; if (exactOptionalPropertyTypes && isPropertyAccessExpression(left) && maybeTypeOfKind(valueType, 32768 /* Undefined */)) { const target = getTypeOfPropertyOfType(getTypeOfExpression(left.expression), left.name.escapedText); @@ -76711,21 +77334,13 @@ ${lanes.join("\n")} const isLeftNaN = isGlobalNaN(skipParentheses(left2)); const isRightNaN = isGlobalNaN(skipParentheses(right2)); if (isLeftNaN || isRightNaN) { - const err = error2( - errorNode2, - Diagnostics.This_condition_will_always_return_0, - tokenToString(operator2 === 37 /* EqualsEqualsEqualsToken */ || operator2 === 35 /* EqualsEqualsToken */ ? 97 /* FalseKeyword */ : 112 /* TrueKeyword */) - ); + const err = error2(errorNode2, Diagnostics.This_condition_will_always_return_0, tokenToString(operator2 === 37 /* EqualsEqualsEqualsToken */ || operator2 === 35 /* EqualsEqualsToken */ ? 97 /* FalseKeyword */ : 112 /* TrueKeyword */)); if (isLeftNaN && isRightNaN) return; const operatorString = operator2 === 38 /* ExclamationEqualsEqualsToken */ || operator2 === 36 /* ExclamationEqualsToken */ ? tokenToString(54 /* ExclamationToken */) : ""; const location = isLeftNaN ? right2 : left2; const expression = skipParentheses(location); - addRelatedInfo(err, createDiagnosticForNode( - location, - Diagnostics.Did_you_mean_0, - `${operatorString}Number.isNaN(${isEntityNameExpression(expression) ? entityNameToString(expression) : "..."})` - )); + addRelatedInfo(err, createDiagnosticForNode(location, Diagnostics.Did_you_mean_0, `${operatorString}Number.isNaN(${isEntityNameExpression(expression) ? entityNameToString(expression) : "..."})`)); } } function isGlobalNaN(expr) { @@ -76765,7 +77380,15 @@ ${lanes.join("\n")} checkExternalEmitHelpers(node, 256 /* Values */); } } - const returnType = getReturnTypeFromAnnotation(func); + let returnType = getReturnTypeFromAnnotation(func); + if (returnType && returnType.flags & 1048576 /* Union */) { + returnType = filterType(returnType, (t) => checkGeneratorInstantiationAssignabilityToReturnType( + t, + functionFlags, + /*errorNode*/ + void 0 + )); + } const iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync); const signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType; const signatureNextType = iterationTypes && iterationTypes.nextType || anyType; @@ -77149,7 +77772,7 @@ ${lanes.join("\n")} } } const startInvocationCount = flowInvocationCount; - const type = checkExpression(node, 128 /* TypeOnly */); + const type = checkExpression(node, 64 /* TypeOnly */); if (flowInvocationCount !== startInvocationCount) { const cache = flowTypeCache || (flowTypeCache = []); cache[getNodeId(node)] = type; @@ -77264,7 +77887,7 @@ ${lanes.join("\n")} return nullWideningType; case 15 /* NoSubstitutionTemplateLiteral */: case 11 /* StringLiteral */: - return hasSkipDirectInferenceFlag(node) ? wildcardType : getFreshTypeOfLiteralType(getStringLiteralType(node.text)); + return hasSkipDirectInferenceFlag(node) ? blockedStringType : getFreshTypeOfLiteralType(getStringLiteralType(node.text)); case 9 /* NumericLiteral */: checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getNumberLiteralType(+node.text)); @@ -77381,15 +78004,15 @@ ${lanes.join("\n")} var _a, _b; if (isInterfaceDeclaration(node.parent) || isClassLike(node.parent) || isTypeAliasDeclaration(node.parent)) { const typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node)); - const modifiers = getTypeParameterModifiers(typeParameter) & (32768 /* In */ | 65536 /* Out */); + const modifiers = getTypeParameterModifiers(typeParameter) & (8192 /* In */ | 16384 /* Out */); if (modifiers) { const symbol = getSymbolOfDeclaration(node.parent); if (isTypeAliasDeclaration(node.parent) && !(getObjectFlags(getDeclaredTypeOfSymbol(symbol)) & (16 /* Anonymous */ | 32 /* Mapped */))) { error2(node, Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types); - } else if (modifiers === 32768 /* In */ || modifiers === 65536 /* Out */) { + } else if (modifiers === 8192 /* In */ || modifiers === 16384 /* Out */) { (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.CheckTypes, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) }); - const source = createMarkerType(symbol, typeParameter, modifiers === 65536 /* Out */ ? markerSubTypeForCheck : markerSuperTypeForCheck); - const target = createMarkerType(symbol, typeParameter, modifiers === 65536 /* Out */ ? markerSuperTypeForCheck : markerSubTypeForCheck); + const source = createMarkerType(symbol, typeParameter, modifiers === 16384 /* Out */ ? markerSubTypeForCheck : markerSuperTypeForCheck); + const target = createMarkerType(symbol, typeParameter, modifiers === 16384 /* Out */ ? markerSuperTypeForCheck : markerSubTypeForCheck); const saveVarianceTypeParameter = typeParameter; varianceTypeParameter = typeParameter; checkTypeAssignableTo(source, target, node, Diagnostics.Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation); @@ -77403,7 +78026,7 @@ ${lanes.join("\n")} checkGrammarModifiers(node); checkVariableLikeDeclaration(node); const func = getContainingFunction(node); - if (hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { + if (hasSyntacticModifier(node, 31 /* ParameterPropertyModifier */)) { if (!(func.kind === 176 /* Constructor */ && nodeIsPresent(func.body))) { error2(node, Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } @@ -77504,11 +78127,7 @@ ${lanes.join("\n")} } const name = element.name; if (name.kind === 80 /* Identifier */ && name.escapedText === predicateVariableName) { - error2( - predicateVariableNode, - Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, - predicateVariableName - ); + error2(predicateVariableNode, Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } else if (name.kind === 207 /* ArrayBindingPattern */ || name.kind === 206 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern( @@ -77577,11 +78196,7 @@ ${lanes.join("\n")} if (returnType === voidType) { 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, returnTypeErrorLocation); + checkGeneratorInstantiationAssignabilityToReturnType(returnType, functionFlags2, returnTypeErrorLocation); } } else if ((functionFlags2 & 3 /* AsyncGenerator */) === 2 /* Async */) { checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation); @@ -77592,6 +78207,13 @@ ${lanes.join("\n")} } } } + function checkGeneratorInstantiationAssignabilityToReturnType(returnType, functionFlags, errorNode) { + const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags & 2 /* Async */) !== 0) || anyType; + const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags & 2 /* Async */) !== 0) || generatorYieldType; + const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags & 2 /* Async */) !== 0) || unknownType; + const generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags & 2 /* Async */)); + return checkTypeAssignableTo(generatorInstantiation, returnType, errorNode); + } function checkClassForDuplicateDeclarations(node) { const instanceNames = /* @__PURE__ */ new Map(); const staticNames = /* @__PURE__ */ new Map(); @@ -77612,7 +78234,7 @@ ${lanes.join("\n")} const isPrivate = isPrivateIdentifier(name); const privateStaticFlags = isPrivate && isStaticMember ? 16 /* PrivateStatic */ : 0; const names = isPrivate ? privateIdentifiers : isStaticMember ? staticNames : instanceNames; - const memberName = name && getPropertyNameForPropertyNameNode(name); + const memberName = name && getEffectivePropertyNameForPropertyNameNode(name); if (memberName) { switch (member.kind) { case 177 /* GetAccessor */: @@ -77659,7 +78281,7 @@ ${lanes.join("\n")} const memberNameNode = member.name; const isStaticMember = isStatic(member); if (isStaticMember && memberNameNode) { - const memberName = getPropertyNameForPropertyNameNode(memberNameNode); + const memberName = getEffectivePropertyNameForPropertyNameNode(memberNameNode); switch (memberName) { case "name": case "length": @@ -77739,7 +78361,7 @@ ${lanes.join("\n")} checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); setNodeLinksForPrivateIdentifierScope(node); - if (hasSyntacticModifier(node, 256 /* Abstract */) && node.kind === 172 /* PropertyDeclaration */ && node.initializer) { + if (hasSyntacticModifier(node, 64 /* Abstract */) && node.kind === 172 /* PropertyDeclaration */ && node.initializer) { error2(node, Diagnostics.Property_0_cannot_have_an_initializer_because_it_is_marked_abstract, declarationNameToString(node.name)); } } @@ -77756,7 +78378,7 @@ ${lanes.join("\n")} error2(node.name, Diagnostics.Class_constructor_may_not_be_a_generator); } checkFunctionOrMethodDeclaration(node); - if (hasSyntacticModifier(node, 256 /* Abstract */) && node.kind === 174 /* MethodDeclaration */ && node.body) { + if (hasSyntacticModifier(node, 64 /* Abstract */) && node.kind === 174 /* MethodDeclaration */ && node.body) { error2(node, Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, declarationNameToString(node.name)); } if (isPrivateIdentifier(node.name) && !getContainingClass(node)) { @@ -77813,7 +78435,7 @@ ${lanes.join("\n")} if (classExtendsNull) { error2(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - const superCallShouldBeRootLevel = !emitStandardClassFields && (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, 31 /* 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); @@ -77882,11 +78504,11 @@ ${lanes.join("\n")} getNodeLinks(getter).flags |= 1 /* TypeChecked */; const getterFlags = getEffectiveModifierFlags(getter); const setterFlags = getEffectiveModifierFlags(setter); - if ((getterFlags & 256 /* Abstract */) !== (setterFlags & 256 /* Abstract */)) { + if ((getterFlags & 64 /* Abstract */) !== (setterFlags & 64 /* Abstract */)) { error2(getter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); error2(setter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } - if (getterFlags & 16 /* Protected */ && !(setterFlags & (16 /* Protected */ | 8 /* Private */)) || getterFlags & 8 /* Private */ && !(setterFlags & 8 /* Private */)) { + if (getterFlags & 4 /* Protected */ && !(setterFlags & (4 /* Protected */ | 2 /* Private */)) || getterFlags & 2 /* Private */ && !(setterFlags & 2 /* Private */)) { error2(getter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); error2(setter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } @@ -77908,12 +78530,7 @@ ${lanes.join("\n")} return getEffectiveTypeArguments2(node, typeParameters)[index]; } function getEffectiveTypeArguments2(node, typeParameters) { - return fillMissingTypeArguments( - map(node.typeArguments, getTypeFromTypeNode), - typeParameters, - getMinTypeArgumentCount(typeParameters), - isInJSFile(node) - ); + return fillMissingTypeArguments(map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { let typeArguments; @@ -78071,7 +78688,7 @@ ${lanes.join("\n")} const propertyName = getPropertyNameFromIndex(indexType, accessNode); if (propertyName) { const propertySymbol = forEachType(apparentObjectType, (t) => getPropertyOfType(t, propertyName)); - if (propertySymbol && getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */) { + if (propertySymbol && getDeclarationModifierFlagsFromSymbol(propertySymbol) & 6 /* NonPublicAccessibilityModifier */) { error2(accessNode, Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, unescapeLeadingUnderscores(propertyName)); return errorType; } @@ -78150,16 +78767,8 @@ ${lanes.join("\n")} } function checkImportType(node) { checkSourceElement(node.argument); - if (node.assertions) { - const override = getResolutionModeOverrideForClause(node.assertions.assertClause, grammarErrorOnNode); - if (override) { - if (!isNightly()) { - grammarErrorOnNode(node.assertions.assertClause, Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); - } - if (getEmitModuleResolutionKind(compilerOptions) !== 3 /* Node16 */ && getEmitModuleResolutionKind(compilerOptions) !== 99 /* NodeNext */) { - grammarErrorOnNode(node.assertions.assertClause, Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); - } - } + if (node.attributes) { + getResolutionModeOverride(node.attributes, grammarErrorOnNode); } checkTypeReferenceOrImport(node); } @@ -78177,16 +78786,16 @@ ${lanes.join("\n")} getTypeFromTypeNode(node); } function isPrivateWithinAmbient(node) { - return (hasEffectiveModifier(node, 8 /* Private */) || isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 33554432 /* Ambient */); + return (hasEffectiveModifier(node, 2 /* Private */) || isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 33554432 /* Ambient */); } function getEffectiveDeclarationFlags(n, flagsToCheck) { let flags = getCombinedModifierFlagsCached(n); if (n.parent.kind !== 264 /* InterfaceDeclaration */ && n.parent.kind !== 263 /* ClassDeclaration */ && n.parent.kind !== 231 /* ClassExpression */ && n.flags & 33554432 /* Ambient */) { const container = getEnclosingContainer(n); - if (container && container.flags & 128 /* ExportContext */ && !(flags & 2 /* Ambient */) && !(isModuleBlock(n.parent) && isModuleDeclaration(n.parent.parent) && isGlobalScopeAugmentation(n.parent.parent))) { - flags |= 1 /* Export */; + if (container && container.flags & 128 /* ExportContext */ && !(flags & 128 /* Ambient */) && !(isModuleBlock(n.parent) && isModuleDeclaration(n.parent.parent) && isGlobalScopeAugmentation(n.parent.parent))) { + flags |= 32 /* Export */; } - flags |= 2 /* Ambient */; + flags |= 128 /* Ambient */; } return flags & flagsToCheck; } @@ -78204,13 +78813,13 @@ ${lanes.join("\n")} const canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck2); forEach(overloads, (o) => { const deviation = getEffectiveDeclarationFlags(o, flagsToCheck2) ^ canonicalFlags; - if (deviation & 1 /* Export */) { + if (deviation & 32 /* Export */) { error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); - } else if (deviation & 2 /* Ambient */) { + } else if (deviation & 128 /* Ambient */) { error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); - } else if (deviation & (8 /* Private */ | 16 /* Protected */)) { + } else if (deviation & (2 /* Private */ | 4 /* Protected */)) { error2(getNameOfDeclaration(o) || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); - } else if (deviation & 256 /* Abstract */) { + } else if (deviation & 64 /* Abstract */) { error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); @@ -78227,7 +78836,7 @@ ${lanes.join("\n")} }); } } - const flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 256 /* Abstract */; + const flagsToCheck = 32 /* Export */ | 128 /* Ambient */ | 2 /* Private */ | 4 /* Protected */ | 64 /* Abstract */; let someNodeFlags = 0 /* None */; let allNodeFlags = flagsToCheck; let someHaveQuestionToken = false; @@ -78275,7 +78884,7 @@ ${lanes.join("\n")} if (isConstructor) { error2(errorNode, Diagnostics.Constructor_implementation_is_missing); } else { - if (hasSyntacticModifier(node, 256 /* Abstract */)) { + if (hasSyntacticModifier(node, 64 /* Abstract */)) { error2(errorNode, Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { error2(errorNode, Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); @@ -78361,7 +78970,7 @@ ${lanes.join("\n")} } }); } - if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !hasSyntacticModifier(lastSeenNonAmbientDeclaration, 256 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !hasSyntacticModifier(lastSeenNonAmbientDeclaration, 64 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -78404,9 +79013,9 @@ ${lanes.join("\n")} let defaultExportedDeclarationSpaces = 0 /* None */; for (const d of symbol.declarations) { const declarationSpaces = getDeclarationSpaces(d); - const effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 1024 /* Default */); - if (effectiveDeclarationFlags & 1 /* Export */) { - if (effectiveDeclarationFlags & 1024 /* Default */) { + const effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 32 /* Export */ | 2048 /* Default */); + if (effectiveDeclarationFlags & 32 /* Export */) { + if (effectiveDeclarationFlags & 2048 /* Default */) { defaultExportedDeclarationSpaces |= declarationSpaces; } else { exportedDeclarationSpaces |= declarationSpaces; @@ -78728,12 +79337,7 @@ ${lanes.join("\n")} const rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); const collidingSymbol = getSymbol2(node.locals, rootName.escapedText, 111551 /* Value */); if (collidingSymbol) { - error2( - collidingSymbol.valueDeclaration, - Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, - idText(rootName), - entityNameToString(promiseConstructorName) - ); + error2(collidingSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, idText(rootName), entityNameToString(promiseConstructorName)); return; } } @@ -79052,6 +79656,12 @@ ${lanes.join("\n")} } } } + function checkJSDocThisTag(node) { + const host2 = getEffectiveJSDocHost(node); + if (host2 && isArrowFunction(host2)) { + error2(node.tagName, Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } + } function checkJSDocImplementsTag(node) { const classLike = getEffectiveJSDocHost(node); if (!classLike || !isClassDeclaration(classLike) && !isClassExpression(classLike)) { @@ -79214,13 +79824,13 @@ ${lanes.join("\n")} break; } const symbol = getSymbolOfDeclaration(member); - if (!symbol.isReferenced && (hasEffectiveModifier(member, 8 /* Private */) || isNamedDeclaration(member) && isPrivateIdentifier(member.name)) && !(member.flags & 33554432 /* Ambient */)) { + if (!symbol.isReferenced && (hasEffectiveModifier(member, 2 /* Private */) || isNamedDeclaration(member) && isPrivateIdentifier(member.name)) && !(member.flags & 33554432 /* Ambient */)) { addDiagnostic(member, 0 /* Local */, createDiagnosticForNode(member.name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; case 176 /* Constructor */: for (const parameter of member.parameters) { - if (!parameter.symbol.isReferenced && hasSyntacticModifier(parameter, 8 /* Private */)) { + if (!parameter.symbol.isReferenced && hasSyntacticModifier(parameter, 2 /* Private */)) { addDiagnostic(parameter, 0 /* Local */, createDiagnosticForNode(parameter.name, Diagnostics.Property_0_is_declared_but_its_value_is_never_read, symbolName(parameter.symbol))); } } @@ -79336,7 +79946,11 @@ ${lanes.join("\n")} const importDecl = importClause.parent; const nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? importClause.namedBindings.kind === 274 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length : 0); if (nDeclarations === unuseds.length) { - addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 ? createDiagnosticForNode(importDecl, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(first(unuseds).name)) : createDiagnosticForNode(importDecl, Diagnostics.All_imports_in_import_declaration_are_unused)); + addDiagnostic( + importDecl, + 0 /* Local */, + unuseds.length === 1 ? createDiagnosticForNode(importDecl, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(first(unuseds).name)) : createDiagnosticForNode(importDecl, Diagnostics.All_imports_in_import_declaration_are_unused) + ); } else { for (const unused of unuseds) errorUnusedLocal(unused, idText(unused.name), addDiagnostic); @@ -79348,7 +79962,11 @@ ${lanes.join("\n")} if (bindingElements.length === 1 && bindingPattern.parent.kind === 260 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 261 /* VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { - addDiagnostic(bindingPattern, kind, bindingElements.length === 1 ? createDiagnosticForNode(bindingPattern, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(bindingElements).name)) : createDiagnosticForNode(bindingPattern, Diagnostics.All_destructured_elements_are_unused)); + addDiagnostic( + bindingPattern, + kind, + bindingElements.length === 1 ? createDiagnosticForNode(bindingPattern, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(bindingElements).name)) : createDiagnosticForNode(bindingPattern, Diagnostics.All_destructured_elements_are_unused) + ); } } else { for (const e of bindingElements) { @@ -79358,7 +79976,11 @@ ${lanes.join("\n")} }); unusedVariables.forEach(([declarationList, declarations]) => { if (declarationList.declarations.length === declarations.length) { - addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? createDiagnosticForNode(first(declarations).name, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(declarations).name)) : createDiagnosticForNode(declarationList.parent.kind === 243 /* VariableStatement */ ? declarationList.parent : declarationList, Diagnostics.All_variables_are_unused)); + addDiagnostic( + declarationList, + 0 /* Local */, + declarations.length === 1 ? createDiagnosticForNode(first(declarations).name, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(declarations).name)) : createDiagnosticForNode(declarationList.parent.kind === 243 /* VariableStatement */ ? declarationList.parent : declarationList, Diagnostics.All_variables_are_unused) + ); } else { for (const decl of declarations) { addDiagnostic(decl, 0 /* Local */, createDiagnosticForNode(decl, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); @@ -79486,13 +80108,7 @@ ${lanes.join("\n")} } const parent2 = getDeclarationContainer(node); if (parent2.kind === 312 /* SourceFile */ && isExternalOrCommonJsModule(parent2)) { - errorSkippedOn( - "noEmit", - name, - Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, - declarationNameToString(name), - declarationNameToString(name) - ); + errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, declarationNameToString(name), declarationNameToString(name)); } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { @@ -79504,13 +80120,7 @@ ${lanes.join("\n")} } const parent2 = getDeclarationContainer(node); if (parent2.kind === 312 /* SourceFile */ && isExternalOrCommonJsModule(parent2) && parent2.flags & 4096 /* HasAsyncFunctions */) { - errorSkippedOn( - "noEmit", - name, - Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, - declarationNameToString(name), - declarationNameToString(name) - ); + errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, declarationNameToString(name), declarationNameToString(name)); } } function recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name) { @@ -79551,13 +80161,7 @@ ${lanes.join("\n")} } if (hasCollision) { Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name), "The target of a Reflect collision check should be an identifier"); - errorSkippedOn( - "noEmit", - node, - Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers, - declarationNameToString(node.name), - "Reflect" - ); + errorSkippedOn("noEmit", node, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers, declarationNameToString(node.name), "Reflect"); } } function checkCollisionsForDeclarationName(node, name) { @@ -79638,7 +80242,7 @@ ${lanes.join("\n")} checkComputedPropertyName(node.propertyName); } const parent2 = node.parent.parent; - const parentCheckMode = node.dotDotDotToken ? 64 /* RestBindingElement */ : 0 /* Normal */; + const parentCheckMode = node.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */; const parentType = getTypeForBindingElementParent(parent2, parentCheckMode); const name = node.propertyName || node.name; if (parentType && !isBindingPattern(name)) { @@ -79672,7 +80276,7 @@ ${lanes.join("\n")} } forEach(node.name.elements, checkSourceElement); } - if (isParameter(node) && node.initializer && nodeIsMissing(getContainingFunction(node).body)) { + if (node.initializer && isParameterDeclaration(node) && nodeIsMissing(getContainingFunction(node).body)) { error2(node, Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } @@ -79792,10 +80396,7 @@ ${lanes.join("\n")} typeToString(nextType) ); if (firstDeclaration) { - addRelatedInfo( - err, - createDiagnosticForNode(firstDeclaration, Diagnostics._0_was_also_declared_here, declName) - ); + addRelatedInfo(err, createDiagnosticForNode(firstDeclaration, Diagnostics._0_was_also_declared_here, declName)); } } function areDeclarationFlagsIdentical(left, right) { @@ -79805,7 +80406,7 @@ ${lanes.join("\n")} if (hasQuestionToken(left) !== hasQuestionToken(right)) { return false; } - const interestingFlags = 8 /* Private */ | 16 /* Protected */ | 512 /* Async */ | 256 /* Abstract */ | 64 /* Readonly */ | 32 /* Static */; + const interestingFlags = 2 /* Private */ | 4 /* Protected */ | 1024 /* Async */ | 64 /* Abstract */ | 8 /* Readonly */ | 256 /* Static */; return getSelectedEffectiveModifierFlags(left, interestingFlags) === getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { @@ -79868,7 +80469,7 @@ ${lanes.join("\n")} } const type = location === condExpr2 ? condType : checkTruthinessExpression(location); const isPropertyExpressionCast = isPropertyAccessExpression(location) && isTypeAssertion(location.expression); - if (!(getTypeFacts(type) & 4194304 /* Truthy */) || isPropertyExpressionCast) + if (!hasTypeFacts(type, 4194304 /* Truthy */) || isPropertyExpressionCast) return; const callSignatures = getSignaturesOfType(type, 0 /* Call */); const isPromise = !!getAwaitedTypeOfPromise(type); @@ -80432,13 +81033,10 @@ ${lanes.join("\n")} !!getAwaitedTypeOfPromise(type) || !allowAsyncIterables && isForOfStatement(errorNode.parent) && errorNode.parent.expression === errorNode && getGlobalAsyncIterableType( /*reportErrors*/ false - ) !== emptyGenericType && isTypeAssignableTo( - type, - getGlobalAsyncIterableType( - /*reportErrors*/ - false - ) - ) + ) !== emptyGenericType && isTypeAssignableTo(type, getGlobalAsyncIterableType( + /*reportErrors*/ + false + )) ); return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); } @@ -80895,14 +81493,7 @@ ${lanes.join("\n")} const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0; const errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base) => !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0); if (errorNode && !isTypeAssignableTo(propType, info.type)) { - const diagnostic = createError( - errorNode, - Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, - symbolToString(prop), - typeToString(propType), - typeToString(info.keyType), - typeToString(info.type) - ); + const diagnostic = createError(errorNode, Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); if (propDeclaration && errorNode !== propDeclaration) { addRelatedInfo(diagnostic, createDiagnosticForNode(propDeclaration, Diagnostics._0_is_declared_here, symbolToString(prop))); } @@ -80921,14 +81512,7 @@ ${lanes.join("\n")} const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0; const errorNode = localCheckDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base) => !!getIndexInfoOfType(base, checkInfo.keyType) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0); if (errorNode && !isTypeAssignableTo(checkInfo.type, info.type)) { - error2( - errorNode, - Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3, - typeToString(checkInfo.keyType), - typeToString(checkInfo.type), - typeToString(info.keyType), - typeToString(info.type) - ); + error2(errorNode, Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3, typeToString(checkInfo.keyType), typeToString(checkInfo.type), typeToString(info.keyType), typeToString(info.type)); } } } @@ -81150,7 +81734,7 @@ ${lanes.join("\n")} if (legacyDecorators && firstDecorator && some(node.members, (p) => hasStaticModifier(p) && isPrivateIdentifierClassElementDeclaration(p))) { grammarErrorOnNode(firstDecorator, Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); } - if (!node.name && !hasSyntacticModifier(node, 1024 /* Default */)) { + if (!node.name && !hasSyntacticModifier(node, 2048 /* Default */)) { grammarErrorOnFirstToken(node, Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -81209,19 +81793,14 @@ ${lanes.join("\n")} )) { issueMemberSpecificError(node, typeWithThis, baseWithThis, Diagnostics.Class_0_incorrectly_extends_base_class_1); } else { - checkTypeAssignableTo( - staticType, - getTypeWithoutSignatures(staticBaseType), - node.name || node, - Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1 - ); + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); } if (baseConstructorType.flags & 8650752 /* TypeVariable */) { if (!isMixinConstructorType(staticType)) { error2(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } else { const constructSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); - if (constructSignatures.some((signature) => signature.flags & 4 /* Abstract */) && !hasSyntacticModifier(node, 256 /* Abstract */)) { + if (constructSignatures.some((signature) => signature.flags & 4 /* Abstract */) && !hasSyntacticModifier(node, 64 /* Abstract */)) { error2(node.name || node, Diagnostics.A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract); } } @@ -81435,7 +82014,7 @@ ${lanes.join("\n")} const signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length) { const declaration = signatures[0].declaration; - if (declaration && hasEffectiveModifier(declaration, 8 /* Private */)) { + if (declaration && hasEffectiveModifier(declaration, 2 /* Private */)) { const typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error2(node, Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); @@ -81455,7 +82034,7 @@ ${lanes.join("\n")} const baseTypes = baseTypeNode && getBaseTypes(type); const baseWithThis = (baseTypes == null ? void 0 : baseTypes.length) ? getTypeWithThisArgument(first(baseTypes), type.thisType) : void 0; const baseStaticType = getBaseConstructorTypeOfClass(type); - const memberHasOverrideModifier = member.parent ? hasOverrideModifier(member) : hasSyntacticModifier(member, 16384 /* Override */); + const memberHasOverrideModifier = member.parent ? hasOverrideModifier(member) : hasSyntacticModifier(member, 16 /* Override */); return checkMemberForOverrideModifier( node, staticType, @@ -81496,7 +82075,7 @@ ${lanes.join("\n")} Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived === base) { const derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 256 /* Abstract */ && (!derivedClassDecl || !hasSyntacticModifier(derivedClassDecl, 256 /* Abstract */))) { + if (baseDeclarationFlags & 64 /* Abstract */ && (!derivedClassDecl || !hasSyntacticModifier(derivedClassDecl, 64 /* Abstract */))) { for (const otherBaseType of getBaseTypes(type)) { if (otherBaseType === baseType) continue; @@ -81539,7 +82118,7 @@ ${lanes.join("\n")} } } else { const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); - if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) { + if (baseDeclarationFlags & 2 /* Private */ || derivedDeclarationFlags & 2 /* Private */) { continue; } let errorMessage; @@ -81556,7 +82135,7 @@ ${lanes.join("\n")} error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType), typeToString(type)); } else if (useDefineForClassFields) { const uninitialized = (_c = derived.declarations) == null ? void 0 : _c.find((d) => d.kind === 172 /* PropertyDeclaration */ && !d.initializer); - if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 256 /* Abstract */) && !(derivedDeclarationFlags & 256 /* Abstract */) && !((_d = derived.declarations) == null ? void 0 : _d.some((d) => !!(d.flags & 33554432 /* Ambient */)))) { + if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 64 /* Abstract */) && !(derivedDeclarationFlags & 64 /* Abstract */) && !((_d = derived.declarations) == null ? void 0 : _d.some((d) => !!(d.flags & 33554432 /* Ambient */)))) { const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol)); const propName = uninitialized.name; if (uninitialized.exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { @@ -81583,7 +82162,7 @@ ${lanes.join("\n")} } } function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) { - return baseDeclarationFlags & 256 /* Abstract */ && (!isPropertyDeclaration(declaration) || !declaration.initializer) || isInterfaceDeclaration(declaration.parent); + return baseDeclarationFlags & 64 /* Abstract */ && (!isPropertyDeclaration(declaration) || !declaration.initializer) || isInterfaceDeclaration(declaration.parent); } function getNonInheritedProperties(type, baseTypes, properties) { if (!length(baseTypes)) { @@ -81648,7 +82227,7 @@ ${lanes.join("\n")} } const constructor = findConstructorDeclaration(node); for (const member of node.members) { - if (getEffectiveModifierFlags(member) & 2 /* Ambient */) { + if (getEffectiveModifierFlags(member) & 128 /* Ambient */) { continue; } if (!isStatic(member) && isPropertyWithoutInitializer(member)) { @@ -81777,7 +82356,10 @@ ${lanes.join("\n")} const value = evaluate(initializer, member); if (value !== void 0) { if (isConstEnum && typeof value === "number" && !isFinite(value)) { - error2(initializer, isNaN(value) ? Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + error2( + initializer, + isNaN(value) ? Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value + ); } } else if (isConstEnum) { error2(initializer, Diagnostics.const_enum_member_initializers_must_be_constant_expressions); @@ -81877,7 +82459,7 @@ ${lanes.join("\n")} } if (isConstantVariable(symbol)) { const declaration = symbol.valueDeclaration; - if (declaration && !declaration.type && declaration.initializer && (!location || declaration !== location && isBlockScopedNameDeclaredBeforeUse(declaration, location))) { + if (declaration && isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && (!location || declaration !== location && isBlockScopedNameDeclaredBeforeUse(declaration, location))) { return evaluate(declaration.initializer, declaration); } } @@ -82144,7 +82726,10 @@ ${lanes.join("\n")} } const inAmbientExternalModule = node.parent.kind === 268 /* ModuleBlock */ && isAmbientModule(node.parent.parent); if (node.parent.kind !== 312 /* SourceFile */ && !inAmbientExternalModule) { - error2(moduleName, node.kind === 278 /* ExportDeclaration */ ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + error2( + moduleName, + node.kind === 278 /* ExportDeclaration */ ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module + ); return false; } if (inAmbientExternalModule && isExternalModuleNameRelative(moduleName.text)) { @@ -82153,12 +82738,13 @@ ${lanes.join("\n")} return false; } } - if (!isImportEqualsDeclaration(node) && node.assertClause) { + if (!isImportEqualsDeclaration(node) && node.attributes) { + const diagnostic = node.attributes.token === 118 /* WithKeyword */ ? Diagnostics.Import_attribute_values_must_be_string_literal_expressions : Diagnostics.Import_assertion_values_must_be_string_literal_expressions; let hasError = false; - for (const clause of node.assertClause.elements) { - if (!isStringLiteral(clause.value)) { + for (const attr of node.attributes.elements) { + if (!isStringLiteral(attr.value)) { hasError = true; - error2(clause.value, Diagnostics.Import_assertion_values_must_be_string_literal_expressions); + error2(attr.value, diagnostic); } } return !hasError; @@ -82180,11 +82766,14 @@ ${lanes.join("\n")} if (alreadyExportedSymbol === target) { const exportingDeclaration = (_c = alreadyExportedSymbol.declarations) == null ? void 0 : _c.find(isJSDocNode); if (exportingDeclaration) { - addRelatedInfo(diag2, createDiagnosticForNode( - exportingDeclaration, - Diagnostics._0_is_automatically_exported_here, - unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName) - )); + addRelatedInfo( + diag2, + createDiagnosticForNode( + exportingDeclaration, + Diagnostics._0_is_automatically_exported_here, + unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName) + ) + ); } } } else { @@ -82225,7 +82814,7 @@ ${lanes.join("\n")} name ); } - if (isType && node.kind === 271 /* ImportEqualsDeclaration */ && hasEffectiveModifier(node, 1 /* Export */)) { + if (isType && node.kind === 271 /* ImportEqualsDeclaration */ && hasEffectiveModifier(node, 32 /* Export */)) { error2(node, Diagnostics.Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled, isolatedModulesLikeFlagName); } break; @@ -82287,32 +82876,26 @@ ${lanes.join("\n")} checkExternalEmitHelpers(node, 131072 /* ImportDefault */); } } - function checkAssertClause(declaration) { + function checkImportAttributes(declaration) { var _a; - if (declaration.assertClause) { - const validForTypeAssertions = isExclusivelyTypeOnlyImportOrExport(declaration); - const override = getResolutionModeOverrideForClause(declaration.assertClause, validForTypeAssertions ? grammarErrorOnNode : void 0); - if (validForTypeAssertions && override) { - if (!isNightly()) { - grammarErrorOnNode(declaration.assertClause, Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); - } - if (getEmitModuleResolutionKind(compilerOptions) !== 3 /* Node16 */ && getEmitModuleResolutionKind(compilerOptions) !== 99 /* NodeNext */) { - return grammarErrorOnNode(declaration.assertClause, Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); - } + const node = declaration.attributes; + if (node) { + const validForTypeAttributes = isExclusivelyTypeOnlyImportOrExport(declaration); + const override = getResolutionModeOverride(node, validForTypeAttributes ? grammarErrorOnNode : void 0); + const isImportAttributes2 = declaration.attributes.token === 118 /* WithKeyword */; + if (validForTypeAttributes && override) { return; } const mode = moduleKind === 199 /* NodeNext */ && declaration.moduleSpecifier && getUsageModeForExpression(declaration.moduleSpecifier); if (mode !== 99 /* ESNext */ && moduleKind !== 99 /* ESNext */) { - return grammarErrorOnNode( - declaration.assertClause, - moduleKind === 199 /* NodeNext */ ? Diagnostics.Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls : Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext - ); + const message = isImportAttributes2 ? moduleKind === 199 /* NodeNext */ ? Diagnostics.Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls : Diagnostics.Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext : moduleKind === 199 /* NodeNext */ ? Diagnostics.Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls : Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext; + return grammarErrorOnNode(node, message); } if (isImportDeclaration(declaration) ? (_a = declaration.importClause) == null ? void 0 : _a.isTypeOnly : declaration.isTypeOnly) { - return grammarErrorOnNode(declaration.assertClause, Diagnostics.Import_assertions_cannot_be_used_with_type_only_imports_or_exports); + return grammarErrorOnNode(node, isImportAttributes2 ? Diagnostics.Import_attributes_cannot_be_used_with_type_only_imports_or_exports : Diagnostics.Import_assertions_cannot_be_used_with_type_only_imports_or_exports); } if (override) { - return grammarErrorOnNode(declaration.assertClause, Diagnostics.resolution_mode_can_only_be_set_for_type_only_imports); + return grammarErrorOnNode(node, Diagnostics.resolution_mode_can_only_be_set_for_type_only_imports); } } } @@ -82344,7 +82927,7 @@ ${lanes.join("\n")} } } } - checkAssertClause(node); + checkImportAttributes(node); } function checkImportEqualsDeclaration(node) { if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) { @@ -82353,7 +82936,7 @@ ${lanes.join("\n")} checkGrammarModifiers(node); if (isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (hasSyntacticModifier(node, 1 /* Export */)) { + if (hasSyntacticModifier(node, 32 /* Export */)) { markExportAsReferenced(node); } if (node.moduleReference.kind !== 283 /* ExternalModuleReference */) { @@ -82417,7 +83000,7 @@ ${lanes.join("\n")} } } } - checkAssertClause(node); + checkImportAttributes(node); } function checkGrammarExportDeclaration(node) { var _a; @@ -82767,6 +83350,8 @@ ${lanes.join("\n")} return checkJSDocAccessibilityModifiers(node); case 357 /* JSDocSatisfiesTag */: return checkJSDocSatisfiesTag(node); + case 350 /* JSDocThisTag */: + return checkJSDocThisTag(node); case 199 /* IndexedAccessType */: return checkIndexedAccessType(node); case 200 /* MappedType */: @@ -82853,9 +83438,14 @@ ${lanes.join("\n")} const diagnostic = node.postfix ? Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1 : Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1; const typeNode = node.type; const type = getTypeFromTypeNode(typeNode); - grammarErrorOnNode(node, diagnostic, token, typeToString( - isJSDocNullableType(node) && !(type === neverType || type === voidType) ? getUnionType(append([type, undefinedType], node.postfix ? void 0 : nullType)) : type - )); + grammarErrorOnNode( + node, + diagnostic, + token, + typeToString( + isJSDocNullableType(node) && !(type === neverType || type === voidType) ? getUnionType(append([type, undefinedType], node.postfix ? void 0 : nullType)) : type + ) + ); } else { grammarErrorOnNode(node, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } @@ -82965,6 +83555,15 @@ ${lanes.join("\n")} case 234 /* AsExpression */: case 217 /* ParenthesizedExpression */: checkAssertionDeferred(node); + break; + case 222 /* VoidExpression */: + checkExpression(node.expression); + break; + case 226 /* BinaryExpression */: + if (isInstanceOfExpression(node)) { + resolveUntypedCall(node); + } + break; } currentNode = saveCurrentNode; (_b = tracing) == null ? void 0 : _b.pop(); @@ -83404,31 +84003,7 @@ ${lanes.join("\n")} if (name.kind === 211 /* PropertyAccessExpression */) { checkPropertyAccessExpression(name, 0 /* Normal */); if (!links.resolvedSymbol) { - const expressionType = checkExpressionCached(name.expression); - const infos = getApplicableIndexInfos(expressionType, getLiteralTypeFromPropertyName(name.name)); - if (infos.length && expressionType.members) { - const resolved = resolveStructuredTypeMembers(expressionType); - const symbol = resolved.members.get("__index" /* Index */); - if (infos === getIndexInfosOfType(expressionType)) { - links.resolvedSymbol = symbol; - } else if (symbol) { - const symbolLinks2 = getSymbolLinks(symbol); - const declarationList = mapDefined(infos, (i) => i.declaration); - const nodeListId = map(declarationList, getNodeId).join(","); - if (!symbolLinks2.filteredIndexSymbolCache) { - symbolLinks2.filteredIndexSymbolCache = /* @__PURE__ */ new Map(); - } - if (symbolLinks2.filteredIndexSymbolCache.has(nodeListId)) { - links.resolvedSymbol = symbolLinks2.filteredIndexSymbolCache.get(nodeListId); - } else { - const copy = createSymbol(131072 /* Signature */, "__index" /* Index */); - copy.declarations = mapDefined(infos, (i) => i.declaration); - copy.parent = expressionType.aliasSymbol ? expressionType.aliasSymbol : expressionType.symbol ? expressionType.symbol : getSymbolAtLocation(copy.declarations[0].parent); - symbolLinks2.filteredIndexSymbolCache.set(nodeListId, copy); - links.resolvedSymbol = symbolLinks2.filteredIndexSymbolCache.get(nodeListId); - } - } - } + links.resolvedSymbol = getApplicableIndexSymbol(checkExpressionCached(name.expression), getLiteralTypeFromPropertyName(name.name)); } } else { checkQualifiedName(name, 0 /* Normal */); @@ -83461,6 +84036,31 @@ ${lanes.join("\n")} } return void 0; } + function getApplicableIndexSymbol(type, keyType) { + const infos = getApplicableIndexInfos(type, keyType); + if (infos.length && type.members) { + const symbol = getIndexSymbolFromSymbolTable(resolveStructuredTypeMembers(type).members); + if (infos === getIndexInfosOfType(type)) { + return symbol; + } else if (symbol) { + const symbolLinks2 = getSymbolLinks(symbol); + const declarationList = mapDefined(infos, (i) => i.declaration); + const nodeListId = map(declarationList, getNodeId).join(","); + if (!symbolLinks2.filteredIndexSymbolCache) { + symbolLinks2.filteredIndexSymbolCache = /* @__PURE__ */ new Map(); + } + if (symbolLinks2.filteredIndexSymbolCache.has(nodeListId)) { + return symbolLinks2.filteredIndexSymbolCache.get(nodeListId); + } else { + const copy = createSymbol(131072 /* Signature */, "__index" /* Index */); + copy.declarations = mapDefined(infos, (i) => i.declaration); + copy.parent = type.aliasSymbol ? type.aliasSymbol : type.symbol ? type.symbol : getSymbolAtLocation(copy.declarations[0].parent); + symbolLinks2.filteredIndexSymbolCache.set(nodeListId, copy); + return copy; + } + } + } + } function resolveJSDocMemberName(name, ignoreErrors, container) { if (isEntityName(name)) { const meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; @@ -83583,6 +84183,13 @@ ${lanes.join("\n")} case 102 /* ImportKeyword */: case 105 /* NewKeyword */: return isMetaProperty(node.parent) ? checkMetaPropertyKeyword(node.parent).symbol : void 0; + case 104 /* InstanceOfKeyword */: + if (isBinaryExpression(node.parent)) { + const type = getTypeOfExpression(node.parent.right); + const hasInstanceMethodType = getSymbolHasInstanceMethodOfObjectType(type); + return (hasInstanceMethodType == null ? void 0 : hasInstanceMethodType.symbol) ?? type.symbol; + } + return void 0; case 236 /* MetaProperty */: return checkExpression(node).symbol; case 295 /* JsxNamespacedName */: @@ -83953,7 +84560,7 @@ ${lanes.join("\n")} } const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); if (target === unknownSymbol) { - return true; + return !excludeTypeOnlyValues || !getTypeOnlyAliasDeclaration(symbol); } return !!(getSymbolFlags( symbol, @@ -83974,7 +84581,7 @@ ${lanes.join("\n")} return true; } const target = getSymbolLinks(symbol).aliasTarget; - if (target && getEffectiveModifierFlags(node) & 1 /* Export */ && getSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { + if (target && getEffectiveModifierFlags(node) & 32 /* Export */ && getSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { return true; } } @@ -83999,10 +84606,10 @@ ${lanes.join("\n")} return false; } function isRequiredInitializedParameter(parameter) { - return !!strictNullChecks && !isOptionalParameter(parameter) && !isJSDocParameterTag(parameter) && !!parameter.initializer && !hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); + return !!strictNullChecks && !isOptionalParameter(parameter) && !isJSDocParameterTag(parameter) && !!parameter.initializer && !hasSyntacticModifier(parameter, 31 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { - return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); + return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && hasSyntacticModifier(parameter, 31 /* ParameterPropertyModifier */); } function isExpandoFunctionDeclaration(node) { const declaration = getParseTreeNode(node, isFunctionDeclaration); @@ -84013,7 +84620,7 @@ ${lanes.join("\n")} if (!symbol || !(symbol.flags & 16 /* Function */)) { return false; } - return !!forEachEntry(getExportsOfSymbol(symbol), (p) => p.flags & 111551 /* Value */ && p.valueDeclaration && isPropertyAccessExpression(p.valueDeclaration)); + return !!forEachEntry(getExportsOfSymbol(symbol), (p) => p.flags & 111551 /* Value */ && isExpandoPropertyDeclaration(p.valueDeclaration)); } function getPropertiesOfContainerFunction(node) { const declaration = getParseTreeNode(node, isFunctionDeclaration); @@ -84423,7 +85030,16 @@ ${lanes.join("\n")} } return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled); }, - isImportRequiredByAugmentation + isImportRequiredByAugmentation, + tryFindAmbientModule: (moduleReferenceExpression) => { + const node = getParseTreeNode(moduleReferenceExpression); + const moduleSpecifier = node && isStringLiteralLike(node) ? node.text : void 0; + return moduleSpecifier !== void 0 ? tryFindAmbientModule( + moduleSpecifier, + /*withAugmentations*/ + true + ) : void 0; + } }; function isImportRequiredByAugmentation(node) { const file = getSourceFileOfNode(node); @@ -84520,11 +85136,11 @@ ${lanes.join("\n")} if (fileToDirective.has(file.path)) return; fileToDirective.set(file.path, [key, mode]); - for (const { fileName, resolutionMode } of file.referencedFiles) { + for (const { fileName } of file.referencedFiles) { const resolvedFile = resolveTripleslashReference(fileName, file.fileName); const referencedFile = host.getSourceFile(resolvedFile); if (referencedFile) { - addReferencedFilesToTypeDirective(referencedFile, key, resolutionMode || file.impliedNodeFormat); + addReferencedFilesToTypeDirective(referencedFile, key, mode || file.impliedNodeFormat); } } } @@ -84850,10 +85466,10 @@ ${lanes.join("\n")} return grammarErrorOnFirstToken(node, Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); } } - if (flags & ~(1025 /* ExportDefault */ | 131072 /* Decorator */)) { + if (flags & ~(2080 /* ExportDefault */ | 32768 /* Decorator */)) { return grammarErrorOnNode(modifier, Diagnostics.Decorators_are_not_valid_here); } - if (hasLeadingDecorators && flags & 126975 /* Modifier */) { + if (hasLeadingDecorators && flags & 98303 /* Modifier */) { Debug.assertIsDefined(firstDecorator); const sourceFile = getSourceFileOfNode(modifier); if (!hasParseDiagnostics(sourceFile)) { @@ -84865,10 +85481,10 @@ ${lanes.join("\n")} } return false; } - flags |= 131072 /* Decorator */; - if (!(flags & 126975 /* Modifier */)) { + flags |= 32768 /* Decorator */; + if (!(flags & 98303 /* Modifier */)) { hasLeadingDecorators = true; - } else if (flags & 1 /* Export */) { + } else if (flags & 32 /* Export */) { sawExportBeforeDecorators = true; } firstDecorator ?? (firstDecorator = modifier); @@ -84897,39 +85513,39 @@ ${lanes.join("\n")} } break; case 164 /* OverrideKeyword */: - if (flags & 16384 /* Override */) { + if (flags & 16 /* Override */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "override"); - } else if (flags & 2 /* Ambient */) { + } else if (flags & 128 /* Ambient */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); - } else if (flags & 64 /* Readonly */) { + } else if (flags & 8 /* Readonly */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); - } else if (flags & 128 /* Accessor */) { + } else if (flags & 512 /* Accessor */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "accessor"); - } else if (flags & 512 /* Async */) { + } else if (flags & 1024 /* Async */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); } - flags |= 16384 /* Override */; + flags |= 16 /* Override */; lastOverride = modifier; break; case 125 /* PublicKeyword */: case 124 /* ProtectedKeyword */: case 123 /* PrivateKeyword */: const text = visibilityToString(modifierToFlag(modifier.kind)); - if (flags & 28 /* AccessibilityModifier */) { + if (flags & 7 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, Diagnostics.Accessibility_modifier_already_seen); - } else if (flags & 16384 /* Override */) { + } else if (flags & 16 /* Override */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); - } else if (flags & 32 /* Static */) { + } else if (flags & 256 /* Static */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); - } else if (flags & 128 /* Accessor */) { + } else if (flags & 512 /* Accessor */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "accessor"); - } else if (flags & 64 /* Readonly */) { + } else if (flags & 8 /* Readonly */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); - } else if (flags & 512 /* Async */) { + } else if (flags & 1024 /* Async */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } else if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 312 /* SourceFile */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); - } else if (flags & 256 /* Abstract */) { + } else if (flags & 64 /* Abstract */) { if (modifier.kind === 123 /* PrivateKeyword */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } else { @@ -84941,60 +85557,60 @@ ${lanes.join("\n")} flags |= modifierToFlag(modifier.kind); break; case 126 /* StaticKeyword */: - if (flags & 32 /* Static */) { + if (flags & 256 /* Static */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "static"); - } else if (flags & 64 /* Readonly */) { + } else if (flags & 8 /* Readonly */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); - } else if (flags & 512 /* Async */) { + } else if (flags & 1024 /* Async */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); - } else if (flags & 128 /* Accessor */) { + } else if (flags & 512 /* Accessor */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "accessor"); } else if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 312 /* SourceFile */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } else if (node.kind === 169 /* Parameter */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); - } else if (flags & 256 /* Abstract */) { + } else if (flags & 64 /* Abstract */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); - } else if (flags & 16384 /* Override */) { + } else if (flags & 16 /* Override */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); } - flags |= 32 /* Static */; + flags |= 256 /* Static */; lastStatic = modifier; break; case 129 /* AccessorKeyword */: - if (flags & 128 /* Accessor */) { + if (flags & 512 /* Accessor */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "accessor"); - } else if (flags & 64 /* Readonly */) { + } else if (flags & 8 /* Readonly */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "readonly"); - } else if (flags & 2 /* Ambient */) { + } else if (flags & 128 /* Ambient */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "declare"); } else if (node.kind !== 172 /* PropertyDeclaration */) { return grammarErrorOnNode(modifier, Diagnostics.accessor_modifier_can_only_appear_on_a_property_declaration); } - flags |= 128 /* Accessor */; + flags |= 512 /* Accessor */; break; case 148 /* ReadonlyKeyword */: - if (flags & 64 /* Readonly */) { + if (flags & 8 /* Readonly */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "readonly"); } else if (node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 171 /* PropertySignature */ && node.kind !== 181 /* IndexSignature */ && node.kind !== 169 /* Parameter */) { return grammarErrorOnNode(modifier, Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); - } else if (flags & 128 /* Accessor */) { + } else if (flags & 512 /* Accessor */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "readonly", "accessor"); } - flags |= 64 /* Readonly */; + flags |= 8 /* Readonly */; break; case 95 /* ExportKeyword */: if (compilerOptions.verbatimModuleSyntax && !(node.flags & 33554432 /* Ambient */) && node.kind !== 265 /* TypeAliasDeclaration */ && node.kind !== 264 /* InterfaceDeclaration */ && // ModuleDeclaration needs to be checked that it is uninstantiated later node.kind !== 267 /* ModuleDeclaration */ && node.parent.kind === 312 /* SourceFile */ && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */)) { return grammarErrorOnNode(modifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); } - if (flags & 1 /* Export */) { + if (flags & 32 /* Export */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "export"); - } else if (flags & 2 /* Ambient */) { + } else if (flags & 128 /* Ambient */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); - } else if (flags & 256 /* Abstract */) { + } else if (flags & 64 /* Abstract */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); - } else if (flags & 512 /* Async */) { + } else if (flags & 1024 /* Async */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } else if (isClassLike(node.parent)) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export"); @@ -85005,7 +85621,7 @@ ${lanes.join("\n")} } else if (blockScopeKind === 6 /* AwaitUsing */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "export"); } - flags |= 1 /* Export */; + flags |= 32 /* Export */; break; case 90 /* DefaultKeyword */: const container = node.parent.kind === 312 /* SourceFile */ ? node.parent : node.parent.parent; @@ -85015,19 +85631,19 @@ ${lanes.join("\n")} return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "default"); } else if (blockScopeKind === 6 /* AwaitUsing */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "default"); - } else if (!(flags & 1 /* Export */)) { + } else if (!(flags & 32 /* Export */)) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "default"); } else if (sawExportBeforeDecorators) { return grammarErrorOnNode(firstDecorator, Diagnostics.Decorators_are_not_valid_here); } - flags |= 1024 /* Default */; + flags |= 2048 /* Default */; break; case 138 /* DeclareKeyword */: - if (flags & 2 /* Ambient */) { + if (flags & 128 /* Ambient */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "declare"); - } else if (flags & 512 /* Async */) { + } else if (flags & 1024 /* Async */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); - } else if (flags & 16384 /* Override */) { + } else if (flags & 16 /* Override */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); } else if (isClassLike(node.parent) && !isPropertyDeclaration(node)) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare"); @@ -85041,62 +85657,62 @@ ${lanes.join("\n")} return grammarErrorOnNode(modifier, Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } else if (isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare"); - } else if (flags & 128 /* Accessor */) { + } else if (flags & 512 /* Accessor */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "declare", "accessor"); } - flags |= 2 /* Ambient */; + flags |= 128 /* Ambient */; lastDeclare = modifier; break; case 128 /* AbstractKeyword */: - if (flags & 256 /* Abstract */) { + if (flags & 64 /* Abstract */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "abstract"); } if (node.kind !== 263 /* ClassDeclaration */ && node.kind !== 185 /* ConstructorType */) { if (node.kind !== 174 /* MethodDeclaration */ && node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 177 /* GetAccessor */ && node.kind !== 178 /* SetAccessor */) { return grammarErrorOnNode(modifier, Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 263 /* ClassDeclaration */ && hasSyntacticModifier(node.parent, 256 /* Abstract */))) { + if (!(node.parent.kind === 263 /* ClassDeclaration */ && hasSyntacticModifier(node.parent, 64 /* Abstract */))) { const message = node.kind === 172 /* PropertyDeclaration */ ? Diagnostics.Abstract_properties_can_only_appear_within_an_abstract_class : Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class; return grammarErrorOnNode(modifier, message); } - if (flags & 32 /* Static */) { + if (flags & 256 /* Static */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - if (flags & 8 /* Private */) { + if (flags & 2 /* Private */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); } - if (flags & 512 /* Async */ && lastAsync) { + if (flags & 1024 /* Async */ && lastAsync) { return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } - if (flags & 16384 /* Override */) { + if (flags & 16 /* Override */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); } - if (flags & 128 /* Accessor */) { + if (flags & 512 /* Accessor */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "accessor"); } } if (isNamedDeclaration(node) && node.name.kind === 81 /* PrivateIdentifier */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); } - flags |= 256 /* Abstract */; + flags |= 64 /* Abstract */; break; case 134 /* AsyncKeyword */: - if (flags & 512 /* Async */) { + if (flags & 1024 /* Async */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "async"); - } else if (flags & 2 /* Ambient */ || node.parent.flags & 33554432 /* Ambient */) { + } else if (flags & 128 /* Ambient */ || node.parent.flags & 33554432 /* Ambient */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } else if (node.kind === 169 /* Parameter */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } - if (flags & 256 /* Abstract */) { + if (flags & 64 /* Abstract */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } - flags |= 512 /* Async */; + flags |= 1024 /* Async */; lastAsync = modifier; break; case 103 /* InKeyword */: case 147 /* OutKeyword */: - const inOutFlag = modifier.kind === 103 /* InKeyword */ ? 32768 /* In */ : 65536 /* Out */; + const inOutFlag = modifier.kind === 103 /* InKeyword */ ? 8192 /* In */ : 16384 /* Out */; const inOutText = modifier.kind === 103 /* InKeyword */ ? "in" : "out"; if (node.kind !== 168 /* TypeParameter */ || !(isInterfaceDeclaration(node.parent) || isClassLike(node.parent) || isTypeAliasDeclaration(node.parent))) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias, inOutText); @@ -85104,7 +85720,7 @@ ${lanes.join("\n")} if (flags & inOutFlag) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, inOutText); } - if (inOutFlag & 32768 /* In */ && flags & 65536 /* Out */) { + if (inOutFlag & 8192 /* In */ && flags & 16384 /* Out */) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "in", "out"); } flags |= inOutFlag; @@ -85113,24 +85729,24 @@ ${lanes.join("\n")} } } if (node.kind === 176 /* Constructor */) { - if (flags & 32 /* Static */) { + if (flags & 256 /* Static */) { return grammarErrorOnNode(lastStatic, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } - if (flags & 16384 /* Override */) { + if (flags & 16 /* Override */) { return grammarErrorOnNode(lastOverride, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); } - if (flags & 512 /* Async */) { + if (flags & 1024 /* Async */) { return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } return false; - } else if ((node.kind === 272 /* ImportDeclaration */ || node.kind === 271 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + } else if ((node.kind === 272 /* ImportDeclaration */ || node.kind === 271 /* ImportEqualsDeclaration */) && flags & 128 /* Ambient */) { return grammarErrorOnNode(lastDeclare, Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); - } else if (node.kind === 169 /* Parameter */ && flags & 16476 /* ParameterPropertyModifier */ && isBindingPattern(node.name)) { + } else if (node.kind === 169 /* Parameter */ && flags & 31 /* ParameterPropertyModifier */ && isBindingPattern(node.name)) { return grammarErrorOnNode(node, Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); - } else if (node.kind === 169 /* Parameter */ && flags & 16476 /* ParameterPropertyModifier */ && node.dotDotDotToken) { + } else if (node.kind === 169 /* Parameter */ && flags & 31 /* ParameterPropertyModifier */ && node.dotDotDotToken) { return grammarErrorOnNode(node, Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } - if (flags & 512 /* Async */) { + if (flags & 1024 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); } return false; @@ -85574,10 +86190,7 @@ ${lanes.join("\n")} if (isInTopLevelContext(forInOrOfStatement)) { if (!hasParseDiagnostics(sourceFile)) { if (!isEffectiveExternalModule(sourceFile, compilerOptions)) { - diagnostics.add(createDiagnosticForNode( - forInOrOfStatement.awaitModifier, - Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module - )); + diagnostics.add(createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); } switch (moduleKind) { case 100 /* Node16 */: @@ -85596,10 +86209,7 @@ ${lanes.join("\n")} } default: diagnostics.add( - createDiagnosticForNode( - forInOrOfStatement.awaitModifier, - Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher - ) + createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher) ); break; } @@ -85656,12 +86266,12 @@ ${lanes.join("\n")} if (languageVersion < 2 /* ES2015 */ && isPrivateIdentifier(accessor.name)) { return grammarErrorOnNode(accessor.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); } - if (accessor.body === void 0 && !hasSyntacticModifier(accessor, 256 /* Abstract */)) { + if (accessor.body === void 0 && !hasSyntacticModifier(accessor, 64 /* Abstract */)) { return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, Diagnostics._0_expected, "{"); } } if (accessor.body) { - if (hasSyntacticModifier(accessor, 256 /* Abstract */)) { + if (hasSyntacticModifier(accessor, 64 /* Abstract */)) { return grammarErrorOnNode(accessor, Diagnostics.An_abstract_accessor_cannot_have_an_implementation); } if (accessor.parent.kind === 187 /* TypeLiteral */ || accessor.parent.kind === 264 /* InterfaceDeclaration */) { @@ -85733,7 +86343,7 @@ ${lanes.join("\n")} } break; case 171 /* PropertySignature */: - if (!hasSyntacticModifier(parent2, 64 /* Readonly */)) { + if (!hasSyntacticModifier(parent2, 8 /* Readonly */)) { return grammarErrorOnNode(parent2.name, Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } break; @@ -85903,7 +86513,7 @@ ${lanes.join("\n")} const message = node.initializer ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context; return grammarErrorOnNode(node.exclamationToken, message); } - if ((moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */) && moduleKind !== 4 /* System */ && !(node.parent.parent.flags & 33554432 /* Ambient */) && hasSyntacticModifier(node.parent.parent, 1 /* Export */)) { + if ((moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */) && moduleKind !== 4 /* System */ && !(node.parent.parent.flags & 33554432 /* Ambient */) && hasSyntacticModifier(node.parent.parent, 32 /* Export */)) { checkESModuleMarker(node.name); } return !!blockScopeKind && checkGrammarNameInLetOrConstDeclarations(node.name); @@ -86093,7 +86703,7 @@ ${lanes.join("\n")} } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 264 /* InterfaceDeclaration */ || node.kind === 265 /* TypeAliasDeclaration */ || node.kind === 272 /* ImportDeclaration */ || node.kind === 271 /* ImportEqualsDeclaration */ || node.kind === 278 /* ExportDeclaration */ || node.kind === 277 /* ExportAssignment */ || node.kind === 270 /* NamespaceExportDeclaration */ || hasSyntacticModifier(node, 2 /* Ambient */ | 1 /* Export */ | 1024 /* Default */)) { + if (node.kind === 264 /* InterfaceDeclaration */ || node.kind === 265 /* TypeAliasDeclaration */ || node.kind === 272 /* ImportDeclaration */ || node.kind === 271 /* ImportEqualsDeclaration */ || node.kind === 278 /* ExportDeclaration */ || node.kind === 277 /* ExportAssignment */ || node.kind === 270 /* NamespaceExportDeclaration */ || hasSyntacticModifier(node, 128 /* Ambient */ | 32 /* Export */ | 2048 /* Default */)) { return false; } return grammarErrorOnFirstToken(node, Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier); @@ -86128,7 +86738,7 @@ ${lanes.join("\n")} return false; } function checkGrammarNumericLiteral(node) { - const isFractional = getTextOfNode(node).indexOf(".") !== -1; + const isFractional = getTextOfNode(node).includes("."); const isScientific = node.numericLiteralFlags & 16 /* Scientific */; if (isFractional || isScientific) { return; @@ -86227,12 +86837,12 @@ ${lanes.join("\n")} if (moduleKind !== 99 /* ESNext */ && moduleKind !== 199 /* NodeNext */ && moduleKind !== 100 /* Node16 */) { checkGrammarForDisallowedTrailingComma(nodeArguments); if (nodeArguments.length > 1) { - const assertionArgument = nodeArguments[1]; - return grammarErrorOnNode(assertionArgument, Diagnostics.Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_or_nodenext); + const importAttributesArgument = nodeArguments[1]; + return grammarErrorOnNode(importAttributesArgument, Diagnostics.Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_or_nodenext); } } if (nodeArguments.length === 0 || nodeArguments.length > 2) { - return grammarErrorOnNode(node, Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments); + return grammarErrorOnNode(node, Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments); } const spreadElement = find(nodeArguments, isSpreadElement); if (spreadElement) { @@ -86320,7 +86930,7 @@ ${lanes.join("\n")} } function getEffectivePropertyNameForPropertyNameNode(node) { const name = getPropertyNameForPropertyNameNode(node); - return name ? name : isComputedPropertyName(node) && isEntityNameExpression(node.expression) ? tryGetNameFromEntityNameExpression(node.expression) : void 0; + return name ? name : isComputedPropertyName(node) ? tryGetNameFromType(getTypeOfExpression(node.expression)) : void 0; } function getCombinedModifierFlagsCached(node) { if (lastGetCombinedModifierFlagsNode === node) { @@ -86501,9 +87111,8 @@ ${lanes.join("\n")} CheckMode3[CheckMode3["SkipContextSensitive"] = 4] = "SkipContextSensitive"; CheckMode3[CheckMode3["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; CheckMode3[CheckMode3["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; - CheckMode3[CheckMode3["IsForStringLiteralArgumentCompletions"] = 32] = "IsForStringLiteralArgumentCompletions"; - CheckMode3[CheckMode3["RestBindingElement"] = 64] = "RestBindingElement"; - CheckMode3[CheckMode3["TypeOnly"] = 128] = "TypeOnly"; + CheckMode3[CheckMode3["RestBindingElement"] = 32] = "RestBindingElement"; + CheckMode3[CheckMode3["TypeOnly"] = 64] = "TypeOnly"; return CheckMode3; })(CheckMode || {}); SignatureCheckMode = /* @__PURE__ */ ((SignatureCheckMode3) => { @@ -86552,12 +87161,14 @@ ${lanes.join("\n")} this.canTrackSymbol = !!((_a = this.inner) == null ? void 0 : _a.trackSymbol); } trackSymbol(symbol, enclosingDeclaration, meaning) { - var _a; + var _a, _b; if (((_a = this.inner) == null ? void 0 : _a.trackSymbol) && !this.disableTrackSymbol) { if (this.inner.trackSymbol(symbol, enclosingDeclaration, meaning)) { this.onDiagnosticReported(); return true; } + if (!(symbol.flags & 262144 /* TypeParameter */)) + ((_b = this.context).trackedSymbols ?? (_b.trackedSymbols = [])).push([symbol, enclosingDeclaration, meaning]); } return false; } @@ -86631,13 +87242,6 @@ ${lanes.join("\n")} this.inner.reportNonSerializableProperty(propertyName); } } - reportImportTypeNodeResolutionModeOverride() { - var _a; - if ((_a = this.inner) == null ? void 0 : _a.reportImportTypeNodeResolutionModeOverride) { - this.onDiagnosticReported(); - this.inner.reportImportTypeNodeResolutionModeOverride(); - } - } onDiagnosticReported() { this.context.reportedDiagnostic = true; } @@ -87325,7 +87929,7 @@ ${lanes.join("\n")} return context.factory.updateImportTypeNode( node, Debug.checkDefined(nodeVisitor(node.argument, visitor, isTypeNode)), - nodeVisitor(node.assertions, visitor, isImportTypeAssertionContainer), + nodeVisitor(node.attributes, visitor, isImportAttributes), nodeVisitor(node.qualifier, visitor, isEntityName), nodesVisitor(node.typeArguments, visitor, isTypeNode), node.isTypeOf @@ -87876,20 +88480,20 @@ ${lanes.join("\n")} nodesVisitor(node.modifiers, visitor, isModifierLike), nodeVisitor(node.importClause, visitor, isImportClause), Debug.checkDefined(nodeVisitor(node.moduleSpecifier, visitor, isExpression)), - nodeVisitor(node.assertClause, visitor, isAssertClause) + nodeVisitor(node.attributes, visitor, isImportAttributes) ); }, - [300 /* AssertClause */]: function visitEachChildOfAssertClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateAssertClause( + [300 /* ImportAttributes */]: function visitEachChildOfImportAttributes(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateImportAttributes( node, - nodesVisitor(node.elements, visitor, isAssertEntry), + nodesVisitor(node.elements, visitor, isImportAttribute), node.multiLine ); }, - [301 /* AssertEntry */]: function visitEachChildOfAssertEntry(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateAssertEntry( + [301 /* ImportAttribute */]: function visitEachChildOfImportAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportAttribute( node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isAssertionKey)), + Debug.checkDefined(nodeVisitor(node.name, visitor, isImportAttributeName)), Debug.checkDefined(nodeVisitor(node.value, visitor, isExpression)) ); }, @@ -87941,7 +88545,7 @@ ${lanes.join("\n")} node.isTypeOnly, nodeVisitor(node.exportClause, visitor, isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, isExpression), - nodeVisitor(node.assertClause, visitor, isAssertClause) + nodeVisitor(node.attributes, visitor, isImportAttributes) ); }, [279 /* NamedExports */]: function visitEachChildOfNamedExports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { @@ -88368,7 +88972,7 @@ ${lanes.join("\n")} const line = lineInfo.getLineText(index); const comment = sourceMapCommentRegExp.exec(line); if (comment) { - return trimStringEnd(comment[1]); + return comment[1].trimEnd(); } else if (!line.match(whitespaceOrMapCommentRegExp)) { break; } @@ -88795,15 +89399,15 @@ ${lanes.join("\n")} } break; case 243 /* VariableStatement */: - if (hasSyntacticModifier(node, 1 /* Export */)) { + if (hasSyntacticModifier(node, 32 /* Export */)) { for (const decl of node.declarationList.declarations) { exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings); } } break; case 262 /* FunctionDeclaration */: - if (hasSyntacticModifier(node, 1 /* Export */)) { - if (hasSyntacticModifier(node, 1024 /* Default */)) { + if (hasSyntacticModifier(node, 32 /* Export */)) { + if (hasSyntacticModifier(node, 2048 /* Default */)) { if (!hasExportDefault) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node)); hasExportDefault = true; @@ -88819,8 +89423,8 @@ ${lanes.join("\n")} } break; case 263 /* ClassDeclaration */: - if (hasSyntacticModifier(node, 1 /* Export */)) { - if (hasSyntacticModifier(node, 1024 /* Default */)) { + if (hasSyntacticModifier(node, 32 /* Export */)) { + if (hasSyntacticModifier(node, 2048 /* Default */)) { if (!hasExportDefault) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node)); hasExportDefault = true; @@ -89710,7 +90314,7 @@ ${lanes.join("\n")} // src/compiler/transformers/namedEvaluation.ts function getAssignedNameOfIdentifier(factory2, name, expression) { const original = getOriginalNode(skipOuterExpressions(expression)); - if ((isClassDeclaration(original) || isFunctionDeclaration(original)) && !original.name && hasSyntacticModifier(original, 1024 /* Default */)) { + if ((isClassDeclaration(original) || isFunctionDeclaration(original)) && !original.name && hasSyntacticModifier(original, 2048 /* Default */)) { return factory2.createStringLiteral("default"); } return factory2.createStringLiteralFromNode(name); @@ -89978,10 +90582,7 @@ ${lanes.join("\n")} function getRawLiteral(factory2, node, currentSourceFile) { let text = node.rawText; if (text === void 0) { - Debug.assertIsDefined( - currentSourceFile, - "Template literal node is missing 'rawText' and does not have a source file. Possibly bad transform." - ); + Debug.assertIsDefined(currentSourceFile, "Template literal node is missing 'rawText' and does not have a source file. Possibly bad transform."); text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node); const isLast = node.kind === 15 /* NoSubstitutionTemplateLiteral */ || node.kind === 18 /* TemplateTail */; text = text.substring(1, text.length - (isLast ? 1 : 2)); @@ -90040,12 +90641,15 @@ ${lanes.join("\n")} return transformSourceFile(node); } function transformBundle(node) { - return factory2.createBundle(node.sourceFiles.map(transformSourceFile), mapDefined(node.prepends, (prepend) => { - if (prepend.kind === 315 /* InputFiles */) { - return createUnparsedSourceFile(prepend, "js"); - } - return prepend; - })); + return factory2.createBundle( + node.sourceFiles.map(transformSourceFile), + mapDefined(node.prepends, (prepend) => { + if (prepend.kind === 315 /* InputFiles */) { + return createUnparsedSourceFile(prepend, "js"); + } + return prepend; + }) + ); } function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -90081,13 +90685,13 @@ ${lanes.join("\n")} break; case 263 /* ClassDeclaration */: case 262 /* FunctionDeclaration */: - if (hasSyntacticModifier(node, 2 /* Ambient */)) { + if (hasSyntacticModifier(node, 128 /* Ambient */)) { break; } if (node.name) { recordEmittedDeclarationInScope(node); } else { - Debug.assert(node.kind === 263 /* ClassDeclaration */ || hasSyntacticModifier(node, 1024 /* Default */)); + Debug.assert(node.kind === 263 /* ClassDeclaration */ || hasSyntacticModifier(node, 2048 /* Default */)); } break; } @@ -90142,7 +90746,7 @@ ${lanes.join("\n")} function namespaceElementVisitorWorker(node) { if (node.kind === 278 /* ExportDeclaration */ || node.kind === 272 /* ImportDeclaration */ || node.kind === 273 /* ImportClause */ || node.kind === 271 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 283 /* ExternalModuleReference */) { return void 0; - } else if (node.transformFlags & 1 /* ContainsTypeScript */ || hasSyntacticModifier(node, 1 /* Export */)) { + } else if (node.transformFlags & 1 /* ContainsTypeScript */ || hasSyntacticModifier(node, 32 /* Export */)) { return visitTypeScript(node); } return node; @@ -90200,7 +90804,7 @@ ${lanes.join("\n")} function modifierVisitor(node) { if (isDecorator(node)) return void 0; - if (modifierToFlag(node.kind) & 117086 /* TypeScriptModifier */) { + if (modifierToFlag(node.kind) & 28895 /* TypeScriptModifier */) { return void 0; } else if (currentNamespace && node.kind === 95 /* ExportKeyword */) { return void 0; @@ -90208,7 +90812,7 @@ ${lanes.join("\n")} return node; } function visitTypeScript(node) { - if (isStatement(node) && hasSyntacticModifier(node, 2 /* Ambient */)) { + if (isStatement(node) && hasSyntacticModifier(node, 128 /* Ambient */)) { return factory2.createNotEmittedStatement(node); } switch (node.kind) { @@ -90698,7 +91302,7 @@ ${lanes.join("\n")} return !nodeIsMissing(node.body); } function visitPropertyDeclaration(node, parent2) { - const isAmbient = node.flags & 33554432 /* Ambient */ || hasSyntacticModifier(node, 256 /* Abstract */); + const isAmbient = node.flags & 33554432 /* Ambient */ || hasSyntacticModifier(node, 64 /* Abstract */); if (isAmbient && !(legacyDecorators && hasDecorators(node))) { return void 0; } @@ -90707,7 +91311,7 @@ ${lanes.join("\n")} if (isAmbient) { return factory2.updatePropertyDeclaration( node, - concatenate(modifiers, factory2.createModifiersFromModifierFlags(2 /* Ambient */)), + concatenate(modifiers, factory2.createModifiersFromModifierFlags(128 /* Ambient */)), Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), /*questionOrExclamationToken*/ void 0, @@ -90870,7 +91474,7 @@ ${lanes.join("\n")} ); } function shouldEmitAccessorDeclaration(node) { - return !(nodeIsMissing(node.body) && hasSyntacticModifier(node, 256 /* Abstract */)); + return !(nodeIsMissing(node.body) && hasSyntacticModifier(node, 64 /* Abstract */)); } function visitGetAccessor(node, parent2) { if (!(node.transformFlags & 1 /* ContainsTypeScript */)) { @@ -91469,7 +92073,7 @@ ${lanes.join("\n")} void 0, importClause, node.moduleSpecifier, - node.assertClause + node.attributes ) : void 0; } function visitImportClause(node) { @@ -91519,7 +92123,7 @@ ${lanes.join("\n")} node.isTypeOnly, exportClause, node.moduleSpecifier, - node.assertClause + node.attributes ) : void 0; } function visitNamedExports(node, allowEmpty) { @@ -91553,7 +92157,7 @@ ${lanes.join("\n")} /*importClause*/ void 0, node.moduleReference.expression, - /*assertClause*/ + /*attributes*/ void 0 ), node @@ -91603,16 +92207,16 @@ ${lanes.join("\n")} } } function isExportOfNamespace(node) { - return currentNamespace !== void 0 && hasSyntacticModifier(node, 1 /* Export */); + return currentNamespace !== void 0 && hasSyntacticModifier(node, 32 /* Export */); } function isExternalModuleExport(node) { - return currentNamespace === void 0 && hasSyntacticModifier(node, 1 /* Export */); + return currentNamespace === void 0 && hasSyntacticModifier(node, 32 /* Export */); } function isNamedExternalModuleExport(node) { - return isExternalModuleExport(node) && !hasSyntacticModifier(node, 1024 /* Default */); + return isExternalModuleExport(node) && !hasSyntacticModifier(node, 2048 /* Default */); } function isDefaultExternalModuleExport(node) { - return isExternalModuleExport(node) && hasSyntacticModifier(node, 1024 /* Default */); + return isExternalModuleExport(node) && hasSyntacticModifier(node, 2048 /* Default */); } function createExportMemberAssignmentStatement(node) { const expression = factory2.createAssignment( @@ -92953,8 +93557,8 @@ ${lanes.join("\n")} getClassLexicalEnvironment().classThis = node.emitNode.classThis; } const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */; - const isExport = hasSyntacticModifier(node, 1 /* Export */); - const isDefault = hasSyntacticModifier(node, 1024 /* Default */); + const isExport = hasSyntacticModifier(node, 32 /* Export */); + const isDefault = hasSyntacticModifier(node, 2048 /* Default */); let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const heritageClauses = visitNodes2(node.heritageClauses, heritageClauseVisitor, isHeritageClause); const { members, prologue } = transformClassMembers(node); @@ -93500,7 +94104,7 @@ ${lanes.join("\n")} return void 0; } const propertyOriginalNode = getOriginalNode(property); - if (hasSyntacticModifier(propertyOriginalNode, 256 /* Abstract */)) { + if (hasSyntacticModifier(propertyOriginalNode, 64 /* Abstract */)) { return void 0; } let initializer = visitNode(property.initializer, visitor, isExpression); @@ -94513,16 +95117,19 @@ ${lanes.join("\n")} true ); if (hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node)) { - members = setTextRange(factory2.createNodeArray([ - ...members, - factory2.createClassStaticBlockDeclaration( - factory2.createBlock( - decorationStatements, - /*multiLine*/ - true + members = setTextRange( + factory2.createNodeArray([ + ...members, + factory2.createClassStaticBlockDeclaration( + factory2.createBlock( + decorationStatements, + /*multiLine*/ + true + ) ) - ) - ]), members); + ]), + members + ); decorationStatements = void 0; } return { decorationStatements, members }; @@ -94545,8 +95152,8 @@ ${lanes.join("\n")} return addRange([updated], decorationStatements); } function transformClassDeclarationWithClassDecorators(node, name) { - const isExport = hasSyntacticModifier(node, 1 /* Export */); - const isDefault = hasSyntacticModifier(node, 1024 /* Default */); + const isExport = hasSyntacticModifier(node, 32 /* Export */); + const isDefault = hasSyntacticModifier(node, 2048 /* Default */); const modifiers = visitNodes2(node.modifiers, (node2) => isExportOrDefaultModifier(node2) || isDecorator(node2) ? void 0 : node2, isModifierLike); const location = moveRangePastModifiers(node); const classAlias = getClassAliasIfNeeded(node); @@ -94567,18 +95174,21 @@ ${lanes.join("\n")} let members = visitNodes2(node.members, visitor, isClassElement); let decorationStatements = []; ({ members, decorationStatements } = transformDecoratorsOfClassElements(node, members)); - const assignClassAliasInStaticBlock = languageVersion >= 9 /* ES2022 */ && !!classAlias && some(members, (member) => isPropertyDeclaration(member) && hasSyntacticModifier(member, 32 /* Static */) || isClassStaticBlockDeclaration(member)); + const assignClassAliasInStaticBlock = languageVersion >= 9 /* ES2022 */ && !!classAlias && some(members, (member) => isPropertyDeclaration(member) && hasSyntacticModifier(member, 256 /* Static */) || isClassStaticBlockDeclaration(member)); if (assignClassAliasInStaticBlock) { - members = setTextRange(factory2.createNodeArray([ - factory2.createClassStaticBlockDeclaration( - factory2.createBlock([ - factory2.createExpressionStatement( - factory2.createAssignment(classAlias, factory2.createThis()) - ) - ]) - ), - ...members - ]), members); + members = setTextRange( + factory2.createNodeArray([ + factory2.createClassStaticBlockDeclaration( + factory2.createBlock([ + factory2.createExpressionStatement( + factory2.createAssignment(classAlias, factory2.createThis()) + ) + ]) + ), + ...members + ]), + members + ); } const classExpression = factory2.createClassExpression( modifiers, @@ -94650,55 +95260,67 @@ ${lanes.join("\n")} return updated; } function visitMethodDeclaration(node) { - return finishClassElement(factory2.updateMethodDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - node.asteriskToken, - Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), - /*questionToken*/ - void 0, - /*typeParameters*/ - void 0, - visitNodes2(node.parameters, visitor, isParameter), - /*type*/ - void 0, - visitNode(node.body, visitor, isBlock) - ), node); + return finishClassElement( + factory2.updateMethodDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + node.asteriskToken, + Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), + /*questionToken*/ + void 0, + /*typeParameters*/ + void 0, + visitNodes2(node.parameters, visitor, isParameter), + /*type*/ + void 0, + visitNode(node.body, visitor, isBlock) + ), + node + ); } function visitGetAccessorDeclaration(node) { - return finishClassElement(factory2.updateGetAccessorDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), - visitNodes2(node.parameters, visitor, isParameter), - /*type*/ - void 0, - visitNode(node.body, visitor, isBlock) - ), node); + return finishClassElement( + factory2.updateGetAccessorDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), + visitNodes2(node.parameters, visitor, isParameter), + /*type*/ + void 0, + visitNode(node.body, visitor, isBlock) + ), + node + ); } function visitSetAccessorDeclaration(node) { - return finishClassElement(factory2.updateSetAccessorDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), - visitNodes2(node.parameters, visitor, isParameter), - visitNode(node.body, visitor, isBlock) - ), node); + return finishClassElement( + factory2.updateSetAccessorDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), + visitNodes2(node.parameters, visitor, isParameter), + visitNode(node.body, visitor, isBlock) + ), + node + ); } function visitPropertyDeclaration(node) { - if (node.flags & 33554432 /* Ambient */ || hasSyntacticModifier(node, 2 /* Ambient */)) { + if (node.flags & 33554432 /* Ambient */ || hasSyntacticModifier(node, 128 /* Ambient */)) { return void 0; } - return finishClassElement(factory2.updatePropertyDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - visitNode(node.initializer, visitor, isExpression) - ), node); + return finishClassElement( + factory2.updatePropertyDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), + /*questionOrExclamationToken*/ + void 0, + /*type*/ + void 0, + visitNode(node.initializer, visitor, isExpression) + ), + node + ); } function visitParameterDeclaration(node) { const updated = factory2.updateParameterDeclaration( @@ -94771,7 +95393,7 @@ ${lanes.join("\n")} const memberName = getExpressionForPropertyName( member, /*generateNameForComputedPropertyName*/ - !hasSyntacticModifier(member, 2 /* Ambient */) + !hasSyntacticModifier(member, 128 /* Ambient */) ); const descriptor = languageVersion > 0 /* ES3 */ ? isPropertyDeclaration(member) && !hasAccessorModifier(member) ? factory2.createVoidZero() : factory2.createNull() : void 0; const helper = emitHelpers().createDecorateHelper( @@ -95287,7 +95909,10 @@ ${lanes.join("\n")} classInfo2.classDescriptorName = factory2.createUniqueName("_classDescriptor", 16 /* Optimistic */ | 32 /* FileLevel */); classInfo2.classExtraInitializersName = factory2.createUniqueName("_classExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */); const needsUniqueClassThis = some(node.members, (member) => (isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)); - classInfo2.classThis = factory2.createUniqueName("_classThis", needsUniqueClassThis ? 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */ : 16 /* Optimistic */ | 32 /* FileLevel */); + classInfo2.classThis = factory2.createUniqueName( + "_classThis", + needsUniqueClassThis ? 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */ : 16 /* Optimistic */ | 32 /* FileLevel */ + ); classDefinitionStatements.push( createLet(classInfo2.classDecoratorsName, factory2.createArrayLiteralExpression(classDecorators)), createLet(classInfo2.classDescriptorName), @@ -95557,8 +96182,8 @@ ${lanes.join("\n")} const statements = []; const originalClass = getOriginalNode(node, isClassLike) ?? node; const className = originalClass.name ? factory2.createStringLiteralFromNode(originalClass.name) : factory2.createStringLiteral("default"); - const isExport = hasSyntacticModifier(node, 1 /* Export */); - const isDefault = hasSyntacticModifier(node, 1024 /* Default */); + const isExport = hasSyntacticModifier(node, 32 /* Export */); + const isDefault = hasSyntacticModifier(node, 2048 /* Default */); if (!node.name) { node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, className); } @@ -97706,9 +98331,12 @@ ${lanes.join("\n")} } function visitReturnStatement(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { - return factory2.updateReturnStatement(node, createDownlevelAwait( - node.expression ? visitNode(node.expression, visitor, isExpression) : factory2.createVoidZero() - )); + return factory2.updateReturnStatement( + node, + createDownlevelAwait( + node.expression ? visitNode(node.expression, visitor, isExpression) : factory2.createVoidZero() + ) + ); } return visitEachChild(node, visitor, context); } @@ -97734,7 +98362,10 @@ ${lanes.join("\n")} const target = e.expression; objects.push(visitNode(target, visitor, isExpression)); } else { - chunkObject = append(chunkObject, e.kind === 303 /* PropertyAssignment */ ? factory2.createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression)) : visitNode(e, visitor, isObjectLiteralElementLike)); + chunkObject = append( + chunkObject, + e.kind === 303 /* PropertyAssignment */ ? factory2.createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression)) : visitNode(e, visitor, isObjectLiteralElementLike) + ); } } if (chunkObject) { @@ -97773,13 +98404,16 @@ ${lanes.join("\n")} ); exportedVariableStatement = false; const visited = visitEachChild(node, visitor, context); - const statement = concatenate(visited.statements, taggedTemplateStringDeclarations && [ - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList(taggedTemplateStringDeclarations) - ) - ]); + const statement = concatenate( + visited.statements, + taggedTemplateStringDeclarations && [ + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList(taggedTemplateStringDeclarations) + ) + ] + ); const result = factory2.updateSourceFile(visited, setTextRange(factory2.createNodeArray(statement), node.statements)); exitSubtree(ancestorFacts); return result; @@ -97872,7 +98506,7 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitVariableStatement(node) { - if (hasSyntacticModifier(node, 1 /* Export */)) { + if (hasSyntacticModifier(node, 32 /* Export */)) { const savedExportedVariableStatement = exportedVariableStatement; exportedVariableStatement = true; const visited = visitEachChild(node, visitor, context); @@ -98917,15 +99551,18 @@ ${lanes.join("\n")} right = factory2.createTempVariable(hoistVariableDeclaration); left = factory2.createAssignment(right, left); } - return setTextRange(factory2.createConditionalExpression( - createNotNullCondition(left, right), - /*questionToken*/ - void 0, - right, - /*colonToken*/ - void 0, - visitNode(node.right, visitor, isExpression) - ), node); + return setTextRange( + factory2.createConditionalExpression( + createNotNullCondition(left, right), + /*questionToken*/ + void 0, + right, + /*colonToken*/ + void 0, + visitNode(node.right, visitor, isExpression) + ), + node + ); } function visitDeleteExpression(node) { return isOptionalChain(skipParentheses(node.expression)) ? setOriginalNode(visitNonOptionalExpression( @@ -99091,18 +99728,21 @@ ${lanes.join("\n")} const envBinding = createEnvBinding(); const bodyStatements = transformUsingDeclarations(node.statements, pos, node.statements.length, envBinding, topLevelStatements); if (exportBindings.size) { - append(topLevelStatements, factory2.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory2.createNamedExports(arrayFrom(exportBindings.values())) - )); + append( + topLevelStatements, + factory2.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory2.createNamedExports(arrayFrom(exportBindings.values())) + ) + ); } addRange(topLevelStatements, endLexicalEnvironment()); if (exportVars.length) { topLevelStatements.push(factory2.createVariableStatement( - factory2.createModifiersFromModifierFlags(1 /* Export */), + factory2.createModifiersFromModifierFlags(32 /* Export */), factory2.createVariableDeclarationList( exportVars, 1 /* Let */ @@ -99399,8 +100039,8 @@ ${lanes.join("\n")} if (!node.name && defaultExportBinding) { return node; } - const isExported2 = hasSyntacticModifier(node, 1 /* Export */); - const isDefault = hasSyntacticModifier(node, 1024 /* Default */); + const isExported2 = hasSyntacticModifier(node, 32 /* Export */); + const isDefault = hasSyntacticModifier(node, 2048 /* Default */); let expression = factory2.converters.convertToClassExpression(node); if (node.name) { hoistBindingIdentifier( @@ -99448,7 +100088,7 @@ ${lanes.join("\n")} } function hoistVariableStatement(node) { let expressions; - const isExported2 = hasSyntacticModifier(node, 1 /* Export */); + const isExported2 = hasSyntacticModifier(node, 32 /* Export */); for (const variable of node.declarationList.declarations) { hoistBindingElement(variable, isExported2, variable); if (variable.initializer) { @@ -99755,7 +100395,7 @@ ${lanes.join("\n")} factory2.createNamedImports(arrayFrom(importSpecifiersMap.values())) ), factory2.createStringLiteral(importSource), - /*assertClause*/ + /*attributes*/ void 0 ); setParentRecursive( @@ -99867,7 +100507,9 @@ ${lanes.join("\n")} } } function hasProto(obj) { - return obj.properties.some((p) => isPropertyAssignment(p) && (isIdentifier(p.name) && idText(p.name) === "__proto__" || isStringLiteral(p.name) && p.name.text === "__proto__")); + return obj.properties.some( + (p) => isPropertyAssignment(p) && (isIdentifier(p.name) && idText(p.name) === "__proto__" || isStringLiteral(p.name) && p.name.text === "__proto__") + ); } function hasKeyAfterPropsSpread(node) { let spread = false; @@ -100040,7 +100682,7 @@ ${lanes.join("\n")} } function transformJsxSpreadAttributeToProps(node) { if (isObjectLiteralExpression(node.expression) && !hasProto(node.expression)) { - return node.expression.properties; + return sameMap(node.expression.properties, (p) => Debug.checkDefined(visitNode(p, visitor, isObjectLiteralElementLike))); } return factory2.createSpreadAssignment(Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); } @@ -100621,7 +101263,7 @@ ${lanes.join("\n")} hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -32768 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { - return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0 && node.kind === 253 /* ReturnStatement */ && !node.expression; + return (hierarchyFacts & 8192 /* ConstructorWithSuperCall */) !== 0 && node.kind === 253 /* ReturnStatement */ && !node.expression; } function isOrMayContainReturnCompletion(node) { return node.transformFlags & 4194304 /* ContainsHoistedDeclarationOrCompletion */ && (isReturnStatement(node) || isIfStatement(node) || isWithStatement(node) || isSwitchStatement(node) || isCaseBlock(node) || isCaseClause(node) || isDefaultClause(node) || isTryStatement(node) || isCatchClause(node) || isLabeledStatement(node) || isIterationStatement( @@ -100631,7 +101273,7 @@ ${lanes.join("\n")} ) || isBlock(node)); } function shouldVisitNode(node) { - return (node.transformFlags & 1024 /* ContainsES2015 */) !== 0 || convertedLoopState !== void 0 || hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node) || isIterationStatement( + return (node.transformFlags & 1024 /* ContainsES2015 */) !== 0 || convertedLoopState !== void 0 || hierarchyFacts & 8192 /* ConstructorWithSuperCall */ && isOrMayContainReturnCompletion(node) || isIterationStatement( node, /*lookInLabeledStatements*/ false @@ -100664,7 +101306,7 @@ ${lanes.join("\n")} /*expressionResultIsUnused*/ false ); - exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */); + exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); return result; } return visitorWorker( @@ -100678,6 +101320,7 @@ ${lanes.join("\n")} function callExpressionVisitor(node) { if (node.kind === 108 /* SuperKeyword */) { return visitSuperKeyword( + node, /*isExpressionOfCall*/ true ); @@ -100787,6 +101430,7 @@ ${lanes.join("\n")} return visitSpreadElement(node); case 108 /* SuperKeyword */: return visitSuperKeyword( + node, /*isExpressionOfCall*/ false ); @@ -100856,7 +101500,10 @@ ${lanes.join("\n")} return updated; } function returnCapturedThis(node) { - return setOriginalNode(factory2.createReturnStatement(factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */)), node); + return setOriginalNode(factory2.createReturnStatement(createCapturedThis()), node); + } + function createCapturedThis() { + return factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */); } function visitReturnStatement(node) { if (convertedLoopState) { @@ -100880,8 +101527,9 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitThisKeyword(node) { + hierarchyFacts |= 65536 /* LexicalThis */; if (hierarchyFacts & 2 /* ArrowFunction */ && !(hierarchyFacts & 16384 /* StaticInitializer */)) { - hierarchyFacts |= 65536 /* CapturedLexicalThis */; + hierarchyFacts |= 131072 /* CapturedLexicalThis */; } if (convertedLoopState) { if (hierarchyFacts & 2 /* ArrowFunction */) { @@ -100902,10 +101550,13 @@ ${lanes.join("\n")} } } if (node.flags & 256 /* IdentifierHasExtendedUnicodeEscape */) { - return setOriginalNode(setTextRange( - factory2.createIdentifier(unescapeLeadingUnderscores(node.escapedText)), + return setOriginalNode( + setTextRange( + factory2.createIdentifier(unescapeLeadingUnderscores(node.escapedText)), + node + ), node - ), node); + ); } return node; } @@ -100988,8 +101639,8 @@ ${lanes.join("\n")} setTextRange(statement, node); startOnNewLine(statement); statements.push(statement); - if (hasSyntacticModifier(node, 1 /* Export */)) { - const exportStatement = hasSyntacticModifier(node, 1024 /* Default */) ? factory2.createExportDefault(factory2.getLocalName(node)) : factory2.createExternalModuleExport(factory2.getLocalName(node)); + if (hasSyntacticModifier(node, 32 /* Export */)) { + const exportStatement = hasSyntacticModifier(node, 2048 /* Default */) ? factory2.createExportDefault(factory2.getLocalName(node)) : factory2.createExternalModuleExport(factory2.getLocalName(node)); setOriginalNode(exportStatement, statement); statements.push(exportStatement); } @@ -101017,7 +101668,7 @@ ${lanes.join("\n")} void 0, /*dotDotDotToken*/ void 0, - factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */) + createSyntheticSuper() )] : [], /*type*/ void 0, @@ -101107,7 +101758,7 @@ ${lanes.join("\n")} setEmitFlags(constructorFunction, 16 /* CapturesThis */); } statements.push(constructorFunction); - exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */); + exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; } function transformConstructorParameters(constructor, hasSynthesizedSuper) { @@ -101131,103 +101782,35 @@ ${lanes.join("\n")} setEmitFlags(block, 3072 /* NoComments */); return block; } - function transformConstructorBodyWorker(prologueOut, statementsOut, statementsIn, statementOffset, superPath, superPathDepth, constructor, isDerivedClass, hasSynthesizedSuper, isFirstStatement) { - let mayReplaceThis = false; - const superStatementIndex = superPathDepth < superPath.length ? superPath[superPathDepth] : -1; - const leadingStatementsEnd = superStatementIndex >= 0 ? superStatementIndex : statementsIn.length; - if (isFirstStatement && superStatementIndex >= 0) { - let firstMaterialIndex = statementOffset; - while (isFirstStatement && firstMaterialIndex < superStatementIndex) { - const statement = constructor.body.statements[firstMaterialIndex]; - if (!isUninitializedVariableStatement(statement) && !isUsingDeclarationStateVariableStatement(statement)) - break; - firstMaterialIndex++; - } - isFirstStatement = superStatementIndex === firstMaterialIndex; - } - addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset, leadingStatementsEnd - statementOffset)); - const superStatement = superStatementIndex >= 0 ? statementsIn[superStatementIndex] : void 0; - if (superStatement && isTryStatement(superStatement)) { - const tryBlockStatements = []; - mayReplaceThis = transformConstructorBodyWorker( - prologueOut, - tryBlockStatements, - superStatement.tryBlock.statements, - /*statementOffset*/ - 0, - superPath, - superPathDepth + 1, - constructor, - isDerivedClass, - hasSynthesizedSuper, - isFirstStatement - ); - const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements); - setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); - statementsOut.push(factory2.updateTryStatement( - superStatement, - factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), - visitNode(superStatement.catchClause, visitor, isCatchClause), - visitNode(superStatement.finallyBlock, visitor, isBlock) - )); - } else { - const superCall = superStatement && getSuperCallFromStatement(superStatement); - let superCallExpression; - if (hasSynthesizedSuper) { - superCallExpression = createDefaultSuperCallOrThis(); - hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */; - } else if (superCall) { - superCallExpression = visitSuperCallInBody(superCall); - hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */; - } - if (isDerivedClass || superCallExpression) { - if (superCallExpression && superStatementIndex === statementsIn.length - 1 && !(constructor.body.transformFlags & 16384 /* ContainsLexicalThis */)) { - const superCall2 = cast(cast(superCallExpression, isBinaryExpression).left, isCallExpression); - const returnStatement = factory2.createReturnStatement(superCallExpression); - setCommentRange(returnStatement, getCommentRange(superCall2)); - setEmitFlags(superCall2, 3072 /* NoComments */); - statementsOut.push(returnStatement); - return false; - } else { - if (isFirstStatement) { - insertCaptureThisForNode(statementsOut, constructor, superCallExpression || createActualThis()); - } else { - insertCaptureThisForNode(prologueOut, constructor, createActualThis()); - if (superCallExpression) { - addSuperThisCaptureThisForNode(statementsOut, superCallExpression); - } - } - mayReplaceThis = true; - } - } else { - insertCaptureThisForNodeIfNeeded(prologueOut, constructor); - } - } - if (superStatementIndex >= 0) { - addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex + 1)); - } - return mayReplaceThis; - } function isUninitializedVariableStatement(node) { return isVariableStatement(node) && every(node.declarationList.declarations, (decl) => isIdentifier(decl.name) && !decl.initializer); } - function isUsingDeclarationStateVariableStatement(node) { - if (!isVariableStatement(node) || node.declarationList.declarations.length !== 1) + function containsSuperCall(node) { + if (isSuperCall(node)) { + return true; + } + if (!(node.transformFlags & 134217728 /* ContainsLexicalSuper */)) { return false; - const varDecl = node.declarationList.declarations[0]; - if (!isIdentifier(varDecl.name) || !varDecl.initializer) - return false; - const initializer = varDecl.initializer; - if (!isObjectLiteralExpression(initializer) || initializer.properties.length !== 3) - return false; - const [stackProp, errorProp, hasErrorProp] = initializer.properties; - if (!isPropertyAssignment(stackProp) || !isIdentifier(stackProp.name) || idText(stackProp.name) !== "stack" || !isArrayLiteralExpression(stackProp.initializer)) - return false; - if (!isPropertyAssignment(errorProp) || !isIdentifier(errorProp.name) || idText(errorProp.name) !== "error" || !isVoidExpression(errorProp.initializer) || !isNumericLiteral(errorProp.initializer.expression)) - return false; - if (!isPropertyAssignment(hasErrorProp) || !isIdentifier(hasErrorProp.name) || idText(hasErrorProp.name) !== "hasError" || hasErrorProp.initializer.kind !== 97 /* FalseKeyword */) - return false; - return true; + } + switch (node.kind) { + case 219 /* ArrowFunction */: + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: + case 176 /* Constructor */: + case 175 /* ClassStaticBlockDeclaration */: + return false; + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 174 /* MethodDeclaration */: + case 172 /* PropertyDeclaration */: { + const named = node; + if (isComputedPropertyName(named.name)) { + return !!forEachChild(named.name, containsSuperCall); + } + return false; + } + } + return !!forEachChild(node, containsSuperCall); } function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { const isDerivedClass = !!extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */; @@ -101242,31 +101825,22 @@ ${lanes.join("\n")} /*statementOffset*/ 0 ); - const superStatementIndices = findSuperStatementIndexPath(constructor.body.statements, standardPrologueEnd); - if (hasSynthesizedSuper || superStatementIndices.length > 0) { - hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */; + if (hasSynthesizedSuper || containsSuperCall(constructor.body)) { + hierarchyFacts |= 8192 /* ConstructorWithSuperCall */; } - const mayReplaceThis = transformConstructorBodyWorker( - prologue, - statements, - constructor.body.statements, - standardPrologueEnd, - superStatementIndices, - /*superPathDepth*/ - 0, - constructor, - isDerivedClass, - hasSynthesizedSuper, - /*isFirstStatement*/ - true - // NOTE: this will be recalculated inside of transformConstructorBodyWorker - ); + addRange(statements, visitNodes2(constructor.body.statements, visitor, isStatement, standardPrologueEnd)); + const mayReplaceThis = isDerivedClass || hierarchyFacts & 8192 /* ConstructorWithSuperCall */; addDefaultValueAssignmentsIfNeeded2(prologue, constructor); addRestParameterIfNeeded(prologue, constructor, hasSynthesizedSuper); insertCaptureNewTargetIfNeeded(prologue, constructor); + if (mayReplaceThis) { + insertCaptureThisForNode(prologue, constructor, createActualThis()); + } else { + insertCaptureThisForNodeIfNeeded(prologue, constructor); + } factory2.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); if (mayReplaceThis && !isSufficientlyCoveredByReturnStatements(constructor.body)) { - statements.push(factory2.createReturnStatement(factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */))); + statements.push(factory2.createReturnStatement(createCapturedThis())); } const body = factory2.createBlock( setTextRange( @@ -101283,6 +101857,230 @@ ${lanes.join("\n")} true ); setTextRange(body, constructor.body); + return simplifyConstructor(body, constructor.body, hasSynthesizedSuper); + } + function isCapturedThis(node) { + return isGeneratedIdentifier(node) && idText(node) === "_this"; + } + function isSyntheticSuper(node) { + return isGeneratedIdentifier(node) && idText(node) === "_super"; + } + function isThisCapturingVariableStatement(node) { + return isVariableStatement(node) && node.declarationList.declarations.length === 1 && isThisCapturingVariableDeclaration(node.declarationList.declarations[0]); + } + function isThisCapturingVariableDeclaration(node) { + return isVariableDeclaration(node) && isCapturedThis(node.name) && !!node.initializer; + } + function isThisCapturingAssignment(node) { + return isAssignmentExpression( + node, + /*excludeCompoundAssignment*/ + true + ) && isCapturedThis(node.left); + } + function isTransformedSuperCall(node) { + return isCallExpression(node) && isPropertyAccessExpression(node.expression) && isSyntheticSuper(node.expression.expression) && isIdentifier(node.expression.name) && (idText(node.expression.name) === "call" || idText(node.expression.name) === "apply") && node.arguments.length >= 1 && node.arguments[0].kind === 110 /* ThisKeyword */; + } + function isTransformedSuperCallWithFallback(node) { + return isBinaryExpression(node) && node.operatorToken.kind === 57 /* BarBarToken */ && node.right.kind === 110 /* ThisKeyword */ && isTransformedSuperCall(node.left); + } + function isImplicitSuperCall(node) { + return isBinaryExpression(node) && node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ && isBinaryExpression(node.left) && node.left.operatorToken.kind === 38 /* ExclamationEqualsEqualsToken */ && isSyntheticSuper(node.left.left) && node.left.right.kind === 106 /* NullKeyword */ && isTransformedSuperCall(node.right) && idText(node.right.expression.name) === "apply"; + } + function isImplicitSuperCallWithFallback(node) { + return isBinaryExpression(node) && node.operatorToken.kind === 57 /* BarBarToken */ && node.right.kind === 110 /* ThisKeyword */ && isImplicitSuperCall(node.left); + } + function isThisCapturingTransformedSuperCallWithFallback(node) { + return isThisCapturingAssignment(node) && isTransformedSuperCallWithFallback(node.right); + } + function isThisCapturingImplicitSuperCallWithFallback(node) { + return isThisCapturingAssignment(node) && isImplicitSuperCallWithFallback(node.right); + } + function isTransformedSuperCallLike(node) { + return isTransformedSuperCall(node) || isTransformedSuperCallWithFallback(node) || isThisCapturingTransformedSuperCallWithFallback(node) || isImplicitSuperCall(node) || isImplicitSuperCallWithFallback(node) || isThisCapturingImplicitSuperCallWithFallback(node); + } + function simplifyConstructorInlineSuperInThisCaptureVariable(body) { + for (let i = 0; i < body.statements.length - 1; i++) { + const statement = body.statements[i]; + if (!isThisCapturingVariableStatement(statement)) { + continue; + } + const varDecl = statement.declarationList.declarations[0]; + if (varDecl.initializer.kind !== 110 /* ThisKeyword */) { + continue; + } + const thisCaptureStatementIndex = i; + let superCallIndex = i + 1; + while (superCallIndex < body.statements.length) { + const statement2 = body.statements[superCallIndex]; + if (isExpressionStatement(statement2)) { + if (isTransformedSuperCallLike(skipOuterExpressions(statement2.expression))) { + break; + } + } + if (isUninitializedVariableStatement(statement2)) { + superCallIndex++; + continue; + } + return body; + } + const following = body.statements[superCallIndex]; + let expression = following.expression; + if (isThisCapturingAssignment(expression)) { + expression = expression.right; + } + const newVarDecl = factory2.updateVariableDeclaration( + varDecl, + varDecl.name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + expression + ); + const newDeclList = factory2.updateVariableDeclarationList(statement.declarationList, [newVarDecl]); + const newVarStatement = factory2.createVariableStatement(statement.modifiers, newDeclList); + setOriginalNode(newVarStatement, following); + setTextRange(newVarStatement, following); + const newStatements = factory2.createNodeArray([ + ...body.statements.slice(0, thisCaptureStatementIndex), + // copy statements preceding to `var _this` + ...body.statements.slice(thisCaptureStatementIndex + 1, superCallIndex), + // copy intervening temp variables + newVarStatement, + ...body.statements.slice(superCallIndex + 1) + // copy statements following `super.call(this, ...)` + ]); + setTextRange(newStatements, body.statements); + return factory2.updateBlock(body, newStatements); + } + return body; + } + function simplifyConstructorInlineSuperReturn(body, original) { + for (const statement of original.statements) { + if (statement.transformFlags & 134217728 /* ContainsLexicalSuper */ && !getSuperCallFromStatement(statement)) { + return body; + } + } + const canElideThisCapturingVariable = !(original.transformFlags & 16384 /* ContainsLexicalThis */) && !(hierarchyFacts & 65536 /* LexicalThis */) && !(hierarchyFacts & 131072 /* CapturedLexicalThis */); + for (let i = body.statements.length - 1; i > 0; i--) { + const statement = body.statements[i]; + if (isReturnStatement(statement) && statement.expression && isCapturedThis(statement.expression)) { + const preceding = body.statements[i - 1]; + let expression; + if (isExpressionStatement(preceding) && isThisCapturingTransformedSuperCallWithFallback(skipOuterExpressions(preceding.expression))) { + expression = preceding.expression; + } else if (canElideThisCapturingVariable && isThisCapturingVariableStatement(preceding)) { + const varDecl = preceding.declarationList.declarations[0]; + if (isTransformedSuperCallLike(skipOuterExpressions(varDecl.initializer))) { + expression = factory2.createAssignment( + createCapturedThis(), + varDecl.initializer + ); + } + } + if (!expression) { + break; + } + const newReturnStatement = factory2.createReturnStatement(expression); + setOriginalNode(newReturnStatement, preceding); + setTextRange(newReturnStatement, preceding); + const newStatements = factory2.createNodeArray([ + ...body.statements.slice(0, i - 1), + // copy all statements preceding `_super.call(this, ...)` + newReturnStatement, + ...body.statements.slice(i + 1) + // copy all statements following `return _this;` + ]); + setTextRange(newStatements, body.statements); + return factory2.updateBlock(body, newStatements); + } + } + return body; + } + function elideUnusedThisCaptureWorker(node) { + if (isThisCapturingVariableStatement(node)) { + const varDecl = node.declarationList.declarations[0]; + if (varDecl.initializer.kind === 110 /* ThisKeyword */) { + return void 0; + } + } else if (isThisCapturingAssignment(node)) { + return factory2.createPartiallyEmittedExpression(node.right, node); + } + switch (node.kind) { + case 219 /* ArrowFunction */: + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: + case 176 /* Constructor */: + case 175 /* ClassStaticBlockDeclaration */: + return node; + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 174 /* MethodDeclaration */: + case 172 /* PropertyDeclaration */: { + const named = node; + if (isComputedPropertyName(named.name)) { + return factory2.replacePropertyName(named, visitEachChild(named.name, elideUnusedThisCaptureWorker, nullTransformationContext)); + } + return node; + } + } + return visitEachChild(node, elideUnusedThisCaptureWorker, nullTransformationContext); + } + function simplifyConstructorElideUnusedThisCapture(body, original) { + if (original.transformFlags & 16384 /* ContainsLexicalThis */ || hierarchyFacts & 65536 /* LexicalThis */ || hierarchyFacts & 131072 /* CapturedLexicalThis */) { + return body; + } + for (const statement of original.statements) { + if (statement.transformFlags & 134217728 /* ContainsLexicalSuper */ && !getSuperCallFromStatement(statement)) { + return body; + } + } + return factory2.updateBlock(body, visitNodes2(body.statements, elideUnusedThisCaptureWorker, isStatement)); + } + function injectSuperPresenceCheckWorker(node) { + if (isTransformedSuperCall(node) && node.arguments.length === 2 && isIdentifier(node.arguments[1]) && idText(node.arguments[1]) === "arguments") { + return factory2.createLogicalAnd( + factory2.createStrictInequality( + createSyntheticSuper(), + factory2.createNull() + ), + node + ); + } + switch (node.kind) { + case 219 /* ArrowFunction */: + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: + case 176 /* Constructor */: + case 175 /* ClassStaticBlockDeclaration */: + return node; + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 174 /* MethodDeclaration */: + case 172 /* PropertyDeclaration */: { + const named = node; + if (isComputedPropertyName(named.name)) { + return factory2.replacePropertyName(named, visitEachChild(named.name, injectSuperPresenceCheckWorker, nullTransformationContext)); + } + return node; + } + } + return visitEachChild(node, injectSuperPresenceCheckWorker, nullTransformationContext); + } + function complicateConstructorInjectSuperPresenceCheck(body) { + return factory2.updateBlock(body, visitNodes2(body.statements, injectSuperPresenceCheckWorker, isStatement)); + } + function simplifyConstructor(body, original, hasSynthesizedSuper) { + const inputBody = body; + body = simplifyConstructorInlineSuperInThisCaptureVariable(body); + body = simplifyConstructorInlineSuperReturn(body, original); + if (body !== inputBody) { + body = simplifyConstructorElideUnusedThisCapture(body, original); + } + if (hasSynthesizedSuper) { + body = complicateConstructorInjectSuperPresenceCheck(body); + } return body; } function isSufficientlyCoveredByReturnStatements(statement) { @@ -101308,11 +102106,11 @@ ${lanes.join("\n")} return factory2.createLogicalOr( factory2.createLogicalAnd( factory2.createStrictInequality( - factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), + createSyntheticSuper(), factory2.createNull() ), factory2.createFunctionApplyCall( - factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), + createSyntheticSuper(), createActualThis(), factory2.createIdentifier("arguments") ) @@ -101567,24 +102365,12 @@ ${lanes.join("\n")} return true; } function insertCaptureThisForNodeIfNeeded(statements, node) { - if (hierarchyFacts & 65536 /* CapturedLexicalThis */ && node.kind !== 219 /* ArrowFunction */) { + if (hierarchyFacts & 131072 /* CapturedLexicalThis */ && node.kind !== 219 /* ArrowFunction */) { insertCaptureThisForNode(statements, node, factory2.createThis()); return true; } return false; } - function addSuperThisCaptureThisForNode(statements, superExpression) { - enableSubstitutionsForCapturedThis(); - const assignSuperExpression = factory2.createExpressionStatement( - factory2.createBinaryExpression( - factory2.createThis(), - 64 /* EqualsToken */, - superExpression - ) - ); - statements.push(assignSuperExpression); - setCommentRange(assignSuperExpression, getOriginalNode(superExpression).parent); - } function insertCaptureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); const captureThisStatement = factory2.createVariableStatement( @@ -101592,7 +102378,7 @@ ${lanes.join("\n")} void 0, factory2.createVariableDeclarationList([ factory2.createVariableDeclaration( - factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), + createCapturedThis(), /*exclamationToken*/ void 0, /*type*/ @@ -101813,7 +102599,7 @@ ${lanes.join("\n")} } function visitArrowFunction(node) { if (node.transformFlags & 16384 /* ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* StaticInitializer */)) { - hierarchyFacts |= 65536 /* CapturedLexicalThis */; + hierarchyFacts |= 131072 /* CapturedLexicalThis */; } const savedConvertedLoopState = convertedLoopState; convertedLoopState = void 0; @@ -101846,7 +102632,7 @@ ${lanes.join("\n")} const parameters = visitParameterList(node.parameters, visitor, context); const body = transformFunctionBody2(node); const name = hierarchyFacts & 32768 /* NewTarget */ ? factory2.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */); + exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return factory2.updateFunctionExpression( node, @@ -101869,7 +102655,7 @@ ${lanes.join("\n")} const parameters = visitParameterList(node.parameters, visitor, context); const body = transformFunctionBody2(node); const name = hierarchyFacts & 32768 /* NewTarget */ ? factory2.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */); + exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return factory2.updateFunctionDeclaration( node, @@ -101893,7 +102679,7 @@ ${lanes.join("\n")} if (hierarchyFacts & 32768 /* NewTarget */ && !name && (node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */)) { name = factory2.getGeneratedNameForNode(node); } - exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */); + exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return setOriginalNode( setTextRange( @@ -102046,7 +102832,7 @@ ${lanes.join("\n")} return node.declarationList.declarations.length === 1 && !!node.declarationList.declarations[0].initializer && !!(getInternalEmitFlags(node.declarationList.declarations[0].initializer) & 1 /* TypeScriptClassWrapper */); } function visitVariableStatement(node) { - const ancestorFacts = enterSubtree(0 /* None */, hasSyntacticModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */); + const ancestorFacts = enterSubtree(0 /* None */, hasSyntacticModifier(node, 32 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */); let updated; if (convertedLoopState && (node.declarationList.flags & 7 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) { let assignments; @@ -102084,7 +102870,11 @@ ${lanes.join("\n")} if (node.flags & 7 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } - const declarations = visitNodes2(node.declarations, node.flags & 1 /* Let */ ? visitVariableDeclarationInLetDeclarationList : visitVariableDeclaration, isVariableDeclaration); + const declarations = visitNodes2( + node.declarations, + node.flags & 1 /* Let */ ? visitVariableDeclarationInLetDeclarationList : visitVariableDeclaration, + isVariableDeclaration + ); const declarationList = factory2.createVariableDeclarationList(declarations); setOriginalNode(declarationList, node); setTextRange(declarationList, node); @@ -103298,7 +104088,7 @@ ${lanes.join("\n")} } else { updated = factory2.updateSetAccessorDeclaration(node, node.modifiers, node.name, parameters, body); } - exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */); + exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return updated; } @@ -103448,13 +104238,6 @@ ${lanes.join("\n")} ) ); } - function visitSuperCallInBody(node) { - return visitCallExpressionWithPotentialCapturedThisAssignment( - node, - /*assignToCapturedThis*/ - false - ); - } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { if (node.transformFlags & 32768 /* ContainsRestOrSpread */ || node.expression.kind === 108 /* SuperKeyword */ || isSuperProperty(skipOuterExpressions(node.expression))) { const { target, thisArg } = factory2.createCallBinding(node.expression, hoistVariableDeclaration); @@ -103491,10 +104274,13 @@ ${lanes.join("\n")} resultingCall, createActualThis() ); - resultingCall = assignToCapturedThis ? factory2.createAssignment(factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), initializer) : initializer; + resultingCall = assignToCapturedThis ? factory2.createAssignment(createCapturedThis(), initializer) : initializer; } return setOriginalNode(resultingCall, node); } + if (isSuperCall(node)) { + hierarchyFacts |= 131072 /* CapturedLexicalThis */; + } return visitEachChild(node, visitor, context); } function visitNewExpression(node) { @@ -103527,11 +104313,7 @@ ${lanes.join("\n")} // As we visit each element, we return one of two functions to use as the "key": // - `visitSpanOfSpreads` for one or more contiguous `...` spread expressions, i.e. `...a, ...b` in `[1, 2, ...a, ...b]` // - `visitSpanOfNonSpreads` for one or more contiguous non-spread elements, i.e. `1, 2`, in `[1, 2, ...a, ...b]` - spanMap( - elements, - partitionSpread, - (partition, visitPartition, _start, end) => visitPartition(partition, multiLine, hasTrailingComma && end === numElements) - ) + spanMap(elements, partitionSpread, (partition, visitPartition, _start, end) => visitPartition(partition, multiLine, hasTrailingComma && end === numElements)) ); if (segments.length === 1) { const firstSegment = segments[0]; @@ -103625,8 +104407,15 @@ ${lanes.join("\n")} } return setTextRange(expression, node); } - function visitSuperKeyword(isExpressionOfCall) { - return hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? factory2.createPropertyAccessExpression(factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), "prototype") : factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */); + function createSyntheticSuper() { + return factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */); + } + function visitSuperKeyword(node, isExpressionOfCall) { + const expression = hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? factory2.createPropertyAccessExpression(setOriginalNode(createSyntheticSuper(), node), "prototype") : createSyntheticSuper(); + setOriginalNode(expression, node); + setCommentRange(expression, node); + setSourceMapRange(expression, node); + return expression; } function visitMetaProperty(node) { if (node.keywordToken === 105 /* NewKeyword */ && node.name.escapedText === "target") { @@ -103732,7 +104521,7 @@ ${lanes.join("\n")} } function substituteThisKeyword(node) { if (enabledSubstitutions & 1 /* CapturedThis */ && hierarchyFacts & 16 /* CapturesThis */) { - return setTextRange(factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), node); + return setTextRange(createCapturedThis(), node); } return node; } @@ -104195,11 +104984,7 @@ ${lanes.join("\n")} ); break; case 212 /* ElementAccessExpression */: - target = factory2.updateElementAccessExpression( - left, - cacheExpression(Debug.checkDefined(visitNode(left.expression, visitor, isLeftHandSideExpression))), - cacheExpression(Debug.checkDefined(visitNode(left.argumentExpression, visitor, isExpression))) - ); + target = factory2.updateElementAccessExpression(left, cacheExpression(Debug.checkDefined(visitNode(left.expression, visitor, isLeftHandSideExpression))), cacheExpression(Debug.checkDefined(visitNode(left.argumentExpression, visitor, isExpression)))); break; default: target = Debug.checkDefined(visitNode(left, visitor, isExpression)); @@ -104234,12 +105019,7 @@ ${lanes.join("\n")} } else if (node.operatorToken.kind === 28 /* CommaToken */) { return visitCommaExpression(node); } - return factory2.updateBinaryExpression( - node, - cacheExpression(Debug.checkDefined(visitNode(node.left, visitor, isExpression))), - node.operatorToken, - Debug.checkDefined(visitNode(node.right, visitor, isExpression)) - ); + return factory2.updateBinaryExpression(node, cacheExpression(Debug.checkDefined(visitNode(node.left, visitor, isExpression))), node.operatorToken, Debug.checkDefined(visitNode(node.right, visitor, isExpression))); } return visitEachChild(node, visitor, context); } @@ -104447,11 +105227,7 @@ ${lanes.join("\n")} } function visitElementAccessExpression(node) { if (containsYield(node.argumentExpression)) { - return factory2.updateElementAccessExpression( - node, - cacheExpression(Debug.checkDefined(visitNode(node.expression, visitor, isLeftHandSideExpression))), - Debug.checkDefined(visitNode(node.argumentExpression, visitor, isExpression)) - ); + return factory2.updateElementAccessExpression(node, cacheExpression(Debug.checkDefined(visitNode(node.expression, visitor, isLeftHandSideExpression))), Debug.checkDefined(visitNode(node.argumentExpression, visitor, isExpression))); } return visitEachChild(node, visitor, context); } @@ -104809,12 +105585,7 @@ ${lanes.join("\n")} for (const variable of initializer.declarations) { hoistVariableDeclaration(variable.name); } - node = factory2.updateForInStatement( - node, - initializer.declarations[0].name, - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory2.liftToBlock)) - ); + node = factory2.updateForInStatement(node, initializer.declarations[0].name, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory2.liftToBlock))); } else { node = visitEachChild(node, visitor, context); } @@ -105981,12 +106752,14 @@ ${lanes.join("\n")} // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - factory2.createArrayLiteralExpression(jsonSourceFile ? emptyArray : [ - factory2.createStringLiteral("require"), - factory2.createStringLiteral("exports"), - ...aliasedModuleNames, - ...unaliasedModuleNames - ]), + factory2.createArrayLiteralExpression( + jsonSourceFile ? emptyArray : [ + factory2.createStringLiteral("require"), + factory2.createStringLiteral("exports"), + ...aliasedModuleNames, + ...unaliasedModuleNames + ] + ), // Add the module body function argument: // // function (require, exports, module1, module2) ... @@ -106712,22 +107485,25 @@ ${lanes.join("\n")} ); } else { const temp = factory2.createTempVariable(hoistVariableDeclaration); - return factory2.createComma(factory2.createAssignment(temp, arg), factory2.createConditionalExpression( - /*condition*/ - factory2.createIdentifier("__syncRequire"), - /*questionToken*/ - void 0, - /*whenTrue*/ - createImportCallExpressionCommonJS( - temp, - /*isInlineable*/ - true - ), - /*colonToken*/ - void 0, - /*whenFalse*/ - createImportCallExpressionAMD(temp, containsLexicalThis) - )); + return factory2.createComma( + factory2.createAssignment(temp, arg), + factory2.createConditionalExpression( + /*condition*/ + factory2.createIdentifier("__syncRequire"), + /*questionToken*/ + void 0, + /*whenTrue*/ + createImportCallExpressionCommonJS( + temp, + /*isInlineable*/ + true + ), + /*colonToken*/ + void 0, + /*whenFalse*/ + createImportCallExpressionAMD(temp, containsLexicalThis) + ) + ); } } function createImportCallExpressionAMD(arg, containsLexicalThis) { @@ -107023,7 +107799,7 @@ ${lanes.join("\n")} Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); let statements; if (moduleKind !== 2 /* AMD */) { - if (hasSyntacticModifier(node, 1 /* Export */)) { + if (hasSyntacticModifier(node, 32 /* Export */)) { statements = append( statements, setOriginalNode( @@ -107069,7 +107845,7 @@ ${lanes.join("\n")} ); } } else { - if (hasSyntacticModifier(node, 1 /* Export */)) { + if (hasSyntacticModifier(node, 32 /* Export */)) { statements = append( statements, setOriginalNode( @@ -107168,7 +107944,10 @@ ${lanes.join("\n")} factory2.createExpressionStatement( createExportExpression( factory2.cloneNode(node.exportClause.name), - getHelperExpressionForExport(node, moduleKind !== 2 /* AMD */ ? createRequireCall2(node) : isExportNamespaceAsDefaultDeclaration(node) ? generatedName : factory2.createIdentifier(idText(node.exportClause.name))) + getHelperExpressionForExport( + node, + moduleKind !== 2 /* AMD */ ? createRequireCall2(node) : isExportNamespaceAsDefaultDeclaration(node) ? generatedName : factory2.createIdentifier(idText(node.exportClause.name)) + ) ) ), node @@ -107204,7 +107983,7 @@ ${lanes.join("\n")} } function visitFunctionDeclaration(node) { let statements; - if (hasSyntacticModifier(node, 1 /* Export */)) { + if (hasSyntacticModifier(node, 32 /* Export */)) { statements = append( statements, setOriginalNode( @@ -107241,7 +108020,7 @@ ${lanes.join("\n")} } function visitClassDeclaration(node) { let statements; - if (hasSyntacticModifier(node, 1 /* Export */)) { + if (hasSyntacticModifier(node, 32 /* Export */)) { statements = append( statements, setOriginalNode( @@ -107275,7 +108054,7 @@ ${lanes.join("\n")} let statements; let variables; let expressions; - if (hasSyntacticModifier(node, 1 /* Export */)) { + if (hasSyntacticModifier(node, 32 /* Export */)) { let modifiers; let removeCommentsOnExpressions = false; for (const variable of node.declarationList.declarations) { @@ -107461,8 +108240,8 @@ ${lanes.join("\n")} return statements; } const seen = new IdentifierNameMap(); - if (hasSyntacticModifier(decl, 1 /* Export */)) { - const exportName = hasSyntacticModifier(decl, 1024 /* Default */) ? factory2.createIdentifier("default") : factory2.getDeclarationName(decl); + if (hasSyntacticModifier(decl, 32 /* Export */)) { + const exportName = hasSyntacticModifier(decl, 2048 /* Default */) ? factory2.createIdentifier("default") : factory2.getDeclarationName(decl); statements = appendExportStatement( statements, seen, @@ -107560,21 +108339,24 @@ ${lanes.join("\n")} factory2.createStringLiteralFromNode(name), factory2.createObjectLiteralExpression([ factory2.createPropertyAssignment("enumerable", factory2.createTrue()), - factory2.createPropertyAssignment("get", factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - /*parameters*/ - [], - /*type*/ - void 0, - factory2.createBlock([factory2.createReturnStatement(value)]) - )) + factory2.createPropertyAssignment( + "get", + factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + /*parameters*/ + [], + /*type*/ + void 0, + factory2.createBlock([factory2.createReturnStatement(value)]) + ) + ) ]) ] ) : factory2.createAssignment( @@ -107953,13 +108735,10 @@ ${lanes.join("\n")} addRange(statements, hoistedStatements); insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); const exportStarFunction = addExportStarIfNeeded(statements); - const modifiers = node.transformFlags & 2097152 /* ContainsAwait */ ? factory2.createModifiersFromModifierFlags(512 /* Async */) : void 0; + const modifiers = node.transformFlags & 2097152 /* ContainsAwait */ ? factory2.createModifiersFromModifierFlags(1024 /* Async */) : void 0; const moduleObject = factory2.createObjectLiteralExpression( [ - factory2.createPropertyAssignment( - "setters", - createSettersArray(exportStarFunction, dependencyGroups) - ), + factory2.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), factory2.createPropertyAssignment( "execute", factory2.createFunctionExpression( @@ -108158,7 +108937,7 @@ ${lanes.join("\n")} factory2.createAssignment(importVariableName, parameterName) ) ); - if (hasSyntacticModifier(entry, 1 /* Export */)) { + if (hasSyntacticModifier(entry, 32 /* Export */)) { statements.push( factory2.createExpressionStatement( factory2.createCallExpression( @@ -108311,7 +109090,7 @@ ${lanes.join("\n")} ); } function visitFunctionDeclaration(node) { - if (hasSyntacticModifier(node, 1 /* Export */)) { + if (hasSyntacticModifier(node, 32 /* Export */)) { hoistedStatements = append( hoistedStatements, factory2.updateFunctionDeclaration( @@ -108398,7 +109177,7 @@ ${lanes.join("\n")} statements = append(statements, factory2.updateVariableStatement(node, modifiers, declarationList)); } else { let expressions; - const isExportedDeclaration = hasSyntacticModifier(node, 1 /* Export */); + const isExportedDeclaration = hasSyntacticModifier(node, 32 /* Export */); for (const variable of node.declarationList.declarations) { if (variable.initializer) { expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration)); @@ -108534,8 +109313,8 @@ ${lanes.join("\n")} return statements; } let excludeName; - if (hasSyntacticModifier(decl, 1 /* Export */)) { - const exportName = hasSyntacticModifier(decl, 1024 /* Default */) ? factory2.createStringLiteral("default") : decl.name; + if (hasSyntacticModifier(decl, 32 /* Export */)) { + const exportName = hasSyntacticModifier(decl, 2048 /* Default */) ? factory2.createStringLiteral("default") : decl.name; statements = appendExportStatement(statements, exportName, factory2.getLocalName(decl)); excludeName = getTextOfIdentifierOrLiteral(exportName); } @@ -109211,7 +109990,9 @@ ${lanes.join("\n")} ) ]) ), - factory2.createStringLiteral("module") + factory2.createStringLiteral("module"), + /*attributes*/ + void 0 ); const requireHelperName = factory2.createUniqueName("__require", 16 /* Optimistic */ | 32 /* FileLevel */); const requireStatement = factory2.createVariableStatement( @@ -109284,19 +110065,22 @@ ${lanes.join("\n")} return singleOrMany(statements); } function appendExportsOfImportEqualsDeclaration(statements, node) { - if (hasSyntacticModifier(node, 1 /* Export */)) { - statements = append(statements, factory2.createExportDeclaration( - /*modifiers*/ - void 0, - node.isTypeOnly, - factory2.createNamedExports([factory2.createExportSpecifier( - /*isTypeOnly*/ - false, - /*propertyName*/ + if (hasSyntacticModifier(node, 32 /* Export */)) { + statements = append( + statements, + factory2.createExportDeclaration( + /*modifiers*/ void 0, - idText(node.name) - )]) - )); + node.isTypeOnly, + factory2.createNamedExports([factory2.createExportSpecifier( + /*isTypeOnly*/ + false, + /*propertyName*/ + void 0, + idText(node.name) + )]) + ) + ); } return statements; } @@ -109325,7 +110109,7 @@ ${lanes.join("\n")} ) ), node.moduleSpecifier, - node.assertClause + node.attributes ); setOriginalNode(importDecl, node.exportClause); const exportDecl = isExportNamespaceAsDefaultDeclaration(node) ? factory2.createExportDefault(synthName) : factory2.createExportDeclaration( @@ -109503,7 +110287,7 @@ ${lanes.join("\n")} } else if (isConstructSignatureDeclaration(node) || isCallSignatureDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isFunctionDeclaration(node) || isIndexSignatureDeclaration(node)) { return getReturnTypeVisibilityError; } else if (isParameter(node)) { - if (isParameterPropertyDeclaration(node, node.parent) && hasSyntacticModifier(node.parent, 8 /* Private */)) { + if (isParameterPropertyDeclaration(node, node.parent) && hasSyntacticModifier(node.parent, 2 /* Private */)) { return getVariableDeclarationTypeVisibilityError; } return getParameterDeclarationTypeVisibilityError; @@ -109521,7 +110305,7 @@ ${lanes.join("\n")} function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; - } else if (node.kind === 172 /* PropertyDeclaration */ || node.kind === 211 /* PropertyAccessExpression */ || node.kind === 212 /* ElementAccessExpression */ || node.kind === 226 /* BinaryExpression */ || node.kind === 171 /* PropertySignature */ || node.kind === 169 /* Parameter */ && hasSyntacticModifier(node.parent, 8 /* Private */)) { + } else if (node.kind === 172 /* PropertyDeclaration */ || node.kind === 211 /* PropertyAccessExpression */ || node.kind === 212 /* ElementAccessExpression */ || node.kind === 226 /* BinaryExpression */ || node.kind === 171 /* PropertySignature */ || node.kind === 169 /* Parameter */ && hasSyntacticModifier(node.parent, 2 /* Private */)) { if (isStatic(node)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } else if (node.parent.kind === 263 /* ClassDeclaration */ || node.kind === 169 /* Parameter */) { @@ -109731,7 +110515,7 @@ ${lanes.join("\n")} } function hasInternalAnnotation(range, currentSourceFile) { const comment = currentSourceFile.text.substring(range.pos, range.end); - return stringContains(comment, "@internal"); + return comment.includes("@internal"); } function isInternalDeclaration(node, currentSourceFile) { const parseTreeNode = getParseTreeNode(node); @@ -109795,8 +110579,7 @@ ${lanes.join("\n")} trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode, reportNonlocalAugmentation, - reportNonSerializableProperty, - reportImportTypeNodeResolutionModeOverride + reportNonSerializableProperty }; let errorNameNode; let errorFallbackNode; @@ -109825,6 +110608,17 @@ ${lanes.join("\n")} const container = getSourceFileOfNode(node); refs.set(getOriginalNodeId(container), container); } + function trackReferencedAmbientModuleFromImport(node) { + const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(node); + const symbol = moduleSpecifier && resolver.tryFindAmbientModule(moduleSpecifier); + if (symbol == null ? void 0 : symbol.declarations) { + for (const decl of symbol.declarations) { + if (isAmbientModule(decl) && getSourceFileOfNode(decl) !== currentSourceFile) { + trackReferencedAmbientModule(decl, symbol); + } + } + } + } function handleSymbolAccessibilityError(symbolAccessibilityResult) { if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { @@ -109840,20 +110634,9 @@ ${lanes.join("\n")} const errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); if (errorInfo) { if (errorInfo.typeName) { - context.addDiagnostic(createDiagnosticForNode( - symbolAccessibilityResult.errorNode || errorInfo.errorNode, - errorInfo.diagnosticMessage, - getTextOfNode(errorInfo.typeName), - symbolAccessibilityResult.errorSymbolName, - symbolAccessibilityResult.errorModuleName - )); + context.addDiagnostic(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); } else { - context.addDiagnostic(createDiagnosticForNode( - symbolAccessibilityResult.errorNode || errorInfo.errorNode, - errorInfo.diagnosticMessage, - symbolAccessibilityResult.errorSymbolName, - symbolAccessibilityResult.errorModuleName - )); + context.addDiagnostic(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); } return true; } @@ -109890,41 +110673,22 @@ ${lanes.join("\n")} } function reportInaccessibleUniqueSymbolError() { if (errorNameNode || errorFallbackNode) { - context.addDiagnostic(createDiagnosticForNode( - errorNameNode || errorFallbackNode, - Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, - errorDeclarationNameWithFallback(), - "unique symbol" - )); + context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, errorDeclarationNameWithFallback(), "unique symbol")); } } function reportCyclicStructureError() { if (errorNameNode || errorFallbackNode) { - context.addDiagnostic(createDiagnosticForNode( - errorNameNode || errorFallbackNode, - Diagnostics.The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary, - errorDeclarationNameWithFallback() - )); + context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary, errorDeclarationNameWithFallback())); } } function reportInaccessibleThisError() { if (errorNameNode || errorFallbackNode) { - context.addDiagnostic(createDiagnosticForNode( - errorNameNode || errorFallbackNode, - Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, - errorDeclarationNameWithFallback(), - "this" - )); + context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, errorDeclarationNameWithFallback(), "this")); } } function reportLikelyUnsafeImportRequiredError(specifier) { if (errorNameNode || errorFallbackNode) { - context.addDiagnostic(createDiagnosticForNode( - errorNameNode || errorFallbackNode, - Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, - errorDeclarationNameWithFallback(), - specifier - )); + context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, errorDeclarationNameWithFallback(), specifier)); } } function reportTruncationError() { @@ -109950,11 +110714,6 @@ ${lanes.join("\n")} context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized, propertyName)); } } - function reportImportTypeNodeResolutionModeOverride() { - if (!isNightly() && (errorNameNode || errorFallbackNode)) { - context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); - } - } function transformDeclarationsForJS(sourceFile, bundled) { const oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = (s) => s.errorNode && canProduceDiagnostics(s.errorNode) ? createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : { @@ -109974,9 +110733,8 @@ ${lanes.join("\n")} refs = /* @__PURE__ */ new Map(); libs2 = /* @__PURE__ */ new Map(); let hasNoDefaultLib = false; - const bundle = factory2.createBundle(map( - node.sourceFiles, - (sourceFile) => { + const bundle = factory2.createBundle( + map(node.sourceFiles, (sourceFile) => { if (sourceFile.isDeclarationFile) return void 0; hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib; @@ -110034,18 +110792,19 @@ ${lanes.join("\n")} /*libReferences*/ [] ); - } - ), mapDefined(node.prepends, (prepend) => { - if (prepend.kind === 315 /* InputFiles */) { - const sourceFile = createUnparsedSourceFile(prepend, "dts", stripInternal); - hasNoDefaultLib = hasNoDefaultLib || !!sourceFile.hasNoDefaultLib; - collectReferences(sourceFile, refs); - recordTypeReferenceDirectivesIfNecessary(map(sourceFile.typeReferenceDirectives, (ref) => [ref.fileName, ref.resolutionMode])); - collectLibs(sourceFile, libs2); - return sourceFile; - } - return prepend; - })); + }), + mapDefined(node.prepends, (prepend) => { + if (prepend.kind === 315 /* InputFiles */) { + const sourceFile = createUnparsedSourceFile(prepend, "dts", stripInternal); + hasNoDefaultLib = hasNoDefaultLib || !!sourceFile.hasNoDefaultLib; + collectReferences(sourceFile, refs); + recordTypeReferenceDirectivesIfNecessary(map(sourceFile.typeReferenceDirectives, (ref) => [ref.fileName, ref.resolutionMode])); + collectLibs(sourceFile, libs2); + return sourceFile; + } + return prepend; + }) + ); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); bundle.syntheticLibReferences = getLibReferences(); @@ -110214,6 +110973,9 @@ ${lanes.join("\n")} if (elem.kind === 232 /* OmittedExpression */) { return elem; } + if (elem.propertyName && isComputedPropertyName(elem.propertyName) && isEntityNameExpression(elem.propertyName.expression)) { + checkEntityNameVisibility(elem.propertyName.expression, enclosingDeclaration); + } if (elem.propertyName && isIdentifier(elem.propertyName) && isIdentifier(elem.name) && !elem.symbol.isReferenced && !isIdentifierANonContextualKeyword(elem.propertyName)) { return factory2.updateBindingElement( elem, @@ -110269,7 +111031,7 @@ ${lanes.join("\n")} return void 0; } function ensureType(node, type, ignorePrivate) { - if (!ignorePrivate && hasEffectiveModifier(node, 8 /* Private */)) { + if (!ignorePrivate && hasEffectiveModifier(node, 2 /* Private */)) { return; } if (shouldPrintWithInitializer(node)) { @@ -110349,7 +111111,7 @@ ${lanes.join("\n")} } } function updateParamsList(node, params, modifierMask) { - if (hasEffectiveModifier(node, 8 /* Private */)) { + if (hasEffectiveModifier(node, 2 /* Private */)) { return factory2.createNodeArray(); } const newParams = map(params, (p) => ensureParameter(p, modifierMask)); @@ -110394,7 +111156,7 @@ ${lanes.join("\n")} return factory2.createNodeArray(newParams || emptyArray); } function ensureTypeParams(node, params) { - return hasEffectiveModifier(node, 8 /* Private */) ? void 0 : visitNodes2(params, visitDeclarationSubtree, isTypeParameterDeclaration); + return hasEffectiveModifier(node, 2 /* Private */) ? void 0 : visitNodes2(params, visitDeclarationSubtree, isTypeParameterDeclaration); } function isEnclosingDeclaration(node) { return isSourceFile(node) || isTypeAliasDeclaration(node) || isModuleDeclaration(node) || isClassDeclaration(node) || isInterfaceDeclaration(node) || isFunctionLike(node) || isIndexSignatureDeclaration(node) || isMappedTypeNode(node); @@ -110456,30 +111218,42 @@ ${lanes.join("\n")} decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), - getResolutionModeOverrideForClauseInNightly(decl.assertClause) + tryGetResolutionModeOverride(decl.attributes) ); } const visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : void 0; if (!decl.importClause.namedBindings) { - return visibleDefaultBinding && factory2.updateImportDeclaration(decl, decl.modifiers, factory2.updateImportClause( - decl.importClause, - decl.importClause.isTypeOnly, - visibleDefaultBinding, - /*namedBindings*/ - void 0 - ), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return visibleDefaultBinding && factory2.updateImportDeclaration( + decl, + decl.modifiers, + factory2.updateImportClause( + decl.importClause, + decl.importClause.isTypeOnly, + visibleDefaultBinding, + /*namedBindings*/ + void 0 + ), + rewriteModuleSpecifier(decl, decl.moduleSpecifier), + tryGetResolutionModeOverride(decl.attributes) + ); } if (decl.importClause.namedBindings.kind === 274 /* NamespaceImport */) { const namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : ( /*namedBindings*/ void 0 ); - return visibleDefaultBinding || namedBindings ? factory2.updateImportDeclaration(decl, decl.modifiers, factory2.updateImportClause( - decl.importClause, - decl.importClause.isTypeOnly, - visibleDefaultBinding, - namedBindings - ), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : void 0; + return visibleDefaultBinding || namedBindings ? factory2.updateImportDeclaration( + decl, + decl.modifiers, + factory2.updateImportClause( + decl.importClause, + decl.importClause.isTypeOnly, + visibleDefaultBinding, + namedBindings + ), + rewriteModuleSpecifier(decl, decl.moduleSpecifier), + tryGetResolutionModeOverride(decl.attributes) + ) : void 0; } const bindingList = mapDefined(decl.importClause.namedBindings.elements, (b) => resolver.isDeclarationVisible(b) ? b : void 0); if (bindingList && bindingList.length || visibleDefaultBinding) { @@ -110493,7 +111267,7 @@ ${lanes.join("\n")} bindingList && bindingList.length ? factory2.updateNamedImports(decl.importClause.namedBindings, bindingList) : void 0 ), rewriteModuleSpecifier(decl, decl.moduleSpecifier), - getResolutionModeOverrideForClauseInNightly(decl.assertClause) + tryGetResolutionModeOverride(decl.attributes) ); } if (resolver.isImportRequiredByAugmentation(decl)) { @@ -110503,19 +111277,13 @@ ${lanes.join("\n")} /*importClause*/ void 0, rewriteModuleSpecifier(decl, decl.moduleSpecifier), - getResolutionModeOverrideForClauseInNightly(decl.assertClause) + tryGetResolutionModeOverride(decl.attributes) ); } } - function getResolutionModeOverrideForClauseInNightly(assertClause) { - const mode = getResolutionModeOverrideForClause(assertClause); - if (mode !== void 0) { - if (!isNightly()) { - context.addDiagnostic(createDiagnosticForNode(assertClause, Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); - } - return assertClause; - } - return void 0; + function tryGetResolutionModeOverride(node) { + const mode = getResolutionModeOverride(node); + return node && mode !== void 0 ? node : void 0; } function transformAndReplaceLatePaintedStatements(statements) { while (length(lateMarkedStatements)) { @@ -110574,7 +111342,7 @@ ${lanes.join("\n")} const oldWithinObjectLiteralType = suppressNewDiagnosticContexts; let shouldEnterSuppressNewDiagnosticsContextContext = (input.kind === 187 /* TypeLiteral */ || input.kind === 200 /* MappedType */) && input.parent.kind !== 265 /* TypeAliasDeclaration */; if (isMethodDeclaration(input) || isMethodSignature(input)) { - if (hasEffectiveModifier(input, 8 /* Private */)) { + if (hasEffectiveModifier(input, 2 /* Private */)) { if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; return cleanup(factory2.createPropertyDeclaration( @@ -110662,7 +111430,7 @@ ${lanes.join("\n")} input, ensureModifiers(input), input.name, - updateAccessorParamsList(input, hasEffectiveModifier(input, 8 /* Private */)), + updateAccessorParamsList(input, hasEffectiveModifier(input, 2 /* Private */)), ensureType(input, accessorType), /*body*/ void 0 @@ -110679,7 +111447,7 @@ ${lanes.join("\n")} input, ensureModifiers(input), input.name, - updateAccessorParamsList(input, hasEffectiveModifier(input, 8 /* Private */)), + updateAccessorParamsList(input, hasEffectiveModifier(input, 2 /* Private */)), /*body*/ void 0 )); @@ -110798,10 +111566,11 @@ ${lanes.join("\n")} case 205 /* ImportType */: { if (!isLiteralImportTypeNode(input)) return cleanup(input); + trackReferencedAmbientModuleFromImport(input); return cleanup(factory2.updateImportTypeNode( input, factory2.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), - input.assertions, + input.attributes, input.qualifier, visitNodes2(input.typeArguments, visitDeclarationSubtree, isTypeNode), input.isTypeOf @@ -110835,7 +111604,7 @@ ${lanes.join("\n")} } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 174 /* MethodDeclaration */ && hasEffectiveModifier(node.parent, 8 /* Private */); + return node.parent.kind === 174 /* MethodDeclaration */ && hasEffectiveModifier(node.parent, 2 /* Private */); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -110849,13 +111618,14 @@ ${lanes.join("\n")} resultHasExternalModuleIndicator = true; } resultHasScopeMarker = true; + trackReferencedAmbientModuleFromImport(input); return factory2.updateExportDeclaration( input, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), - getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : void 0 + tryGetResolutionModeOverride(input.attributes) ); } case 277 /* ExportAssignment */: { @@ -110893,11 +111663,11 @@ ${lanes.join("\n")} return input; } function stripExportModifiers(statement) { - if (isImportEqualsDeclaration(statement) || hasEffectiveModifier(statement, 1024 /* Default */) || !canHaveModifiers(statement)) { + if (isImportEqualsDeclaration(statement) || hasEffectiveModifier(statement, 2048 /* Default */) || !canHaveModifiers(statement)) { return statement; } - const modifiers = factory2.createModifiersFromModifierFlags(getEffectiveModifierFlags(statement) & (258047 /* All */ ^ 1 /* Export */)); - return factory2.updateModifiers(statement, modifiers); + const modifiers = factory2.createModifiersFromModifierFlags(getEffectiveModifierFlags(statement) & (131071 /* All */ ^ 32 /* Export */)); + return factory2.replaceModifiers(statement, modifiers); } function updateModuleDeclarationAndKeyword(node, modifiers, name, body) { const updated = factory2.updateModuleDeclaration(node, modifiers, name, body); @@ -110923,10 +111693,18 @@ ${lanes.join("\n")} return; switch (input.kind) { case 271 /* ImportEqualsDeclaration */: { - return transformImportEqualsDeclaration(input); + const transformed = transformImportEqualsDeclaration(input); + if (transformed) { + trackReferencedAmbientModuleFromImport(input); + } + return transformed; } case 272 /* ImportDeclaration */: { - return transformImportDeclaration(input); + const transformed = transformImportDeclaration(input); + if (transformed) { + trackReferencedAmbientModuleFromImport(input); + } + return transformed; } } if (isDeclaration(input) && isDeclarationAndNotVisible(input)) @@ -110994,7 +111772,7 @@ ${lanes.join("\n")} fakespace.symbol = props[0].parent; const exportMappings = []; let declarations = mapDefined(props, (p) => { - if (!p.valueDeclaration || !(isPropertyAccessExpression(p.valueDeclaration) || isElementAccessExpression(p.valueDeclaration) || isBinaryExpression(p.valueDeclaration))) { + if (!isExpandoPropertyDeclaration(p.valueDeclaration)) { return void 0; } const nameStr = unescapeLeadingUnderscores(p.escapedName); @@ -111020,7 +111798,7 @@ ${lanes.join("\n")} return factory2.createVariableStatement(isNonContextualKeywordName ? void 0 : [factory2.createToken(95 /* ExportKeyword */)], factory2.createVariableDeclarationList([varDecl])); }); if (!exportMappings.length) { - declarations = mapDefined(declarations, (declaration) => factory2.updateModifiers(declaration, 0 /* None */)); + declarations = mapDefined(declarations, (declaration) => factory2.replaceModifiers(declaration, 0 /* None */)); } else { declarations.push(factory2.createExportDeclaration( /*modifiers*/ @@ -111038,10 +111816,10 @@ ${lanes.join("\n")} )); } const namespaceDecl = factory2.createModuleDeclaration(ensureModifiers(input), input.name, factory2.createModuleBlock(declarations), 32 /* Namespace */); - if (!hasEffectiveModifier(clean2, 1024 /* Default */)) { + if (!hasEffectiveModifier(clean2, 2048 /* Default */)) { return [clean2, namespaceDecl]; } - const modifiers = factory2.createModifiersFromModifierFlags(getEffectiveModifierFlags(clean2) & ~1025 /* ExportDefault */ | 2 /* Ambient */); + const modifiers = factory2.createModifiersFromModifierFlags(getEffectiveModifierFlags(clean2) & ~2080 /* ExportDefault */ | 128 /* Ambient */); const cleanDeclaration = factory2.updateFunctionDeclaration( clean2, modifiers, @@ -111133,17 +111911,20 @@ ${lanes.join("\n")} if (ctor) { const oldDiag2 = getSymbolAccessibilityDiagnostic; parameterProperties = compact(flatMap(ctor.parameters, (param) => { - if (!hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */) || shouldStripInternal(param)) + if (!hasSyntacticModifier(param, 31 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 80 /* Identifier */) { - return preserveJsDoc(factory2.createPropertyDeclaration( - ensureModifiers(param), - param.name, - param.questionToken, - ensureType(param, param.type), - ensureNoInitializer(param) - ), param); + return preserveJsDoc( + factory2.createPropertyDeclaration( + ensureModifiers(param), + param.name, + param.questionToken, + ensureType(param, param.type), + ensureNoInitializer(param) + ), + param + ); } else { return walkBindingPattern(param.name); } @@ -111219,14 +112000,17 @@ ${lanes.join("\n")} } return factory2.updateHeritageClause(clause, visitNodes2(factory2.createNodeArray(filter(clause.types, (t) => isEntityNameExpression(t.expression) || t.expression.kind === 106 /* NullKeyword */)), visitDeclarationSubtree, isExpressionWithTypeArguments)); })); - return [statement, cleanup(factory2.updateClassDeclaration( - input, - modifiers, - input.name, - typeParameters, - heritageClauses, - members - ))]; + return [ + statement, + cleanup(factory2.updateClassDeclaration( + input, + modifiers, + input.name, + typeParameters, + heritageClauses, + members + )) + ]; } else { const heritageClauses = transformHeritageClauses(input.heritageClauses); return cleanup(factory2.updateClassDeclaration( @@ -111243,12 +112027,17 @@ ${lanes.join("\n")} return cleanup(transformVariableStatement(input)); } case 266 /* EnumDeclaration */: { - return cleanup(factory2.updateEnumDeclaration(input, factory2.createNodeArray(ensureModifiers(input)), input.name, factory2.createNodeArray(mapDefined(input.members, (m) => { - if (shouldStripInternal(m)) - return; - const constValue = resolver.getConstantValue(m); - return preserveJsDoc(factory2.updateEnumMember(m, m.name, constValue !== void 0 ? typeof constValue === "string" ? factory2.createStringLiteral(constValue) : factory2.createNumericLiteral(constValue) : void 0), m); - })))); + return cleanup(factory2.updateEnumDeclaration( + input, + factory2.createNodeArray(ensureModifiers(input)), + input.name, + factory2.createNodeArray(mapDefined(input.members, (m) => { + if (shouldStripInternal(m)) + return; + const constValue = resolver.getConstantValue(m); + return preserveJsDoc(factory2.updateEnumMember(m, m.name, constValue !== void 0 ? typeof constValue === "string" ? factory2.createStringLiteral(constValue) : factory2.createNumericLiteral(constValue) : void 0), m); + })) + )); } } return Debug.assertNever(input, `Unhandled top-level node in declaration emit: ${Debug.formatSyntaxKind(input.kind)}`); @@ -111350,11 +112139,11 @@ ${lanes.join("\n")} return factory2.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - let mask2 = 258047 /* All */ ^ (4 /* Public */ | 512 /* Async */ | 16384 /* Override */); - let additions = needsDeclare && !isAlwaysType(node) ? 2 /* Ambient */ : 0 /* None */; + let mask2 = 131071 /* All */ ^ (1 /* Public */ | 1024 /* Async */ | 16 /* Override */); + let additions = needsDeclare && !isAlwaysType(node) ? 128 /* Ambient */ : 0 /* None */; const parentIsFile = node.parent.kind === 312 /* SourceFile */; if (!parentIsFile || isBundledEmit && parentIsFile && isExternalModule(node.parent)) { - mask2 ^= 2 /* Ambient */; + mask2 ^= 128 /* Ambient */; additions = 0 /* None */; } return maskModifierFlags(node, mask2, additions); @@ -111372,9 +112161,19 @@ ${lanes.join("\n")} return accessorType; } function transformHeritageClauses(nodes) { - return factory2.createNodeArray(filter(map(nodes, (clause) => factory2.updateHeritageClause(clause, visitNodes2(factory2.createNodeArray(filter(clause.types, (t) => { - return isEntityNameExpression(t.expression) || clause.token === 96 /* ExtendsKeyword */ && t.expression.kind === 106 /* NullKeyword */; - })), visitDeclarationSubtree, isExpressionWithTypeArguments))), (clause) => clause.types && !!clause.types.length)); + return factory2.createNodeArray(filter( + map(nodes, (clause) => factory2.updateHeritageClause( + clause, + visitNodes2( + factory2.createNodeArray(filter(clause.types, (t) => { + return isEntityNameExpression(t.expression) || clause.token === 96 /* ExtendsKeyword */ && t.expression.kind === 106 /* NullKeyword */; + })), + visitDeclarationSubtree, + isExpressionWithTypeArguments + ) + )), + (clause) => clause.types && !!clause.types.length + )); } } function isAlwaysType(node) { @@ -111386,13 +112185,13 @@ ${lanes.join("\n")} function maskModifiers(factory2, node, modifierMask, modifierAdditions) { return factory2.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } - function maskModifierFlags(node, modifierMask = 258047 /* All */ ^ 4 /* Public */, modifierAdditions = 0 /* None */) { + function maskModifierFlags(node, modifierMask = 131071 /* All */ ^ 1 /* Public */, modifierAdditions = 0 /* None */) { let flags = getEffectiveModifierFlags(node) & modifierMask | modifierAdditions; - if (flags & 1024 /* Default */ && !(flags & 1 /* Export */)) { - flags ^= 1 /* Export */; + if (flags & 2048 /* Default */ && !(flags & 32 /* Export */)) { + flags ^= 32 /* Export */; } - if (flags & 1024 /* Default */ && flags & 2 /* Ambient */) { - flags ^= 2 /* Ambient */; + if (flags & 2048 /* Default */ && flags & 128 /* Ambient */) { + flags ^= 128 /* Ambient */; } return flags; } @@ -111405,7 +112204,7 @@ ${lanes.join("\n")} switch (node.kind) { case 172 /* PropertyDeclaration */: case 171 /* PropertySignature */: - return !hasEffectiveModifier(node, 8 /* Private */); + return !hasEffectiveModifier(node, 2 /* Private */); case 169 /* Parameter */: case 260 /* VariableDeclaration */: return true; @@ -112309,6 +113108,7 @@ ${lanes.join("\n")} inlineSourceMap: compilerOptions.inlineSourceMap, extendedDiagnostics: compilerOptions.extendedDiagnostics, onlyPrintJsDocStyle: true, + omitBraceSourceMapPositions: true, writeBundleFileInfo: !!bundleBuildInfo, recordInternalSection: !!bundleBuildInfo, relativeToBuildInfo @@ -112671,6 +113471,7 @@ ${lanes.join("\n")} onAfterEmitToken } = handlers; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; + var omitBraceSourcePositions = !!printerOptions.omitBraceSourceMapPositions; var newLine = getNewLineCharacter(printerOptions); var moduleKind = getEmitModuleKind(printerOptions); var bundledHelpers = /* @__PURE__ */ new Map(); @@ -113305,10 +114106,10 @@ ${lanes.join("\n")} return emitNamedExports(node); case 281 /* ExportSpecifier */: return emitExportSpecifier(node); - case 300 /* AssertClause */: - return emitAssertClause(node); - case 301 /* AssertEntry */: - return emitAssertEntry(node); + case 300 /* ImportAttributes */: + return emitImportAttributes(node); + case 301 /* ImportAttribute */: + return emitImportAttribute(node); case 282 /* MissingDeclaration */: return; case 283 /* ExternalModuleReference */: @@ -113690,14 +114491,8 @@ ${lanes.join("\n")} nonEscapingWrite(`}`); } function emitTabStop(hint, node, snippet) { - Debug.assert( - node.kind === 242 /* EmptyStatement */, - `A tab stop cannot be attached to a node of kind ${Debug.formatSyntaxKind(node.kind)}.` - ); - Debug.assert( - hint !== 5 /* EmbeddedStatement */, - `A tab stop cannot be attached to an embedded statement.` - ); + Debug.assert(node.kind === 242 /* EmptyStatement */, `A tab stop cannot be attached to a node of kind ${Debug.formatSyntaxKind(node.kind)}.`); + Debug.assert(hint !== 5 /* EmbeddedStatement */, `A tab stop cannot be attached to an embedded statement.`); nonEscapingWrite(`$${snippet.order}`); } function emitIdentifier(node) { @@ -114089,16 +114884,16 @@ ${lanes.join("\n")} writeKeyword("import"); writePunctuation("("); emit(node.argument); - if (node.assertions) { + if (node.attributes) { writePunctuation(","); writeSpace(); writePunctuation("{"); writeSpace(); - writeKeyword("assert"); + writeKeyword(node.attributes.token === 132 /* AssertKeyword */ ? "assert" : "with"); writePunctuation(":"); writeSpace(); - const elements = node.assertions.assertClause.elements; - emitList(node.assertions.assertClause, elements, 526226 /* ImportClauseEntries */); + const elements = node.attributes.elements; + emitList(node.attributes, elements, 526226 /* ImportAttributes */); writeSpace(); writePunctuation("}"); } @@ -114190,7 +114985,7 @@ ${lanes.join("\n")} /*jsxAttributeEscape*/ false ); - return !(expression.numericLiteralFlags & 448 /* WithSpecifier */) && !stringContains(text, tokenToString(25 /* DotToken */)) && !stringContains(text, String.fromCharCode(69 /* E */)) && !stringContains(text, String.fromCharCode(101 /* e */)); + return !(expression.numericLiteralFlags & 448 /* WithSpecifier */) && !text.includes(tokenToString(25 /* DotToken */)) && !text.includes(String.fromCharCode(69 /* E */)) && !text.includes(String.fromCharCode(101 /* e */)); } else if (isAccessExpression(expression)) { const constantValue = getConstantValue(expression); return typeof constantValue === "number" && isFinite(constantValue) && constantValue >= 0 && Math.floor(constantValue) === constantValue; @@ -114672,7 +115467,11 @@ ${lanes.join("\n")} decreaseIndent(); } } - pos = writeTokenText(token, writer2, pos); + if (!omitBraceSourcePositions && (token === 19 /* OpenBraceToken */ || token === 20 /* CloseBraceToken */)) { + pos = writeToken(token, pos, writer2, contextNode); + } else { + pos = writeTokenText(token, writer2, pos); + } if (isSimilarNode && contextNode.end !== pos) { const isJsxExprContext = contextNode.kind === 294 /* JsxExpression */; emitTrailingCommentsOfPosition( @@ -115083,8 +115882,8 @@ ${lanes.join("\n")} writeSpace(); } emitExpression(node.moduleSpecifier); - if (node.assertClause) { - emitWithLeadingSpace(node.assertClause); + if (node.attributes) { + emitWithLeadingSpace(node.attributes); } writeTrailingSemicolon(); } @@ -115122,7 +115921,10 @@ ${lanes.join("\n")} emitTokenWithComment(90 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); - emitExpression(node.expression, node.isExportEquals ? parenthesizer.getParenthesizeRightSideOfBinaryForOperator(64 /* EqualsToken */) : parenthesizer.parenthesizeExpressionOfExportDefault); + emitExpression( + node.expression, + node.isExportEquals ? parenthesizer.getParenthesizeRightSideOfBinaryForOperator(64 /* EqualsToken */) : parenthesizer.parenthesizeExpressionOfExportDefault + ); writeTrailingSemicolon(); } function emitExportDeclaration(node) { @@ -115150,18 +115952,18 @@ ${lanes.join("\n")} writeSpace(); emitExpression(node.moduleSpecifier); } - if (node.assertClause) { - emitWithLeadingSpace(node.assertClause); + if (node.attributes) { + emitWithLeadingSpace(node.attributes); } writeTrailingSemicolon(); } - function emitAssertClause(node) { - emitTokenWithComment(132 /* AssertKeyword */, node.pos, writeKeyword, node); + function emitImportAttributes(node) { + emitTokenWithComment(node.token, node.pos, writeKeyword, node); writeSpace(); const elements = node.elements; - emitList(node, elements, 526226 /* ImportClauseEntries */); + emitList(node, elements, 526226 /* ImportAttributes */); } - function emitAssertEntry(node) { + function emitImportAttribute(node) { emit(node.name); writePunctuation(":"); writeSpace(); @@ -116020,6 +116822,16 @@ ${lanes.join("\n")} increaseIndent(); shouldDecreaseIndentAfterEmit = true; } + if (shouldEmitInterveningComments && format & 60 /* DelimitersMask */ && !positionIsSynthesized(child.pos)) { + const commentRange = getCommentRange(child); + emitTrailingCommentsOfPosition( + commentRange.pos, + /*prefixSpace*/ + !!(format & 512 /* SpaceBetweenSiblings */), + /*forceNoNewline*/ + true + ); + } writeLine(separatingLineTerminatorCount); shouldEmitInterveningComments = false; } else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { @@ -117378,7 +118190,8 @@ ${lanes.join("\n")} getSymbolOfExternalModuleSpecifier: notImplemented, isBindingCapturedByNode: notImplemented, getDeclarationStatementsForSourceFile: notImplemented, - isImportRequiredByAugmentation: notImplemented + isImportRequiredByAugmentation: notImplemented, + tryFindAmbientModule: notImplemented }; createPrinterWithDefaults = /* @__PURE__ */ memoize(() => createPrinter({})); createPrinterWithRemoveComments = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true })); @@ -117714,7 +118527,8 @@ ${lanes.join("\n")} currentDirectory, useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, - toPath: toPath3 + toPath: toPath3, + getScriptKind: getScriptKind2 }) { const newPath = removeIgnoredPath(fileOrDirectoryPath); if (!newPath) { @@ -117724,7 +118538,7 @@ ${lanes.join("\n")} fileOrDirectoryPath = newPath; if (fileOrDirectoryPath === watchedDirPath) return false; - if (hasExtension(fileOrDirectoryPath) && !isSupportedSourceFileName(fileOrDirectory, options, extraFileExtensions)) { + if (hasExtension(fileOrDirectoryPath) && !(isSupportedSourceFileName(fileOrDirectory, options, extraFileExtensions) || isSupportedScriptKind())) { writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); return true; } @@ -117753,6 +118567,25 @@ ${lanes.join("\n")} function hasSourceFile(file) { return realProgram ? !!realProgram.getSourceFileByPath(file) : builderProgram ? builderProgram.getState().fileInfos.has(file) : !!find(program, (rootFile) => toPath3(rootFile) === file); } + function isSupportedScriptKind() { + if (!getScriptKind2) + return false; + const scriptKind = getScriptKind2(fileOrDirectory); + switch (scriptKind) { + case 3 /* TS */: + case 4 /* TSX */: + case 7 /* Deferred */: + case 5 /* External */: + return true; + case 1 /* JS */: + case 2 /* JSX */: + return getAllowJSCompilerOption(options); + case 6 /* JSON */: + return getResolveJsonModule(options); + case 0 /* Unknown */: + return false; + } + } } function isBuilderProgram(program) { return !!program.getState; @@ -117763,7 +118596,7 @@ ${lanes.join("\n")} } return program.isEmittedFile(file); } - function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo) { + function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo2) { setSysLog(watchLogLevel === 2 /* Verbose */ ? log : noop); const plainInvokeFactory = { watchFile: (file, callback, pollingInterval, options) => host.watchFile(file, callback, pollingInterval, options), @@ -117801,23 +118634,23 @@ ${lanes.join("\n")} return typeof host.useCaseSensitiveFileNames === "boolean" ? host.useCaseSensitiveFileNames : host.useCaseSensitiveFileNames(); } function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) { - log(`ExcludeWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); + log(`ExcludeWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); return { - close: () => log(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`) + close: () => log(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`) }; } function createFileWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { - log(`FileWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); + log(`FileWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); const watcher = triggerInvokingFactory.watchFile(file, cb, flags, options, detailInfo1, detailInfo2); return { close: () => { - log(`FileWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); + log(`FileWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); watcher.close(); } }; } function createDirectoryWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { - const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; + const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; log(watchInfo); const start = timestamp(); const watcher = triggerInvokingFactory.watchDirectory(file, cb, flags, options, detailInfo1, detailInfo2); @@ -117825,7 +118658,7 @@ ${lanes.join("\n")} log(`Elapsed:: ${elapsed}ms ${watchInfo}`); return { close: () => { - const watchInfo2 = `DirectoryWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; + const watchInfo2 = `DirectoryWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; log(watchInfo2); const start2 = timestamp(); watcher.close(); @@ -117840,7 +118673,7 @@ ${lanes.join("\n")} void 0, file, (...args) => { - const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; + const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; log(triggerredInfo); const start = timestamp(); cb.call( @@ -117857,8 +118690,8 @@ ${lanes.join("\n")} detailInfo2 ); } - function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2) { - return `WatchInfo: ${file} ${flags} ${JSON.stringify(options)} ${getDetailWatchInfo2 ? getDetailWatchInfo2(detailInfo1, detailInfo2) : detailInfo2 === void 0 ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`; + function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3) { + return `WatchInfo: ${file} ${flags} ${JSON.stringify(options)} ${getDetailWatchInfo3 ? getDetailWatchInfo3(detailInfo1, detailInfo2) : detailInfo2 === void 0 ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`; } } function getFallbackOptions(options) { @@ -117870,17 +118703,17 @@ ${lanes.join("\n")} function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); } - var ConfigFileProgramReloadLevel, WatchLogLevel; + var ProgramUpdateLevel, WatchLogLevel; var init_watchUtilities = __esm({ "src/compiler/watchUtilities.ts"() { "use strict"; init_ts2(); - ConfigFileProgramReloadLevel = /* @__PURE__ */ ((ConfigFileProgramReloadLevel2) => { - ConfigFileProgramReloadLevel2[ConfigFileProgramReloadLevel2["None"] = 0] = "None"; - ConfigFileProgramReloadLevel2[ConfigFileProgramReloadLevel2["Partial"] = 1] = "Partial"; - ConfigFileProgramReloadLevel2[ConfigFileProgramReloadLevel2["Full"] = 2] = "Full"; - return ConfigFileProgramReloadLevel2; - })(ConfigFileProgramReloadLevel || {}); + ProgramUpdateLevel = /* @__PURE__ */ ((ProgramUpdateLevel2) => { + ProgramUpdateLevel2[ProgramUpdateLevel2["Update"] = 0] = "Update"; + ProgramUpdateLevel2[ProgramUpdateLevel2["RootNamesAndUpdate"] = 1] = "RootNamesAndUpdate"; + ProgramUpdateLevel2[ProgramUpdateLevel2["Full"] = 2] = "Full"; + return ProgramUpdateLevel2; + })(ProgramUpdateLevel || {}); WatchLogLevel = /* @__PURE__ */ ((WatchLogLevel2) => { WatchLogLevel2[WatchLogLevel2["None"] = 0] = "None"; WatchLogLevel2[WatchLogLevel2["TriggerOnly"] = 1] = "TriggerOnly"; @@ -118163,7 +118996,7 @@ ${lanes.join("\n")} function formatColorAndReset(text, formatStyle) { return formatStyle + text + resetEscapeSequence; } - function formatCodeSpan(file, start, length2, indent2, squiggleColor, host) { + function formatCodeSpan(file, start, length2, indent3, squiggleColor, host) { const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length2); const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line; @@ -118176,17 +119009,17 @@ ${lanes.join("\n")} for (let i = firstLine; i <= lastLine; i++) { context += host.getNewLine(); if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += indent2 + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context += indent3 + formatColorAndReset(ellipsis.padStart(gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } const lineStart = getPositionOfLineAndCharacter(file, i, 0); const lineEnd = i < lastLineInFile ? getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; let lineContent = file.text.slice(lineStart, lineEnd); - lineContent = trimStringEnd(lineContent); + lineContent = lineContent.trimEnd(); lineContent = lineContent.replace(/\t/g, " "); - context += indent2 + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += indent3 + formatColorAndReset((i + 1 + "").padStart(gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); - context += indent2 + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += indent3 + formatColorAndReset("".padStart(gutterWidth), gutterStyleSequence) + gutterSeparator; context += squiggleColor; if (i === firstLine) { const lastCharForLine = i === lastLine ? lastLineChar : void 0; @@ -118243,24 +119076,24 @@ ${lanes.join("\n")} } return output; } - function flattenDiagnosticMessageText(diag2, newLine, indent2 = 0) { + function flattenDiagnosticMessageText(diag2, newLine, indent3 = 0) { if (isString(diag2)) { return diag2; } else if (diag2 === void 0) { return ""; } let result = ""; - if (indent2) { + if (indent3) { result += newLine; - for (let i = 0; i < indent2; i++) { + for (let i = 0; i < indent3; i++) { result += " "; } } result += diag2.messageText; - indent2++; + indent3++; if (diag2.next) { for (const kid of diag2.next) { - result += flattenDiagnosticMessageText(kid, newLine, indent2); + result += flattenDiagnosticMessageText(kid, newLine, indent3); } } return result; @@ -118269,8 +119102,6 @@ ${lanes.join("\n")} return (isString(ref) ? containingFileMode : ref.resolutionMode) || containingFileMode; } function getModeForResolutionAtIndex(file, index) { - if (file.impliedNodeFormat === void 0) - return void 0; return getModeForUsageLocation(file, getModuleNameStringLiteralAt(file, index)); } function isExclusivelyTypeOnlyImportOrExport(decl) { @@ -118284,42 +119115,48 @@ ${lanes.join("\n")} return false; } function getModeForUsageLocation(file, usage) { - var _a, _b; - if (file.impliedNodeFormat === void 0) - return void 0; + var _a; if (isImportDeclaration(usage.parent) || isExportDeclaration(usage.parent)) { const isTypeOnly = isExclusivelyTypeOnlyImportOrExport(usage.parent); if (isTypeOnly) { - const override = getResolutionModeOverrideForClause(usage.parent.assertClause); + const override = getResolutionModeOverride(usage.parent.attributes); if (override) { return override; } } } if (usage.parent.parent && isImportTypeNode(usage.parent.parent)) { - const override = getResolutionModeOverrideForClause((_a = usage.parent.parent.assertions) == null ? void 0 : _a.assertClause); + const override = getResolutionModeOverride(usage.parent.parent.attributes); if (override) { return override; } } + if (file.impliedNodeFormat === void 0) + return void 0; if (file.impliedNodeFormat !== 99 /* ESNext */) { return isImportCall(walkUpParenthesizedExpressions(usage.parent)) ? 99 /* ESNext */ : 1 /* CommonJS */; } - const exprParentParent = (_b = walkUpParenthesizedExpressions(usage.parent)) == null ? void 0 : _b.parent; + const exprParentParent = (_a = walkUpParenthesizedExpressions(usage.parent)) == null ? void 0 : _a.parent; return exprParentParent && isImportEqualsDeclaration(exprParentParent) ? 1 /* CommonJS */ : 99 /* ESNext */; } - function getResolutionModeOverrideForClause(clause, grammarErrorOnNode) { - if (!clause) + function getResolutionModeOverride(node, grammarErrorOnNode) { + if (!node) return void 0; - if (length(clause.elements) !== 1) { - grammarErrorOnNode == null ? void 0 : grammarErrorOnNode(clause, Diagnostics.Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require); + if (length(node.elements) !== 1) { + grammarErrorOnNode == null ? void 0 : grammarErrorOnNode( + node, + node.token === 118 /* WithKeyword */ ? Diagnostics.Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require : Diagnostics.Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require + ); return void 0; } - const elem = clause.elements[0]; + const elem = node.elements[0]; if (!isStringLiteralLike(elem.name)) return void 0; if (elem.name.text !== "resolution-mode") { - grammarErrorOnNode == null ? void 0 : grammarErrorOnNode(elem.name, Diagnostics.resolution_mode_is_the_only_valid_key_for_type_import_assertions); + grammarErrorOnNode == null ? void 0 : grammarErrorOnNode( + elem.name, + node.token === 118 /* WithKeyword */ ? Diagnostics.resolution_mode_is_the_only_valid_key_for_type_import_attributes : Diagnostics.resolution_mode_is_the_only_valid_key_for_type_import_assertions + ); return void 0; } if (!isStringLiteralLike(elem.value)) @@ -118449,15 +119286,15 @@ ${lanes.join("\n")} function isReferenceFileLocation(location) { return location.pos !== void 0; } - function getReferencedFileLocation(getSourceFileByPath, ref) { - var _a, _b, _c, _d, _e, _f; - const file = Debug.checkDefined(getSourceFileByPath(ref.file)); + function getReferencedFileLocation(program, ref) { + var _a, _b, _c, _d; + const file = Debug.checkDefined(program.getSourceFileByPath(ref.file)); const { kind, index } = ref; let pos, end, packageId, resolutionMode; switch (kind) { case 3 /* Import */: const importLiteral = getModuleNameStringLiteralAt(file, index); - packageId = (_c = (_b = (_a = file.resolvedModules) == null ? void 0 : _a.get(importLiteral.text, getModeForResolutionAtIndex(file, index))) == null ? void 0 : _b.resolvedModule) == null ? void 0 : _c.packageId; + packageId = (_b = (_a = program.getResolvedModule(file, importLiteral.text, getModeForResolutionAtIndex(file, index))) == null ? void 0 : _a.resolvedModule) == null ? void 0 : _b.packageId; if (importLiteral.pos === -1) return { file, packageId, text: importLiteral.text }; pos = skipTrivia(file.text, importLiteral.pos); @@ -118468,7 +119305,7 @@ ${lanes.join("\n")} break; case 5 /* TypeReferenceDirective */: ({ pos, end, resolutionMode } = file.typeReferenceDirectives[index]); - packageId = (_f = (_e = (_d = file.resolvedTypeReferenceDirectiveNames) == null ? void 0 : _d.get(toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), resolutionMode || file.impliedNodeFormat)) == null ? void 0 : _e.resolvedTypeReferenceDirective) == null ? void 0 : _f.packageId; + packageId = (_d = (_c = program.getResolvedTypeReferenceDirective(file, toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), resolutionMode || file.impliedNodeFormat)) == null ? void 0 : _c.resolvedTypeReferenceDirective) == null ? void 0 : _d.packageId; break; case 7 /* LibReferenceDirective */: ({ pos, end } = file.libReferenceDirectives[index]); @@ -118589,6 +119426,10 @@ ${lanes.join("\n")} let automaticTypeDirectiveResolutions; let resolvedLibReferences; let resolvedLibProcessing; + let resolvedModules; + let resolvedModulesProcessing; + let resolvedTypeReferenceDirectiveNames; + let resolvedTypeReferenceDirectiveNamesProcessing; let packageMap; const maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; let currentNodeModulesDepth = 0; @@ -118664,7 +119505,8 @@ ${lanes.join("\n")} getCanonicalFileName, /*options*/ void 0, - moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache() + moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), + moduleResolutionCache == null ? void 0 : moduleResolutionCache.optionsToRedirectsKey ); actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache( typeDirectiveNames, @@ -118852,6 +119694,8 @@ ${lanes.join("\n")} } oldProgram = void 0; resolvedLibProcessing = void 0; + resolvedModulesProcessing = void 0; + resolvedTypeReferenceDirectiveNamesProcessing = void 0; const program = { getRootFileNames: () => rootNames, getSourceFile, @@ -118893,7 +119737,13 @@ ${lanes.join("\n")} sourceFileToPackageName, redirectTargetsMap, usesUriStyleNodeCoreModules, + resolvedModules, + resolvedTypeReferenceDirectiveNames, resolvedLibReferences, + getResolvedModule, + getResolvedTypeReferenceDirective, + forEachResolvedModule, + forEachResolvedTypeReferenceDirective, getCurrentPackagesMap: () => packageMap, typesPackageExists, packageBundlesTypes, @@ -118924,7 +119774,7 @@ ${lanes.join("\n")} case 1 /* FilePreprocessingFileExplainingDiagnostic */: return programDiagnostics.add(createDiagnosticExplainingFile(diagnostic.file && getSourceFileByPath(diagnostic.file), diagnostic.fileProcessingReason, diagnostic.diagnostic, diagnostic.args || emptyArray)); case 0 /* FilePreprocessingReferencedDiagnostic */: - const { file, pos, end } = getReferencedFileLocation(getSourceFileByPath, diagnostic.reason); + const { file, pos, end } = getReferencedFileLocation(program, diagnostic.reason); return programDiagnostics.add(createFileDiagnostic(file, Debug.checkDefined(pos), Debug.checkDefined(end) - pos, diagnostic.diagnostic, ...diagnostic.args || emptyArray)); case 2 /* ResolutionDiagnostics */: return diagnostic.diagnostics.forEach((d) => programDiagnostics.add(d)); @@ -118937,17 +119787,34 @@ ${lanes.join("\n")} measure("Program", "beforeProgram", "afterProgram"); (_p = tracing) == null ? void 0 : _p.pop(); return program; + function getResolvedModule(file, moduleName, mode) { + var _a2; + return (_a2 = resolvedModules == null ? void 0 : resolvedModules.get(file.path)) == null ? void 0 : _a2.get(moduleName, mode); + } + function getResolvedTypeReferenceDirective(file, typeDirectiveName, mode) { + var _a2; + return (_a2 = resolvedTypeReferenceDirectiveNames == null ? void 0 : resolvedTypeReferenceDirectiveNames.get(file.path)) == null ? void 0 : _a2.get(typeDirectiveName, mode); + } + function forEachResolvedModule(callback, file) { + forEachResolution(resolvedModules, callback, file); + } + function forEachResolvedTypeReferenceDirective(callback, file) { + forEachResolution(resolvedTypeReferenceDirectiveNames, callback, file); + } + function forEachResolution(resolutionCache, callback, file) { + var _a2; + if (file) + (_a2 = resolutionCache == null ? void 0 : resolutionCache.get(file.path)) == null ? void 0 : _a2.forEach((resolution, name, mode) => callback(resolution, name, mode, file.path)); + else + resolutionCache == null ? void 0 : resolutionCache.forEach((resolutions, filePath) => resolutions.forEach((resolution, name, mode) => callback(resolution, name, mode, filePath))); + } function getPackagesMap() { if (packageMap) return packageMap; packageMap = /* @__PURE__ */ new Map(); - files.forEach((sf) => { - if (!sf.resolvedModules) - return; - sf.resolvedModules.forEach(({ resolvedModule }) => { - if (resolvedModule == null ? void 0 : resolvedModule.packageId) - packageMap.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!packageMap.get(resolvedModule.packageId.name)); - }); + forEachResolvedModule(({ resolvedModule }) => { + if (resolvedModule == null ? void 0 : resolvedModule.packageId) + packageMap.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!packageMap.get(resolvedModule.packageId.name)); }); return packageMap; } @@ -119014,7 +119881,7 @@ ${lanes.join("\n")} const resultFromDts = getRedirectReferenceForResolutionFromSourceOfProject(file.path); if (resultFromDts) return resultFromDts; - if (!host.realpath || !options.preserveSymlinks || !stringContains(file.originalFileName, nodeModulesPathPart)) + if (!host.realpath || !options.preserveSymlinks || !file.originalFileName.includes(nodeModulesPathPart)) return void 0; const realDeclarationPath = toPath3(host.realpath(file.originalFileName)); return realDeclarationPath === file.path ? void 0 : getRedirectReferenceForResolutionFromSourceOfProject(realDeclarationPath); @@ -119080,7 +119947,6 @@ ${lanes.join("\n")} return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, file) { - var _a2; if (structureIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { return resolveModuleNamesWorker( moduleNames, @@ -119089,24 +119955,16 @@ ${lanes.join("\n")} void 0 ); } - const oldSourceFile = oldProgram && oldProgram.getSourceFile(file.fileName); - if (oldSourceFile !== file && file.resolvedModules) { - const result2 = []; - for (const moduleName of moduleNames) { - const resolvedModule = file.resolvedModules.get(moduleName.text, getModeForUsageLocation(file, moduleName)); - result2.push(resolvedModule); - } - return result2; - } let unknownModuleNames; let result; let reusedNames; const predictedToResolveToAmbientModuleMarker = emptyResolution; + const oldSourceFile = oldProgram && oldProgram.getSourceFile(file.fileName); for (let i = 0; i < moduleNames.length; i++) { const moduleName = moduleNames[i]; - if (file === oldSourceFile && !hasInvalidatedResolutions(oldSourceFile.path)) { + if (file === oldSourceFile && !hasInvalidatedResolutions(file.path)) { const mode = getModeForUsageLocation(file, moduleName); - const oldResolution = (_a2 = oldSourceFile.resolvedModules) == null ? void 0 : _a2.get(moduleName.text, mode); + const oldResolution = oldProgram == null ? void 0 : oldProgram.getResolvedModule(file, moduleName.text, mode); if (oldResolution == null ? void 0 : oldResolution.resolvedModule) { if (isTraceEnabled(options, host)) { trace( @@ -119153,7 +120011,8 @@ ${lanes.join("\n")} Debug.assert(j === resolutions.length); return result; function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { - const resolutionToFile = getResolvedModule(oldSourceFile, moduleName.text, getModeForUsageLocation(file, moduleName)); + var _a2; + const resolutionToFile = (_a2 = oldProgram == null ? void 0 : oldProgram.getResolvedModule(file, moduleName.text, getModeForUsageLocation(file, moduleName))) == null ? void 0 : _a2.resolvedModule; const resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile) { return false; @@ -119178,28 +120037,18 @@ ${lanes.join("\n")} void 0 ); } - const oldSourceFile = !isString(containingFile) ? oldProgram && oldProgram.getSourceFile(containingFile.fileName) : void 0; - if (!isString(containingFile)) { - if (oldSourceFile !== containingFile && containingFile.resolvedTypeReferenceDirectiveNames) { - const result2 = []; - for (const typeDirectiveName of typeDirectiveNames) { - const resolvedTypeReferenceDirective = containingFile.resolvedTypeReferenceDirectiveNames.get(getTypeReferenceResolutionName(typeDirectiveName), getModeForFileReference(typeDirectiveName, containingFile.impliedNodeFormat)); - result2.push(resolvedTypeReferenceDirective); - } - return result2; - } - } let unknownTypeReferenceDirectiveNames; let result; let reusedNames; const containingSourceFile = !isString(containingFile) ? containingFile : void 0; - const canReuseResolutions = !isString(containingFile) ? containingFile === oldSourceFile && !hasInvalidatedResolutions(oldSourceFile.path) : !hasInvalidatedResolutions(toPath3(containingFile)); + const oldSourceFile = !isString(containingFile) ? oldProgram && oldProgram.getSourceFile(containingFile.fileName) : void 0; + const canReuseResolutions = !isString(containingFile) ? containingFile === oldSourceFile && !hasInvalidatedResolutions(containingFile.path) : !hasInvalidatedResolutions(toPath3(containingFile)); for (let i = 0; i < typeDirectiveNames.length; i++) { const entry = typeDirectiveNames[i]; if (canReuseResolutions) { const typeDirectiveName = getTypeReferenceResolutionName(entry); const mode = getModeForFileReference(entry, containingSourceFile == null ? void 0 : containingSourceFile.impliedNodeFormat); - const oldResolution = (_a2 = !isString(containingFile) ? oldSourceFile == null ? void 0 : oldSourceFile.resolvedTypeReferenceDirectiveNames : oldProgram == null ? void 0 : oldProgram.getAutomaticTypeDirectiveResolutions()) == null ? void 0 : _a2.get(typeDirectiveName, mode); + const oldResolution = !isString(containingFile) ? oldProgram == null ? void 0 : oldProgram.getResolvedTypeReferenceDirective(containingFile, typeDirectiveName, mode) : (_a2 = oldProgram == null ? void 0 : oldProgram.getAutomaticTypeDirectiveResolutions()) == null ? void 0 : _a2.get(typeDirectiveName, mode); if (oldResolution == null ? void 0 : oldResolution.resolvedTypeReferenceDirective) { if (isTraceEnabled(options, host)) { trace( @@ -119361,43 +120210,47 @@ ${lanes.join("\n")} structureIsReused = 1 /* SafeModules */; } } - modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + modifiedSourceFiles.push(newSourceFile); } else if (hasInvalidatedResolutions(oldSourceFile.path)) { structureIsReused = 1 /* SafeModules */; - modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + modifiedSourceFiles.push(newSourceFile); + } else { + for (const moduleName of oldSourceFile.ambientModuleNames) { + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldSourceFile.fileName); + } } newSourceFiles.push(newSourceFile); } if (structureIsReused !== 2 /* Completely */) { return structureIsReused; } - const modifiedFiles = modifiedSourceFiles.map((f) => f.oldFile); - for (const oldFile of oldSourceFiles) { - if (!contains(modifiedFiles, oldFile)) { - for (const moduleName of oldFile.ambientModuleNames) { - ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); - } - } - } - for (const { oldFile: oldSourceFile, newFile: newSourceFile } of modifiedSourceFiles) { + for (const newSourceFile of modifiedSourceFiles) { const moduleNames = getModuleNames(newSourceFile); const resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile); - const resolutionsChanged = hasChangesInResolutions(moduleNames, newSourceFile, resolutions, oldSourceFile.resolvedModules, moduleResolutionIsEqualTo, moduleResolutionNameAndModeGetter); - if (resolutionsChanged) { + (resolvedModulesProcessing ?? (resolvedModulesProcessing = /* @__PURE__ */ new Map())).set(newSourceFile.path, resolutions); + const resolutionsChanged = hasChangesInResolutions( + moduleNames, + newSourceFile, + resolutions, + (name, mode) => oldProgram.getResolvedModule(newSourceFile, name, mode), + moduleResolutionIsEqualTo, + moduleResolutionNameAndModeGetter + ); + if (resolutionsChanged) structureIsReused = 1 /* SafeModules */; - newSourceFile.resolvedModules = zipToModeAwareCache(newSourceFile, moduleNames, resolutions, moduleResolutionNameAndModeGetter); - } else { - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - } const typesReferenceDirectives = newSourceFile.typeReferenceDirectives; const typeReferenceResolutions = resolveTypeReferenceDirectiveNamesReusingOldState(typesReferenceDirectives, newSourceFile); - const typeReferenceResolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, newSourceFile, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, typeDirectiveIsEqualTo, typeReferenceResolutionNameAndModeGetter); - if (typeReferenceResolutionsChanged) { + (resolvedTypeReferenceDirectiveNamesProcessing ?? (resolvedTypeReferenceDirectiveNamesProcessing = /* @__PURE__ */ new Map())).set(newSourceFile.path, typeReferenceResolutions); + const typeReferenceResolutionsChanged = hasChangesInResolutions( + typesReferenceDirectives, + newSourceFile, + typeReferenceResolutions, + (name, mode) => oldProgram == null ? void 0 : oldProgram.getResolvedTypeReferenceDirective(newSourceFile, name, mode), + typeDirectiveIsEqualTo, + typeReferenceResolutionNameAndModeGetter + ); + if (typeReferenceResolutionsChanged) structureIsReused = 1 /* SafeModules */; - newSourceFile.resolvedTypeReferenceDirectiveNames = zipToModeAwareCache(newSourceFile, typesReferenceDirectives, typeReferenceResolutions, typeReferenceResolutionNameAndModeGetter); - } else { - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; - } } if (structureIsReused !== 2 /* Completely */) { return structureIsReused; @@ -119444,6 +120297,8 @@ ${lanes.join("\n")} sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; usesUriStyleNodeCoreModules = oldProgram.usesUriStyleNodeCoreModules; + resolvedModules = oldProgram.resolvedModules; + resolvedTypeReferenceDirectiveNames = oldProgram.resolvedTypeReferenceDirectiveNames; resolvedLibReferences = oldProgram.resolvedLibReferences; packageMap = oldProgram.getCurrentPackagesMap(); return 2 /* Completely */; @@ -120024,7 +120879,7 @@ ${lanes.join("\n")} /*importClause*/ void 0, externalHelpersModuleReference, - /*assertClause*/ + /*attributes*/ void 0 ); addInternalEmitFlags(importDecl, 2 /* NeverApplyImportHelper */); @@ -120082,7 +120937,7 @@ ${lanes.join("\n")} } } } else if (isModuleDeclaration(node)) { - if (isAmbientModule(node) && (inAmbientModule || hasSyntacticModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { + if (isAmbientModule(node) && (inAmbientModule || hasSyntacticModifier(node, 128 /* Ambient */) || file.isDeclarationFile)) { node.name.parent = node; const nameText = getTextOfIdentifierOrLiteral(node.name); if (isExternalModuleFile || inAmbientModule && !isExternalModuleNameRelative(nameText)) { @@ -120265,14 +121120,14 @@ ${lanes.join("\n")} const result = getImpliedNodeFormatForFileWorker(getNormalizedAbsolutePath(fileName, currentDirectory), moduleResolutionCache2 == null ? void 0 : moduleResolutionCache2.getPackageJsonInfoCache(), host2, options2); const languageVersion = getEmitScriptTarget(options2); const setExternalModuleIndicator2 = getSetExternalModuleIndicator(options2); - return typeof result === "object" ? { ...result, languageVersion, setExternalModuleIndicator: setExternalModuleIndicator2 } : { languageVersion, impliedNodeFormat: result, setExternalModuleIndicator: setExternalModuleIndicator2 }; + return typeof result === "object" ? { ...result, languageVersion, setExternalModuleIndicator: setExternalModuleIndicator2, jsDocParsingMode: host2.jsDocParsingMode } : { languageVersion, impliedNodeFormat: result, setExternalModuleIndicator: setExternalModuleIndicator2, jsDocParsingMode: host2.jsDocParsingMode }; } function findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { var _a2; const path = toPath3(fileName); if (useSourceOfProjectReferenceRedirect) { let source = getSourceOfProjectReferenceRedirect(path); - if (!source && host.realpath && options.preserveSymlinks && isDeclarationFileName(fileName) && stringContains(fileName, nodeModulesPathPart)) { + if (!source && host.realpath && options.preserveSymlinks && isDeclarationFileName(fileName) && fileName.includes(nodeModulesPathPart)) { const realPath2 = toPath3(host.realpath(fileName)); if (realPath2 !== path) source = getSourceOfProjectReferenceRedirect(realPath2); @@ -120489,25 +121344,17 @@ ${lanes.join("\n")} } function processTypeReferenceDirectives(file) { const typeDirectives = file.typeReferenceDirectives; - if (!typeDirectives.length) { - file.resolvedTypeReferenceDirectiveNames = void 0; + if (!typeDirectives.length) return; - } - const resolutions = resolveTypeReferenceDirectiveNamesReusingOldState(typeDirectives, file); + const resolutions = (resolvedTypeReferenceDirectiveNamesProcessing == null ? void 0 : resolvedTypeReferenceDirectiveNamesProcessing.get(file.path)) || resolveTypeReferenceDirectiveNamesReusingOldState(typeDirectives, file); + const resolutionsInFile = createModeAwareCache(); + (resolvedTypeReferenceDirectiveNames ?? (resolvedTypeReferenceDirectiveNames = /* @__PURE__ */ new Map())).set(file.path, resolutionsInFile); for (let index = 0; index < typeDirectives.length; index++) { const ref = file.typeReferenceDirectives[index]; const resolvedTypeReferenceDirective = resolutions[index]; const fileName = toFileNameLowerCase(ref.fileName); - setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective, getModeForFileReference(ref, file.impliedNodeFormat)); + resolutionsInFile.set(fileName, getModeForFileReference(ref, file.impliedNodeFormat), resolvedTypeReferenceDirective); const mode = ref.resolutionMode || file.impliedNodeFormat; - if (mode && getEmitModuleResolutionKind(options) !== 3 /* Node16 */ && getEmitModuleResolutionKind(options) !== 99 /* NodeNext */) { - (fileProcessingDiagnostics ?? (fileProcessingDiagnostics = [])).push({ - kind: 2 /* ResolutionDiagnostics */, - diagnostics: [ - createDiagnosticForRange(file, ref, Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext) - ] - }); - } processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: 5 /* TypeReferenceDirective */, file: file.path, index }); } } @@ -120662,14 +121509,16 @@ ${lanes.join("\n")} collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { const moduleNames = getModuleNames(file); - const resolutions = resolveModuleNamesReusingOldState(moduleNames, file); + const resolutions = (resolvedModulesProcessing == null ? void 0 : resolvedModulesProcessing.get(file.path)) || resolveModuleNamesReusingOldState(moduleNames, file); Debug.assert(resolutions.length === moduleNames.length); const optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a2 = getRedirectReferenceForResolution(file)) == null ? void 0 : _a2.commandLine.options : void 0) || options; + const resolutionsInFile = createModeAwareCache(); + (resolvedModules ?? (resolvedModules = /* @__PURE__ */ new Map())).set(file.path, resolutionsInFile); for (let index = 0; index < moduleNames.length; index++) { const resolution = resolutions[index].resolvedModule; const moduleName = moduleNames[index].text; const mode = getModeForUsageLocation(file, moduleNames[index]); - setResolvedModule(file, moduleName, resolutions[index], mode); + resolutionsInFile.set(moduleName, mode, resolutions[index]); addResolutionDiagnosticsFromResolutionOrCache(file, moduleName, resolutions[index], mode); if (!resolution) { continue; @@ -120700,8 +121549,6 @@ ${lanes.join("\n")} currentNodeModulesDepth--; } } - } else { - file.resolvedModules = void 0; } } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { @@ -121216,7 +122063,7 @@ ${lanes.join("\n")} processReason(fileProcessingReason); if (locationReason && (fileIncludeReasons == null ? void 0 : fileIncludeReasons.length) === 1) fileIncludeReasons = void 0; - const location = locationReason && getReferencedFileLocation(getSourceFileByPath, locationReason); + const location = locationReason && getReferencedFileLocation(program, locationReason); const fileIncludeReasonDetails = fileIncludeReasons && chainDiagnosticMessages(fileIncludeReasons, Diagnostics.The_file_is_in_the_program_because_Colon); const redirectInfo = file && explainIfFileIsRedirectAndImpliedFormat(file); const chain = chainDiagnosticMessages(redirectInfo ? fileIncludeReasonDetails ? [fileIncludeReasonDetails, ...redirectInfo] : redirectInfo : fileIncludeReasonDetails, diagnostic, ...args || emptyArray); @@ -121252,7 +122099,7 @@ ${lanes.join("\n")} } function fileIncludeReasonToRelatedInformation(reason) { if (isReferencedFile(reason)) { - const referenceLocation = getReferencedFileLocation(getSourceFileByPath, reason); + const referenceLocation = getReferencedFileLocation(program, reason); let message2; switch (reason.kind) { case 3 /* Import */: @@ -121301,19 +122148,11 @@ ${lanes.join("\n")} case 1 /* SourceFromProjectReference */: case 2 /* OutputFromProjectReference */: const referencedResolvedRef = Debug.checkDefined(resolvedProjectReferences == null ? void 0 : resolvedProjectReferences[reason.index]); - const referenceInfo = forEachProjectReference( - projectReferences, - resolvedProjectReferences, - (resolvedRef, parent2, index2) => resolvedRef === referencedResolvedRef ? { sourceFile: (parent2 == null ? void 0 : parent2.sourceFile) || options.configFile, index: index2 } : void 0 - ); + const referenceInfo = forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, parent2, index2) => resolvedRef === referencedResolvedRef ? { sourceFile: (parent2 == null ? void 0 : parent2.sourceFile) || options.configFile, index: index2 } : void 0); if (!referenceInfo) return void 0; const { sourceFile, index } = referenceInfo; - const referencesSyntax = forEachTsConfigPropArray( - sourceFile, - "references", - (property) => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0 - ); + const referencesSyntax = forEachTsConfigPropArray(sourceFile, "references", (property) => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); return referencesSyntax && referencesSyntax.elements.length > index ? createDiagnosticForNodeInSourceFile( sourceFile, referencesSyntax.elements[index], @@ -121453,11 +122292,7 @@ ${lanes.join("\n")} ); } function createDiagnosticForReference(sourceFile, index, message, ...args) { - const referencesSyntax = forEachTsConfigPropArray( - sourceFile || options.configFile, - "references", - (property) => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0 - ); + const referencesSyntax = forEachTsConfigPropArray(sourceFile || options.configFile, "references", (property) => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); if (referencesSyntax && referencesSyntax.elements.length > index) { programDiagnostics.add(createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, ...args)); } else { @@ -121553,8 +122388,8 @@ ${lanes.join("\n")} if (!symlinks) { symlinks = createSymlinkCache(currentDirectory, getCanonicalFileName); } - if (files && automaticTypeDirectiveResolutions && !symlinks.hasProcessedResolutions()) { - symlinks.setSymlinksFromResolutions(files, automaticTypeDirectiveResolutions); + if (files && !symlinks.hasProcessedResolutions()) { + symlinks.setSymlinksFromResolutions(forEachResolvedModule, forEachResolvedTypeReferenceDirective, automaticTypeDirectiveResolutions); } return symlinks; } @@ -121644,7 +122479,7 @@ ${lanes.join("\n")} var _a; if (!host.getResolvedProjectReferences() || containsIgnoredPath(directory)) return; - if (!originalRealpath || !stringContains(directory, nodeModulesPathPart)) + if (!originalRealpath || !directory.includes(nodeModulesPathPart)) return; const symlinkCache = host.getSymlinkCache(); const directoryPath = ensureTrailingDirectorySeparator(host.toPath(directory)); @@ -121672,7 +122507,7 @@ ${lanes.join("\n")} if (!symlinkedDirectories) return false; const fileOrDirectoryPath = host.toPath(fileOrDirectory); - if (!stringContains(fileOrDirectoryPath, nodeModulesPathPart)) + if (!fileOrDirectoryPath.includes(nodeModulesPathPart)) return false; if (isFile && ((_a = symlinkCache.getSymlinkedFiles()) == null ? void 0 : _a.has(fileOrDirectoryPath))) return true; @@ -121915,7 +122750,7 @@ ${lanes.join("\n")} Diagnostics.Classes_may_not_have_a_field_named_constructor.code, Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code, Diagnostics.Duplicate_label_0.code, - Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments.code, + Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments.code, Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block.code, Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression.code, Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name.code, @@ -122074,16 +122909,14 @@ ${lanes.join("\n")} addReferencedFile(referencedPath); } } - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(({ resolvedTypeReferenceDirective }) => { - if (!resolvedTypeReferenceDirective) { - return; - } - const fileName = resolvedTypeReferenceDirective.resolvedFileName; - const typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); - addReferencedFile(typeFilePath); - }); - } + program.forEachResolvedTypeReferenceDirective(({ resolvedTypeReferenceDirective }) => { + if (!resolvedTypeReferenceDirective) { + return; + } + const fileName = resolvedTypeReferenceDirective.resolvedFileName; + const typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }, sourceFile); if (sourceFile.moduleAugmentations.length) { const checker = program.getTypeChecker(); for (const moduleName of sourceFile.moduleAugmentations) { @@ -122202,13 +123035,16 @@ ${lanes.join("\n")} sourceFile, (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) => { Debug.assert(isDeclarationFileName(fileName), `File extension for signature expected to be dts: Got:: ${fileName}`); - onNewSignature(computeSignatureWithDiagnostics( - programOfThisState, - sourceFile, - text, - host, - data - ), sourceFiles); + onNewSignature( + computeSignatureWithDiagnostics( + programOfThisState, + sourceFile, + text, + host, + data + ), + sourceFiles + ); }, cancellationToken, /*emitOnly*/ @@ -122722,10 +123558,7 @@ ${lanes.join("\n")} state.cleanedDiagnosticsOfLibFiles = true; const program = Debug.checkDefined(state.program); const options = program.getCompilerOptions(); - forEach( - program.getSourceFiles(), - (f) => program.isSourceFileDefaultLibrary(f) && !skipTypeChecking(f, options, program) && removeSemanticDiagnosticsOf(state, f.resolvedPath) - ); + forEach(program.getSourceFiles(), (f) => program.isSourceFileDefaultLibrary(f) && !skipTypeChecking(f, options, program) && removeSemanticDiagnosticsOf(state, f.resolvedPath)); } } function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, host) { @@ -122793,12 +123626,14 @@ ${lanes.join("\n")} state.program, /*firstSourceFile*/ void 0 - ).forEach((file) => handleDtsMayChangeOf( - state, - file.resolvedPath, - cancellationToken, - host - )); + ).forEach( + (file) => handleDtsMayChangeOf( + state, + file.resolvedPath, + cancellationToken, + host + ) + ); removeDiagnosticsOfLibraryFiles(state); return true; } @@ -122831,16 +123666,13 @@ ${lanes.join("\n")} if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, host)) return true; const references = state.referencedMap.getKeys(exportedFromPath); - return references && forEachKey( - references, - (filePath) => handleDtsMayChangeOfFileAndExportsOfFile( - state, - filePath, - seenFileAndExportsOfFile, - cancellationToken, - host - ) - ); + return references && forEachKey(references, (filePath) => handleDtsMayChangeOfFileAndExportsOfFile( + state, + filePath, + seenFileAndExportsOfFile, + cancellationToken, + host + )); }); } function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, host) { @@ -122948,11 +123780,13 @@ ${lanes.join("\n")} if (!isJsonSourceFile(file) && sourceFileMayBeEmitted(file, state.program)) { const emitSignature = (_b2 = state.emitSignatures) == null ? void 0 : _b2.get(key); if (emitSignature !== actualSignature) { - (emitSignatures || (emitSignatures = [])).push(emitSignature === void 0 ? fileId : ( - // There is no emit, encode as false - // fileId, signature: emptyArray if signature only differs in dtsMap option than our own compilerOptions otherwise EmitSignature - [fileId, !isString(emitSignature) && emitSignature[0] === actualSignature ? emptyArray : emitSignature] - )); + (emitSignatures || (emitSignatures = [])).push( + emitSignature === void 0 ? fileId : ( + // There is no emit, encode as false + // fileId, signature: emptyArray if signature only differs in dtsMap option than our own compilerOptions otherwise EmitSignature + [fileId, !isString(emitSignature) && emitSignature[0] === actualSignature ? emptyArray : emitSignature] + ) + ); } } } @@ -123206,9 +124040,7 @@ ${lanes.join("\n")} text = getTextHandlingSourceMapForSignature(text, data); let sourceFileDirectory; if ((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length) { - text += data.diagnostics.map( - (diagnostic) => `${locationInfo(diagnostic)}${DiagnosticCategory[diagnostic.category]}${diagnostic.code}: ${flattenDiagnosticMessageText2(diagnostic.messageText)}` - ).join("\n"); + text += data.diagnostics.map((diagnostic) => `${locationInfo(diagnostic)}${DiagnosticCategory[diagnostic.category]}${diagnostic.code}: ${flattenDiagnosticMessageText2(diagnostic.messageText)}`).join("\n"); } return (host.createHash ?? generateDjb2Hash)(text); function flattenDiagnosticMessageText2(diagnostic) { @@ -123615,9 +124447,7 @@ ${lanes.join("\n")} return void 0; } const map2 = BuilderState.createManyToManyPathMap(); - referenceMap.forEach( - ([fileId, fileIdListId]) => map2.set(toFilePath(fileId), toFilePathsSet(fileIdListId)) - ); + referenceMap.forEach(([fileId, fileIdListId]) => map2.set(toFilePath(fileId), toFilePathsSet(fileIdListId))); return map2; } } @@ -123723,24 +124553,27 @@ ${lanes.join("\n")} if (endsWith(path, "/node_modules/.staging")) { return removeSuffix(path, "/.staging"); } - return some(ignoredPaths, (searchPath) => stringContains(path, searchPath)) ? void 0 : path; + return some(ignoredPaths, (searchPath) => path.includes(searchPath)) ? void 0 : path; } function perceivedOsRootLengthForWatching(pathComponents2, length2) { if (length2 <= 1) return 1; - let userCheckIndex = 1; + let indexAfterOsRoot = 1; let isDosStyle = pathComponents2[0].search(/[a-zA-Z]:/) === 0; if (pathComponents2[0] !== directorySeparator && !isDosStyle && // Non dos style paths pathComponents2[1].search(/[a-zA-Z]\$$/) === 0) { if (length2 === 2) return 2; - userCheckIndex = 2; + indexAfterOsRoot = 2; isDosStyle = true; } - if (isDosStyle && !pathComponents2[userCheckIndex].match(/^users$/i)) { - return userCheckIndex; + if (isDosStyle && !pathComponents2[indexAfterOsRoot].match(/^users$/i)) { + return indexAfterOsRoot; } - return userCheckIndex + 2; + if (pathComponents2[indexAfterOsRoot].match(/^workspaces$/i)) { + return indexAfterOsRoot + 1; + } + return indexAfterOsRoot + 2; } function canWatchDirectoryOrFile(pathComponents2, length2) { if (length2 === void 0) @@ -123843,6 +124676,50 @@ ${lanes.join("\n")} function getRootPathSplitLength(rootPath) { return rootPath.split(directorySeparator).length - (hasTrailingDirectorySeparator(rootPath) ? 1 : 0); } + function getModuleResolutionHost(resolutionHost) { + var _a; + return ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost; + } + function createModuleResolutionLoaderUsingGlobalCache(containingFile, redirectedReference, options, resolutionHost, moduleResolutionCache) { + return { + nameAndMode: moduleResolutionNameAndModeGetter, + resolve: (moduleName, resoluionMode) => resolveModuleNameUsingGlobalCache( + resolutionHost, + moduleResolutionCache, + moduleName, + containingFile, + options, + redirectedReference, + resoluionMode + ) + }; + } + function resolveModuleNameUsingGlobalCache(resolutionHost, moduleResolutionCache, moduleName, containingFile, compilerOptions, redirectedReference, mode) { + const host = getModuleResolutionHost(resolutionHost); + const primaryResult = resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode); + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + const globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== void 0 && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTS(primaryResult.resolvedModule.extension))) { + const { resolvedModule, failedLookupLocations, affectingLocations, resolutionDiagnostics } = loadModuleFromGlobalCache( + Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), + resolutionHost.projectName, + compilerOptions, + host, + globalCache, + moduleResolutionCache + ); + if (resolvedModule) { + primaryResult.resolvedModule = resolvedModule; + primaryResult.failedLookupLocations = updateResolutionField(primaryResult.failedLookupLocations, failedLookupLocations); + primaryResult.affectingLocations = updateResolutionField(primaryResult.affectingLocations, affectingLocations); + primaryResult.resolutionDiagnostics = updateResolutionField(primaryResult.resolutionDiagnostics, resolutionDiagnostics); + return primaryResult; + } + } + return primaryResult; + } function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { let filesWithChangedSetOfUnresolvedImports; let filesWithInvalidatedResolutions; @@ -123872,7 +124749,8 @@ ${lanes.join("\n")} getCurrentDirectory(), resolutionHost.getCanonicalFileName, resolutionHost.getCompilationSettings(), - moduleResolutionCache.getPackageJsonInfoCache() + moduleResolutionCache.getPackageJsonInfoCache(), + moduleResolutionCache.optionsToRedirectsKey ); const resolvedLibraries = /* @__PURE__ */ new Map(); const libraryResolutionCache = createModuleResolutionCache( @@ -123888,6 +124766,16 @@ ${lanes.join("\n")} const rootPathComponents = getPathComponents(rootPath); const typeRootsWatches = /* @__PURE__ */ new Map(); return { + rootDirForResolution, + resolvedModuleNames, + resolvedTypeReferenceDirectives, + resolvedLibraries, + resolvedFileToResolution, + resolutionsWithFailedLookups, + resolutionsWithOnlyAffectingLocations, + directoryWatchesOfFailedLookups, + fileWatchesOfAffectingLocations, + watchFailedLookupLocationsOfExternalModuleResolutions, getModuleResolutionCache: () => moduleResolutionCache, startRecordingFilesWithChangedResolutions, finishRecordingFilesWithChangedResolutions, @@ -123912,10 +124800,10 @@ ${lanes.join("\n")} clear: clear2, onChangesAffectModuleResolution }; - function getResolvedModule2(resolution) { + function getResolvedModule(resolution) { return resolution.resolvedModule; } - function getResolvedTypeReferenceDirective2(resolution) { + function getResolvedTypeReferenceDirective(resolution) { return resolution.resolvedTypeReferenceDirective; } function clear2() { @@ -123978,6 +124866,10 @@ ${lanes.join("\n")} }; } function startCachingPerDirectoryResolution() { + moduleResolutionCache.isReadonly = void 0; + typeReferenceDirectiveResolutionCache.isReadonly = void 0; + libraryResolutionCache.isReadonly = void 0; + moduleResolutionCache.getPackageJsonInfoCache().isReadonly = void 0; moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); libraryResolutionCache.clearAllExceptPackageJsonInfoCache(); @@ -123990,8 +124882,8 @@ ${lanes.join("\n")} if (!((_a = newProgram == null ? void 0 : newProgram.resolvedLibReferences) == null ? void 0 : _a.has(libFileName))) { stopWatchFailedLookupLocationOfResolution( resolution, - resolutionHost.toPath(getInferredLibraryNameResolveFrom(newProgram.getCompilerOptions(), getCurrentDirectory(), libFileName)), - getResolvedModule2 + resolutionHost.toPath(getInferredLibraryNameResolveFrom(resolutionHost.getCompilationSettings(), getCurrentDirectory(), libFileName)), + getResolvedModule ); resolvedLibraries.delete(libFileName); } @@ -124032,58 +124924,26 @@ ${lanes.join("\n")} } }); } - directoryWatchesOfFailedLookups.forEach((watcher, path) => { - if (watcher.refCount === 0) { - directoryWatchesOfFailedLookups.delete(path); - watcher.watcher.close(); - } - }); - fileWatchesOfAffectingLocations.forEach((watcher, path) => { - if (watcher.files === 0 && watcher.resolutions === 0) { - fileWatchesOfAffectingLocations.delete(path); - watcher.watcher.close(); - } - }); + directoryWatchesOfFailedLookups.forEach(closeDirectoryWatchesOfFailedLookup); + fileWatchesOfAffectingLocations.forEach(closeFileWatcherOfAffectingLocation); hasChangedAutomaticTypeDirectiveNames = false; + moduleResolutionCache.isReadonly = true; + typeReferenceDirectiveResolutionCache.isReadonly = true; + libraryResolutionCache.isReadonly = true; + moduleResolutionCache.getPackageJsonInfoCache().isReadonly = true; } - function resolveModuleName2(moduleName, containingFile, compilerOptions, redirectedReference, mode) { + function closeDirectoryWatchesOfFailedLookup(watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + } + function closeFileWatcherOfAffectingLocation(watcher, path) { var _a; - const host = ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost; - const primaryResult = resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode); - if (!resolutionHost.getGlobalCache) { - return primaryResult; + if (watcher.files === 0 && watcher.resolutions === 0 && !((_a = watcher.symlinks) == null ? void 0 : _a.size)) { + fileWatchesOfAffectingLocations.delete(path); + watcher.watcher.close(); } - const globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== void 0 && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTS(primaryResult.resolvedModule.extension))) { - const { resolvedModule, failedLookupLocations, affectingLocations, resolutionDiagnostics } = loadModuleFromGlobalCache( - Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), - resolutionHost.projectName, - compilerOptions, - host, - globalCache, - moduleResolutionCache - ); - if (resolvedModule) { - primaryResult.resolvedModule = resolvedModule; - primaryResult.failedLookupLocations = updateResolutionField(primaryResult.failedLookupLocations, failedLookupLocations); - primaryResult.affectingLocations = updateResolutionField(primaryResult.affectingLocations, affectingLocations); - primaryResult.resolutionDiagnostics = updateResolutionField(primaryResult.resolutionDiagnostics, resolutionDiagnostics); - return primaryResult; - } - } - return primaryResult; - } - function createModuleResolutionLoader2(containingFile, redirectedReference, options) { - return { - nameAndMode: moduleResolutionNameAndModeGetter, - resolve: (moduleName, resoluionMode) => resolveModuleName2( - moduleName, - containingFile, - options, - redirectedReference, - resoluionMode - ) - }; } function resolveNamesWithLocalCache({ entries, @@ -124099,7 +124959,6 @@ ${lanes.join("\n")} shouldRetryResolution, logChanges }) { - var _a; const path = resolutionHost.toPath(containingFile); const resolutionsInFile = perFileCache.get(path) || perFileCache.set(path, createModeAwareCache()).get(path); const resolvedModules = []; @@ -124120,16 +124979,18 @@ ${lanes.join("\n")} resolutionHost.onDiscoveredSymlink(); } resolutionsInFile.set(name, mode, resolution); - watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution); - if (existingResolution) { - stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName); + if (resolution !== existingResolution) { + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution); + if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName); + } } if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { filesWithChangedSetOfUnresolvedImports.push(path); logChanges = false; } } else { - const host = ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost; + const host = getModuleResolutionHost(resolutionHost); if (isTraceEnabled(options, host) && !seenNamesInFile.has(name, mode)) { const resolved = getResolutionWithResolvedFileName(resolution); trace( @@ -124146,11 +125007,13 @@ ${lanes.join("\n")} seenNamesInFile.set(name, mode, true); resolvedModules.push(resolution); } - reusedNames == null ? void 0 : reusedNames.forEach((entry) => seenNamesInFile.set( - loader.nameAndMode.getName(entry), - loader.nameAndMode.getMode(entry, containingSourceFile), - true - )); + reusedNames == null ? void 0 : reusedNames.forEach( + (entry) => seenNamesInFile.set( + loader.nameAndMode.getName(entry), + loader.nameAndMode.getMode(entry, containingSourceFile), + true + ) + ); if (resolutionsInFile.size() !== seenNamesInFile.size()) { resolutionsInFile.forEach((resolution, name, mode) => { if (!seenNamesInFile.has(name, mode)) { @@ -124179,7 +125042,6 @@ ${lanes.join("\n")} } } function resolveTypeReferenceDirectiveReferences(typeDirectiveReferences, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { - var _a; return resolveNamesWithLocalCache({ entries: typeDirectiveReferences, containingFile, @@ -124192,10 +125054,10 @@ ${lanes.join("\n")} containingFile, redirectedReference, options, - ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost, + getModuleResolutionHost(resolutionHost), typeReferenceDirectiveResolutionCache ), - getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective2, + getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: (resolution) => resolution.resolvedTypeReferenceDirective === void 0, deferWatchingNonRelativeResolution: false }); @@ -124209,12 +125071,14 @@ ${lanes.join("\n")} options, reusedNames, perFileCache: resolvedModuleNames, - loader: createModuleResolutionLoader2( + loader: createModuleResolutionLoaderUsingGlobalCache( containingFile, redirectedReference, - options + options, + resolutionHost, + moduleResolutionCache ), - getResolutionWithResolvedFileName: getResolvedModule2, + getResolutionWithResolvedFileName: getResolvedModule, shouldRetryResolution: (resolution) => !resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension), logChanges: logChangesWhenResolvingModule, deferWatchingNonRelativeResolution: true @@ -124222,8 +125086,7 @@ ${lanes.join("\n")} }); } function resolveLibrary2(libraryName, resolveFrom, options, libFileName) { - var _a; - const host = ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost; + const host = getModuleResolutionHost(resolutionHost); let resolution = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName); if (!resolution || resolution.isInvalidated) { const existingResolution = resolution; @@ -124233,17 +125096,17 @@ ${lanes.join("\n")} libraryName, resolution, path, - getResolvedModule2, + getResolvedModule, /*deferWatchingNonRelativeResolution*/ false ); resolvedLibraries.set(libFileName, resolution); if (existingResolution) { - stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolvedModule2); + stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolvedModule); } } else { if (isTraceEnabled(options, host)) { - const resolved = getResolvedModule2(resolution); + const resolved = getResolvedModule(resolution); trace( host, (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved, @@ -124257,6 +125120,7 @@ ${lanes.join("\n")} return resolution; } function resolveSingleModuleNameWithoutWatching(moduleName, containingFile) { + var _a, _b; const path = resolutionHost.toPath(containingFile); const resolutionsInFile = resolvedModuleNames.get(path); const resolution = resolutionsInFile == null ? void 0 : resolutionsInFile.get( @@ -124266,7 +125130,17 @@ ${lanes.join("\n")} ); if (resolution && !resolution.isInvalidated) return resolution; - return resolveModuleName2(moduleName, containingFile, resolutionHost.getCompilationSettings()); + const data = (_a = resolutionHost.beforeResolveSingleModuleNameWithoutWatching) == null ? void 0 : _a.call(resolutionHost, moduleResolutionCache); + const host = getModuleResolutionHost(resolutionHost); + const result = resolveModuleName( + moduleName, + containingFile, + resolutionHost.getCompilationSettings(), + host, + moduleResolutionCache + ); + (_b = resolutionHost.afterResolveSingleModuleNameWithoutWatching) == null ? void 0 : _b.call(resolutionHost, moduleResolutionCache, moduleName, containingFile, result, data); + return result; } function isNodeModulesAtTypesDirectory(dirPath) { return endsWith(dirPath, "/node_modules/@types"); @@ -124366,51 +125240,62 @@ ${lanes.join("\n")} return; } let locationToWatch = affectingLocation; + let isSymlink = false; + let symlinkWatcher; if (resolutionHost.realpath) { locationToWatch = resolutionHost.realpath(affectingLocation); if (affectingLocation !== locationToWatch) { - const fileWatcher2 = fileWatchesOfAffectingLocations.get(locationToWatch); - if (fileWatcher2) { - if (forResolution) - fileWatcher2.resolutions++; - else - fileWatcher2.files++; - fileWatcher2.paths.add(affectingLocation); - fileWatchesOfAffectingLocations.set(affectingLocation, fileWatcher2); - return; - } + isSymlink = true; + symlinkWatcher = fileWatchesOfAffectingLocations.get(locationToWatch); } } - const paths = /* @__PURE__ */ new Set(); - paths.add(locationToWatch); - let actualWatcher = canWatchAffectingLocation(resolutionHost.toPath(locationToWatch)) ? resolutionHost.watchAffectingFileLocation(locationToWatch, (fileName, eventKind) => { - cachedDirectoryStructureHost == null ? void 0 : cachedDirectoryStructureHost.addOrDeleteFile(fileName, resolutionHost.toPath(locationToWatch), eventKind); - const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); - paths.forEach((path) => { - if (watcher.resolutions) - (affectingPathChecks ?? (affectingPathChecks = /* @__PURE__ */ new Set())).add(path); - if (watcher.files) - (affectingPathChecksForFile ?? (affectingPathChecksForFile = /* @__PURE__ */ new Set())).add(path); - packageJsonMap == null ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path)); - }); - resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); - }) : noopFileWatcher; - const watcher = { - watcher: actualWatcher !== noopFileWatcher ? { - close: () => { - actualWatcher.close(); - actualWatcher = noopFileWatcher; - } - } : actualWatcher, - resolutions: forResolution ? 1 : 0, - files: forResolution ? 0 : 1, - paths - }; - fileWatchesOfAffectingLocations.set(locationToWatch, watcher); - if (affectingLocation !== locationToWatch) { - fileWatchesOfAffectingLocations.set(affectingLocation, watcher); - paths.add(affectingLocation); + const resolutions = forResolution ? 1 : 0; + const files = forResolution ? 0 : 1; + if (!isSymlink || !symlinkWatcher) { + const watcher = { + watcher: canWatchAffectingLocation(resolutionHost.toPath(locationToWatch)) ? resolutionHost.watchAffectingFileLocation(locationToWatch, (fileName, eventKind) => { + cachedDirectoryStructureHost == null ? void 0 : cachedDirectoryStructureHost.addOrDeleteFile(fileName, resolutionHost.toPath(locationToWatch), eventKind); + invalidateAffectingFileWatcher(locationToWatch, moduleResolutionCache.getPackageJsonInfoCache().getInternalMap()); + resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); + }) : noopFileWatcher, + resolutions: isSymlink ? 0 : resolutions, + files: isSymlink ? 0 : files, + symlinks: void 0 + }; + fileWatchesOfAffectingLocations.set(locationToWatch, watcher); + if (isSymlink) + symlinkWatcher = watcher; } + if (isSymlink) { + Debug.assert(!!symlinkWatcher); + const watcher = { + watcher: { + close: () => { + var _a; + const symlinkWatcher2 = fileWatchesOfAffectingLocations.get(locationToWatch); + if (((_a = symlinkWatcher2 == null ? void 0 : symlinkWatcher2.symlinks) == null ? void 0 : _a.delete(affectingLocation)) && !symlinkWatcher2.symlinks.size && !symlinkWatcher2.resolutions && !symlinkWatcher2.files) { + fileWatchesOfAffectingLocations.delete(locationToWatch); + symlinkWatcher2.watcher.close(); + } + } + }, + resolutions, + files, + symlinks: void 0 + }; + fileWatchesOfAffectingLocations.set(affectingLocation, watcher); + (symlinkWatcher.symlinks ?? (symlinkWatcher.symlinks = /* @__PURE__ */ new Set())).add(affectingLocation); + } + } + function invalidateAffectingFileWatcher(path, packageJsonMap) { + var _a; + const watcher = fileWatchesOfAffectingLocations.get(path); + if (watcher == null ? void 0 : watcher.resolutions) + (affectingPathChecks ?? (affectingPathChecks = /* @__PURE__ */ new Set())).add(path); + if (watcher == null ? void 0 : watcher.files) + (affectingPathChecksForFile ?? (affectingPathChecksForFile = /* @__PURE__ */ new Set())).add(path); + (_a = watcher == null ? void 0 : watcher.symlinks) == null ? void 0 : _a.forEach((path2) => invalidateAffectingFileWatcher(path2, packageJsonMap)); + packageJsonMap == null ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path)); } function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { const program = resolutionHost.getCurrentProgram(); @@ -124433,7 +125318,7 @@ ${lanes.join("\n")} directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive }); } } - function stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot) { + function stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot, syncDirWatcherRemove) { const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); const toWatch = getDirectoryToWatchFailedLookupLocation( failedLookupLocation, @@ -124448,12 +125333,12 @@ ${lanes.join("\n")} if (dirPath === rootPath) { removeAtRoot = true; } else { - removeDirectoryWatcher(dirPath); + removeDirectoryWatcher(dirPath, syncDirWatcherRemove); } } return removeAtRoot; } - function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) { + function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName, syncDirWatcherRemove) { Debug.checkDefined(resolution.files).delete(filePath); resolution.refCount--; if (resolution.refCount) { @@ -124471,13 +125356,13 @@ ${lanes.join("\n")} let removeAtRoot = false; if (failedLookupLocations) { for (const failedLookupLocation of failedLookupLocations) { - removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot); + removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot, syncDirWatcherRemove); } } if (node10Result) - removeAtRoot = stopWatchFailedLookupLocation(node10Result, removeAtRoot); + removeAtRoot = stopWatchFailedLookupLocation(node10Result, removeAtRoot, syncDirWatcherRemove); if (removeAtRoot) - removeDirectoryWatcher(rootPath); + removeDirectoryWatcher(rootPath, syncDirWatcherRemove); } else if (affectingLocations == null ? void 0 : affectingLocations.length) { resolutionsWithOnlyAffectingLocations.delete(resolution); } @@ -124485,12 +125370,16 @@ ${lanes.join("\n")} for (const affectingLocation of affectingLocations) { const watcher = fileWatchesOfAffectingLocations.get(affectingLocation); watcher.resolutions--; + if (syncDirWatcherRemove) + closeFileWatcherOfAffectingLocation(watcher, affectingLocation); } } } - function removeDirectoryWatcher(dirPath) { + function removeDirectoryWatcher(dirPath, syncDirWatcherRemove) { const dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); dirWatcher.refCount--; + if (syncDirWatcherRemove) + closeDirectoryWatchesOfFailedLookup(dirWatcher, dirPath); } function createDirectoryWatcher(directory, dirPath, nonRecursive) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, (fileOrDirectory) => { @@ -124501,10 +125390,17 @@ ${lanes.join("\n")} scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath); }, nonRecursive ? 0 /* None */ : 1 /* Recursive */); } - function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) { + function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName, syncDirWatcherRemove) { const resolutions = cache.get(filePath); if (resolutions) { - resolutions.forEach((resolution) => stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName)); + resolutions.forEach( + (resolution) => stopWatchFailedLookupLocationOfResolution( + resolution, + filePath, + getResolutionWithResolvedFileName, + syncDirWatcherRemove + ) + ); cache.delete(filePath); } } @@ -124519,9 +125415,9 @@ ${lanes.join("\n")} return; resolvedProjectReference.commandLine.fileNames.forEach((f) => removeResolutionsOfFile(resolutionHost.toPath(f))); } - function removeResolutionsOfFile(filePath) { - removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule2); - removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective2); + function removeResolutionsOfFile(filePath, syncDirWatcherRemove) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule, syncDirWatcherRemove); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective, syncDirWatcherRemove); } function invalidateResolutions(resolutions, canInvalidate) { if (!resolutions) @@ -124776,10 +125672,7 @@ ${lanes.join("\n")} if (fileName === void 0) { return void 0; } - const diagnosticForFileName = find( - diagnostics, - (diagnostic) => diagnostic.file !== void 0 && diagnostic.file.fileName === fileName - ); + const diagnosticForFileName = find(diagnostics, (diagnostic) => diagnostic.file !== void 0 && diagnostic.file.fileName === fileName); if (diagnosticForFileName !== void 0) { const { line } = getLineAndCharacterOfPosition(diagnosticForFileName.file, diagnosticForFileName.start); return { @@ -124947,7 +125840,7 @@ ${lanes.join("\n")} var _a, _b; const options = program.getCompilerOptions(); if (isReferencedFile(reason)) { - const referenceLocation = getReferencedFileLocation((path) => program.getSourceFileByPath(path), reason); + const referenceLocation = getReferencedFileLocation(program, reason); const referenceText = isReferenceFileLocation(referenceLocation) ? referenceLocation.file.text.substring(referenceLocation.pos, referenceLocation.end) : `"${referenceLocation.text}"`; let message; Debug.assert(isReferenceFileLocation(referenceLocation) || reason.kind === 3 /* Import */, "Only synthetic references are imports"); @@ -125172,7 +126065,8 @@ ${lanes.join("\n")} getEnvironmentVariable: maybeBind(host, host.getEnvironmentVariable) || (() => ""), createHash: maybeBind(host, host.createHash), readDirectory: maybeBind(host, host.readDirectory), - storeFilesChangingSignatureDuringEmit: host.storeFilesChangingSignatureDuringEmit + storeFilesChangingSignatureDuringEmit: host.storeFilesChangingSignatureDuringEmit, + jsDocParsingMode: host.jsDocParsingMode }; return compilerHost; } @@ -125430,7 +126324,7 @@ ${lanes.join("\n")} } function createWatchProgram(host) { let builderProgram; - let reloadLevel; + let updateLevel; let missingFilesMap; let watchedWildcardDirectories; let timerToUpdateProgram; @@ -125523,7 +126417,7 @@ ${lanes.join("\n")} watchConfigFileWildCardDirectories(); if (configFileName) updateExtendedConfigFilesWatches(toPath3(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile); - return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames, close }; + return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close, getResolutionCache } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames, close, getResolutionCache }; function close() { clearInvalidateResolutionsOfFailedLookupLocations(); resolutionCache.clear(); @@ -125563,6 +126457,9 @@ ${lanes.join("\n")} parsedConfigs = void 0; } } + function getResolutionCache() { + return resolutionCache; + } function getCurrentBuilderProgram() { return builderProgram; } @@ -125786,7 +126683,7 @@ ${lanes.join("\n")} } function scheduleProgramReload() { Debug.assert(!!configFileName); - reloadLevel = 2 /* Full */; + updateLevel = 2 /* Full */; scheduleProgramUpdate(); } function updateProgramWithWatchStatus() { @@ -125796,8 +126693,8 @@ ${lanes.join("\n")} } function updateProgram() { var _a, _b, _c, _d; - switch (reloadLevel) { - case 1 /* Partial */: + switch (updateLevel) { + case 1 /* RootNamesAndUpdate */: (_a = perfLogger) == null ? void 0 : _a.logStartUpdateProgram("PartialConfigReload"); reloadFileNamesFromConfigFile(); break; @@ -125817,7 +126714,7 @@ ${lanes.join("\n")} writeLog("Reloading new file names and options"); Debug.assert(compilerOptions); Debug.assert(configFileName); - reloadLevel = 0 /* None */; + updateLevel = 0 /* Update */; rootFileNames = getFileNamesFromConfigSpecs(compilerOptions.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions); if (updateErrorForNoInputFiles(rootFileNames, getNormalizedAbsolutePath(configFileName, currentDirectory), compilerOptions.configFile.configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; @@ -125827,7 +126724,7 @@ ${lanes.join("\n")} function reloadConfigFile() { Debug.assert(configFileName); writeLog(`Reloading config file: ${configFileName}`); - reloadLevel = 0 /* None */; + updateLevel = 0 /* Update */; if (cachedDirectoryStructureHost) { cachedDirectoryStructureHost.clearCache(); } @@ -125839,14 +126736,16 @@ ${lanes.join("\n")} } function parseConfigFile2() { Debug.assert(configFileName); - setConfigFileParsingResult(getParsedCommandLineOfConfigFile( - configFileName, - optionsToExtendForConfigFile, - parseConfigFileHost, - extendedConfigCache || (extendedConfigCache = /* @__PURE__ */ new Map()), - watchOptionsToExtend, - extraFileExtensions - )); + setConfigFileParsingResult( + getParsedCommandLineOfConfigFile( + configFileName, + optionsToExtendForConfigFile, + parseConfigFileHost, + extendedConfigCache || (extendedConfigCache = /* @__PURE__ */ new Map()), + watchOptionsToExtend, + extraFileExtensions + ) + ); } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -125862,9 +126761,9 @@ ${lanes.join("\n")} const configPath = toPath3(configFileName2); let config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); if (config) { - if (!config.reloadLevel) + if (!config.updateLevel) return config.parsedCommandLine; - if (config.parsedCommandLine && config.reloadLevel === 1 /* Partial */ && !host.getParsedCommandLine) { + if (config.parsedCommandLine && config.updateLevel === 1 /* RootNamesAndUpdate */ && !host.getParsedCommandLine) { writeLog("Reloading new file names and options"); Debug.assert(compilerOptions); const fileNames = getFileNamesFromConfigSpecs( @@ -125874,7 +126773,7 @@ ${lanes.join("\n")} parseConfigFileHost ); config.parsedCommandLine = { ...config.parsedCommandLine, fileNames }; - config.reloadLevel = void 0; + config.updateLevel = void 0; return config.parsedCommandLine; } } @@ -125882,7 +126781,7 @@ ${lanes.join("\n")} const parsedCommandLine = host.getParsedCommandLine ? host.getParsedCommandLine(configFileName2) : getParsedCommandLineFromConfigFileHost(configFileName2); if (config) { config.parsedCommandLine = parsedCommandLine; - config.reloadLevel = void 0; + config.updateLevel = void 0; } else { (parsedConfigs || (parsedConfigs = /* @__PURE__ */ new Map())).set(configPath, config = { parsedCommandLine }); } @@ -125979,8 +126878,8 @@ ${lanes.join("\n")} toPath: toPath3 })) return; - if (reloadLevel !== 2 /* Full */) { - reloadLevel = 1 /* Partial */; + if (updateLevel !== 2 /* Full */) { + updateLevel = 1 /* RootNamesAndUpdate */; scheduleProgramUpdate(); } }, @@ -126006,11 +126905,11 @@ ${lanes.join("\n")} return; projects.forEach((projectPath) => { if (configFileName && toPath3(configFileName) === projectPath) { - reloadLevel = 2 /* Full */; + updateLevel = 2 /* Full */; } else { const config = parsedConfigs == null ? void 0 : parsedConfigs.get(projectPath); if (config) - config.reloadLevel = 2 /* Full */; + config.updateLevel = 2 /* Full */; resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); } scheduleProgramUpdate(); @@ -126031,7 +126930,7 @@ ${lanes.join("\n")} updateCachedSystemWithFile(configFileName2, configPath, eventKind); const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); if (config) - config.reloadLevel = 2 /* Full */; + config.updateLevel = 2 /* Full */; resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); scheduleProgramUpdate(); }, @@ -126069,8 +126968,8 @@ ${lanes.join("\n")} toPath: toPath3 })) return; - if (config.reloadLevel !== 2 /* Full */) { - config.reloadLevel = 1 /* Partial */; + if (config.updateLevel !== 2 /* Full */) { + config.updateLevel = 1 /* RootNamesAndUpdate */; scheduleProgramUpdate(); } }, @@ -126246,7 +127145,8 @@ ${lanes.join("\n")} compilerHost.getCanonicalFileName, /*options*/ void 0, - moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache() + moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), + moduleResolutionCache == null ? void 0 : moduleResolutionCache.optionsToRedirectsKey ); compilerHost.resolveTypeReferenceDirectiveReferences = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache( typeDirectiveNames, @@ -126543,12 +127443,12 @@ ${lanes.join("\n")} state.projectStatus.delete(resolved); state.diagnostics.delete(resolved); } - function addProjToQueue({ projectPendingBuild }, proj, reloadLevel) { + function addProjToQueue({ projectPendingBuild }, proj, updateLevel) { const value = projectPendingBuild.get(proj); if (value === void 0) { - projectPendingBuild.set(proj, reloadLevel); - } else if (value < reloadLevel) { - projectPendingBuild.set(proj, reloadLevel); + projectPendingBuild.set(proj, updateLevel); + } else if (value < updateLevel) { + projectPendingBuild.set(proj, updateLevel); } } function setupInitialBuild(state, cancellationToken) { @@ -126562,7 +127462,7 @@ ${lanes.join("\n")} buildOrder.forEach( (configFileName) => state.projectPendingBuild.set( toResolvedConfigFilePath(state, configFileName), - 0 /* None */ + 0 /* Update */ ) ); if (cancellationToken) { @@ -126715,10 +127615,13 @@ ${lanes.join("\n")} config.projectReferences ); if (state.watch) { - state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && map( - state.moduleResolutionCache.getPackageJsonInfoCache().entries(), - ([path, data]) => [state.host.realpath && data ? toPath2(state, state.host.realpath(path)) : path, data] - )); + state.lastCachedPackageJsonLookups.set( + projectPath, + state.moduleResolutionCache && map( + state.moduleResolutionCache.getPackageJsonInfoCache().entries(), + ([path, data]) => [state.host.realpath && data ? toPath2(state, state.host.realpath(path)) : path, data] + ) + ); state.builderPrograms.set(projectPath, program); } step++; @@ -126995,8 +127898,8 @@ ${lanes.join("\n")} for (let projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) { const project = buildOrder[projectIndex]; const projectPath = toResolvedConfigFilePath(state, project); - const reloadLevel = state.projectPendingBuild.get(projectPath); - if (reloadLevel === void 0) + const updateLevel = state.projectPendingBuild.get(projectPath); + if (updateLevel === void 0) continue; if (reportQueue) { reportQueue = false; @@ -127008,13 +127911,13 @@ ${lanes.join("\n")} projectPendingBuild.delete(projectPath); continue; } - if (reloadLevel === 2 /* Full */) { + if (updateLevel === 2 /* Full */) { watchConfigFile(state, project, projectPath, config); watchExtendedConfigFiles(state, projectPath, config); watchWildCardDirectories(state, project, projectPath, config); watchInputFiles(state, project, projectPath, config); watchPackageJsonFiles(state, project, projectPath, config); - } else if (reloadLevel === 1 /* Partial */) { + } else if (updateLevel === 1 /* RootNamesAndUpdate */) { config.fileNames = getFileNamesFromConfigSpecs(config.options.configFile.configFileSpecs, getDirectoryPath(project), config.options, state.parseConfigFileHost); updateErrorForNoInputFiles(config.fileNames, project, config.options.configFile.configFileSpecs, config.errors, canJsonReportNoInputFiles(config.raw)); watchInputFiles(state, project, projectPath, config); @@ -127601,7 +128504,7 @@ ${lanes.join("\n")} break; } } - addProjToQueue(state, nextProjectPath, 0 /* None */); + addProjToQueue(state, nextProjectPath, 0 /* Update */); break; } } @@ -127670,7 +128573,7 @@ ${lanes.join("\n")} filesToDelete.push(output); } else { host.deleteFile(output); - invalidateProject(state, resolvedPath, 0 /* None */); + invalidateProject(state, resolvedPath, 0 /* Update */); } } } @@ -127681,22 +128584,22 @@ ${lanes.join("\n")} } return 0 /* Success */; } - function invalidateProject(state, resolved, reloadLevel) { - if (state.host.getParsedCommandLine && reloadLevel === 1 /* Partial */) { - reloadLevel = 2 /* Full */; + function invalidateProject(state, resolved, updateLevel) { + if (state.host.getParsedCommandLine && updateLevel === 1 /* RootNamesAndUpdate */) { + updateLevel = 2 /* Full */; } - if (reloadLevel === 2 /* Full */) { + if (updateLevel === 2 /* Full */) { state.configFileCache.delete(resolved); state.buildOrder = void 0; } state.needsSummary = true; clearProjectStatus(state, resolved); - addProjToQueue(state, resolved, reloadLevel); + addProjToQueue(state, resolved, updateLevel); enableCache(state); } - function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) { + function invalidateProjectAndScheduleBuilds(state, resolvedPath, updateLevel) { state.reportFileChangeDetected = true; - invalidateProject(state, resolvedPath, reloadLevel); + invalidateProject(state, resolvedPath, updateLevel); scheduleBuildInvalidatedProject( state, 250, @@ -127772,15 +128675,18 @@ ${lanes.join("\n")} function watchConfigFile(state, resolved, resolvedPath, parsed) { if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return; - state.allWatchedConfigFiles.set(resolvedPath, watchFile( - state, - resolved, - () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 2 /* Full */), - 2e3 /* High */, - parsed == null ? void 0 : parsed.watchOptions, - WatchType.ConfigFile, - resolved - )); + state.allWatchedConfigFiles.set( + resolvedPath, + watchFile( + state, + resolved, + () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 2 /* Full */), + 2e3 /* High */, + parsed == null ? void 0 : parsed.watchOptions, + WatchType.ConfigFile, + resolved + ) + ); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { updateSharedExtendedConfigFileWatcher( @@ -127824,7 +128730,7 @@ ${lanes.join("\n")} toPath: (fileName) => toPath2(state, fileName) })) return; - invalidateProjectAndScheduleBuilds(state, resolvedPath, 1 /* Partial */); + invalidateProjectAndScheduleBuilds(state, resolvedPath, 1 /* RootNamesAndUpdate */); }, flags, parsed == null ? void 0 : parsed.watchOptions, @@ -127843,7 +128749,7 @@ ${lanes.join("\n")} createNewValue: (_path, input) => watchFile( state, input, - () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* None */), + () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* Update */), 250 /* Low */, parsed == null ? void 0 : parsed.watchOptions, WatchType.SourceFile, @@ -127863,7 +128769,7 @@ ${lanes.join("\n")} createNewValue: (path, _input) => watchFile( state, path, - () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* None */), + () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* Update */), 2e3 /* High */, parsed == null ? void 0 : parsed.watchOptions, WatchType.PackageJson, @@ -127934,7 +128840,7 @@ ${lanes.join("\n")} const configFilePath = toResolvedConfigFilePath(state, configFileName); return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath); }, - invalidateProject: (configFilePath, reloadLevel) => invalidateProject(state, configFilePath, reloadLevel || 0 /* None */), + invalidateProject: (configFilePath, updateLevel) => invalidateProject(state, configFilePath, updateLevel || 0 /* Update */), close: () => stopWatching(state) }; } @@ -128228,6 +129134,66 @@ ${lanes.join("\n")} } }); + // src/jsTyping/shared.ts + function hasArgument(argumentName) { + return sys.args.includes(argumentName); + } + function findArgument(argumentName) { + const index = sys.args.indexOf(argumentName); + return index >= 0 && index < sys.args.length - 1 ? sys.args[index + 1] : void 0; + } + function nowString() { + const d = /* @__PURE__ */ new Date(); + return `${d.getHours().toString().padStart(2, "0")}:${d.getMinutes().toString().padStart(2, "0")}:${d.getSeconds().toString().padStart(2, "0")}.${d.getMilliseconds().toString().padStart(3, "0")}`; + } + function indent2(str) { + return indentStr + str.replace(/\n/g, indentStr); + } + function stringifyIndented(json) { + return indent2(JSON.stringify(json, void 0, 2)); + } + var ActionSet, ActionInvalidate, ActionPackageInstalled, EventTypesRegistry, EventBeginInstallTypes, EventEndInstallTypes, EventInitializationFailed, ActionWatchTypingLocations, Arguments, indentStr; + var init_shared = __esm({ + "src/jsTyping/shared.ts"() { + "use strict"; + init_ts3(); + ActionSet = "action::set"; + ActionInvalidate = "action::invalidate"; + ActionPackageInstalled = "action::packageInstalled"; + EventTypesRegistry = "event::typesRegistry"; + EventBeginInstallTypes = "event::beginInstallTypes"; + EventEndInstallTypes = "event::endInstallTypes"; + EventInitializationFailed = "event::initializationFailed"; + ActionWatchTypingLocations = "action::watchTypingLocations"; + ((Arguments2) => { + Arguments2.GlobalCacheLocation = "--globalTypingsCacheLocation"; + Arguments2.LogFile = "--logFile"; + Arguments2.EnableTelemetry = "--enableTelemetry"; + Arguments2.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments2.TypesMapLocation = "--typesMapLocation"; + Arguments2.NpmLocation = "--npmLocation"; + Arguments2.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation"; + })(Arguments || (Arguments = {})); + indentStr = "\n "; + } + }); + + // src/jsTyping/types.ts + var init_types2 = __esm({ + "src/jsTyping/types.ts"() { + "use strict"; + } + }); + + // src/jsTyping/_namespaces/ts.server.ts + var init_ts_server = __esm({ + "src/jsTyping/_namespaces/ts.server.ts"() { + "use strict"; + init_shared(); + init_types2(); + } + }); + // src/jsTyping/jsTyping.ts function isTypingUpToDate(cachedTyping, availableTypingVersions) { const availableVersion = new Version(getProperty(availableTypingVersions, `ts${versionMajorMinor}`) || getProperty(availableTypingVersions, "latest")); @@ -128282,21 +129248,21 @@ ${lanes.join("\n")} ); addInferredTypings(module2, "Inferred typings from unresolved imports"); } - packageNameToTypingLocation.forEach((typing, name) => { - const registryEntry = typesRegistry.get(name); - if (inferredTypings.has(name) && inferredTypings.get(name) === void 0 && registryEntry !== void 0 && isTypingUpToDate(typing, registryEntry)) { - inferredTypings.set(name, typing.typingLocation); - } - }); for (const excludeTypingName of exclude) { const didDelete = inferredTypings.delete(excludeTypingName); if (didDelete && log) log(`Typing for ${excludeTypingName} is in exclude list, will be ignored.`); } + packageNameToTypingLocation.forEach((typing, name) => { + const registryEntry = typesRegistry.get(name); + if (inferredTypings.get(name) === false && registryEntry !== void 0 && isTypingUpToDate(typing, registryEntry)) { + inferredTypings.set(name, typing.typingLocation); + } + }); const newTypingNames = []; const cachedTypingPaths = []; inferredTypings.forEach((inferred, typing) => { - if (inferred !== void 0) { + if (inferred) { cachedTypingPaths.push(inferred); } else { newTypingNames.push(typing); @@ -128304,11 +129270,11 @@ ${lanes.join("\n")} }); const result = { cachedTypingPaths, newTypingNames, filesToWatch }; if (log) - log(`Result: ${JSON.stringify(result)}`); + log(`Finished typings discovery:${stringifyIndented(result)}`); return result; function addInferredTyping(typingName) { if (!inferredTypings.has(typingName)) { - inferredTypings.set(typingName, void 0); + inferredTypings.set(typingName, false); } } function addInferredTypings(typingNames, message) { @@ -128475,6 +129441,7 @@ ${lanes.join("\n")} "src/jsTyping/jsTyping.ts"() { "use strict"; init_ts3(); + init_ts_server(); unprefixedNodeCoreModuleList = [ "assert", "assert/strict", @@ -128562,74 +129529,6 @@ ${lanes.join("\n")} } }); - // src/jsTyping/shared.ts - function hasArgument(argumentName) { - return sys.args.indexOf(argumentName) >= 0; - } - function findArgument(argumentName) { - const index = sys.args.indexOf(argumentName); - return index >= 0 && index < sys.args.length - 1 ? sys.args[index + 1] : void 0; - } - function nowString() { - const d = /* @__PURE__ */ new Date(); - return `${padLeft(d.getHours().toString(), 2, "0")}:${padLeft(d.getMinutes().toString(), 2, "0")}:${padLeft(d.getSeconds().toString(), 2, "0")}.${padLeft(d.getMilliseconds().toString(), 3, "0")}`; - } - var ActionSet, ActionInvalidate, ActionPackageInstalled, EventTypesRegistry, EventBeginInstallTypes, EventEndInstallTypes, EventInitializationFailed, ActionWatchTypingLocations, Arguments; - var init_shared = __esm({ - "src/jsTyping/shared.ts"() { - "use strict"; - init_ts3(); - ActionSet = "action::set"; - ActionInvalidate = "action::invalidate"; - ActionPackageInstalled = "action::packageInstalled"; - EventTypesRegistry = "event::typesRegistry"; - EventBeginInstallTypes = "event::beginInstallTypes"; - EventEndInstallTypes = "event::endInstallTypes"; - EventInitializationFailed = "event::initializationFailed"; - ActionWatchTypingLocations = "action::watchTypingLocations"; - ((Arguments2) => { - Arguments2.GlobalCacheLocation = "--globalTypingsCacheLocation"; - Arguments2.LogFile = "--logFile"; - Arguments2.EnableTelemetry = "--enableTelemetry"; - Arguments2.TypingSafeListLocation = "--typingSafeListLocation"; - Arguments2.TypesMapLocation = "--typesMapLocation"; - Arguments2.NpmLocation = "--npmLocation"; - Arguments2.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation"; - })(Arguments || (Arguments = {})); - } - }); - - // src/jsTyping/types.ts - var init_types2 = __esm({ - "src/jsTyping/types.ts"() { - "use strict"; - } - }); - - // src/jsTyping/_namespaces/ts.server.ts - var ts_server_exports = {}; - __export(ts_server_exports, { - ActionInvalidate: () => ActionInvalidate, - ActionPackageInstalled: () => ActionPackageInstalled, - ActionSet: () => ActionSet, - ActionWatchTypingLocations: () => ActionWatchTypingLocations, - Arguments: () => Arguments, - EventBeginInstallTypes: () => EventBeginInstallTypes, - EventEndInstallTypes: () => EventEndInstallTypes, - EventInitializationFailed: () => EventInitializationFailed, - EventTypesRegistry: () => EventTypesRegistry, - findArgument: () => findArgument, - hasArgument: () => hasArgument, - nowString: () => nowString - }); - var init_ts_server = __esm({ - "src/jsTyping/_namespaces/ts.server.ts"() { - "use strict"; - init_shared(); - init_types2(); - } - }); - // src/jsTyping/_namespaces/ts.ts var init_ts3 = __esm({ "src/jsTyping/_namespaces/ts.ts"() { @@ -128712,22 +129611,22 @@ ${lanes.join("\n")} return LanguageServiceMode2; })(LanguageServiceMode || {}); emptyOptions = {}; - SemanticClassificationFormat = /* @__PURE__ */ ((SemanticClassificationFormat3) => { - SemanticClassificationFormat3["Original"] = "original"; - SemanticClassificationFormat3["TwentyTwenty"] = "2020"; - return SemanticClassificationFormat3; + SemanticClassificationFormat = /* @__PURE__ */ ((SemanticClassificationFormat2) => { + SemanticClassificationFormat2["Original"] = "original"; + SemanticClassificationFormat2["TwentyTwenty"] = "2020"; + return SemanticClassificationFormat2; })(SemanticClassificationFormat || {}); - OrganizeImportsMode = /* @__PURE__ */ ((OrganizeImportsMode2) => { - OrganizeImportsMode2["All"] = "All"; - OrganizeImportsMode2["SortAndCombine"] = "SortAndCombine"; - OrganizeImportsMode2["RemoveUnused"] = "RemoveUnused"; - return OrganizeImportsMode2; + OrganizeImportsMode = /* @__PURE__ */ ((OrganizeImportsMode3) => { + OrganizeImportsMode3["All"] = "All"; + OrganizeImportsMode3["SortAndCombine"] = "SortAndCombine"; + OrganizeImportsMode3["RemoveUnused"] = "RemoveUnused"; + return OrganizeImportsMode3; })(OrganizeImportsMode || {}); - CompletionTriggerKind = /* @__PURE__ */ ((CompletionTriggerKind2) => { - CompletionTriggerKind2[CompletionTriggerKind2["Invoked"] = 1] = "Invoked"; - CompletionTriggerKind2[CompletionTriggerKind2["TriggerCharacter"] = 2] = "TriggerCharacter"; - CompletionTriggerKind2[CompletionTriggerKind2["TriggerForIncompleteCompletions"] = 3] = "TriggerForIncompleteCompletions"; - return CompletionTriggerKind2; + CompletionTriggerKind = /* @__PURE__ */ ((CompletionTriggerKind4) => { + CompletionTriggerKind4[CompletionTriggerKind4["Invoked"] = 1] = "Invoked"; + CompletionTriggerKind4[CompletionTriggerKind4["TriggerCharacter"] = 2] = "TriggerCharacter"; + CompletionTriggerKind4[CompletionTriggerKind4["TriggerForIncompleteCompletions"] = 3] = "TriggerForIncompleteCompletions"; + return CompletionTriggerKind4; })(CompletionTriggerKind || {}); InlayHintKind = /* @__PURE__ */ ((InlayHintKind2) => { InlayHintKind2["Type"] = "Type"; @@ -128742,17 +129641,17 @@ ${lanes.join("\n")} HighlightSpanKind2["writtenReference"] = "writtenReference"; return HighlightSpanKind2; })(HighlightSpanKind || {}); - IndentStyle = /* @__PURE__ */ ((IndentStyle2) => { - IndentStyle2[IndentStyle2["None"] = 0] = "None"; - IndentStyle2[IndentStyle2["Block"] = 1] = "Block"; - IndentStyle2[IndentStyle2["Smart"] = 2] = "Smart"; - return IndentStyle2; + IndentStyle = /* @__PURE__ */ ((IndentStyle3) => { + IndentStyle3[IndentStyle3["None"] = 0] = "None"; + IndentStyle3[IndentStyle3["Block"] = 1] = "Block"; + IndentStyle3[IndentStyle3["Smart"] = 2] = "Smart"; + return IndentStyle3; })(IndentStyle || {}); - SemicolonPreference = /* @__PURE__ */ ((SemicolonPreference2) => { - SemicolonPreference2["Ignore"] = "ignore"; - SemicolonPreference2["Insert"] = "insert"; - SemicolonPreference2["Remove"] = "remove"; - return SemicolonPreference2; + SemicolonPreference = /* @__PURE__ */ ((SemicolonPreference3) => { + SemicolonPreference3["Ignore"] = "ignore"; + SemicolonPreference3["Insert"] = "insert"; + SemicolonPreference3["Remove"] = "remove"; + return SemicolonPreference3; })(SemicolonPreference || {}); testFormatSettings = getDefaultFormatCodeSettings("\n"); SymbolDisplayPartKind = /* @__PURE__ */ ((SymbolDisplayPartKind2) => { @@ -128806,15 +129705,15 @@ ${lanes.join("\n")} OutputFileType2[OutputFileType2["Declaration"] = 2] = "Declaration"; return OutputFileType2; })(OutputFileType || {}); - EndOfLineState = /* @__PURE__ */ ((EndOfLineState3) => { - EndOfLineState3[EndOfLineState3["None"] = 0] = "None"; - EndOfLineState3[EndOfLineState3["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; - EndOfLineState3[EndOfLineState3["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; - EndOfLineState3[EndOfLineState3["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral"; - EndOfLineState3[EndOfLineState3["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate"; - EndOfLineState3[EndOfLineState3["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail"; - EndOfLineState3[EndOfLineState3["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; - return EndOfLineState3; + EndOfLineState = /* @__PURE__ */ ((EndOfLineState2) => { + EndOfLineState2[EndOfLineState2["None"] = 0] = "None"; + EndOfLineState2[EndOfLineState2["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; + EndOfLineState2[EndOfLineState2["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; + EndOfLineState2[EndOfLineState2["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral"; + EndOfLineState2[EndOfLineState2["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate"; + EndOfLineState2[EndOfLineState2["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail"; + EndOfLineState2[EndOfLineState2["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; + return EndOfLineState2; })(EndOfLineState || {}); TokenClass = /* @__PURE__ */ ((TokenClass2) => { TokenClass2[TokenClass2["Punctuation"] = 0] = "Punctuation"; @@ -128924,33 +129823,33 @@ ${lanes.join("\n")} ClassificationTypeNames2["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value"; return ClassificationTypeNames2; })(ClassificationTypeNames || {}); - ClassificationType = /* @__PURE__ */ ((ClassificationType2) => { - ClassificationType2[ClassificationType2["comment"] = 1] = "comment"; - ClassificationType2[ClassificationType2["identifier"] = 2] = "identifier"; - ClassificationType2[ClassificationType2["keyword"] = 3] = "keyword"; - ClassificationType2[ClassificationType2["numericLiteral"] = 4] = "numericLiteral"; - ClassificationType2[ClassificationType2["operator"] = 5] = "operator"; - ClassificationType2[ClassificationType2["stringLiteral"] = 6] = "stringLiteral"; - ClassificationType2[ClassificationType2["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; - ClassificationType2[ClassificationType2["whiteSpace"] = 8] = "whiteSpace"; - ClassificationType2[ClassificationType2["text"] = 9] = "text"; - ClassificationType2[ClassificationType2["punctuation"] = 10] = "punctuation"; - ClassificationType2[ClassificationType2["className"] = 11] = "className"; - ClassificationType2[ClassificationType2["enumName"] = 12] = "enumName"; - ClassificationType2[ClassificationType2["interfaceName"] = 13] = "interfaceName"; - ClassificationType2[ClassificationType2["moduleName"] = 14] = "moduleName"; - ClassificationType2[ClassificationType2["typeParameterName"] = 15] = "typeParameterName"; - ClassificationType2[ClassificationType2["typeAliasName"] = 16] = "typeAliasName"; - ClassificationType2[ClassificationType2["parameterName"] = 17] = "parameterName"; - ClassificationType2[ClassificationType2["docCommentTagName"] = 18] = "docCommentTagName"; - ClassificationType2[ClassificationType2["jsxOpenTagName"] = 19] = "jsxOpenTagName"; - ClassificationType2[ClassificationType2["jsxCloseTagName"] = 20] = "jsxCloseTagName"; - ClassificationType2[ClassificationType2["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; - ClassificationType2[ClassificationType2["jsxAttribute"] = 22] = "jsxAttribute"; - ClassificationType2[ClassificationType2["jsxText"] = 23] = "jsxText"; - ClassificationType2[ClassificationType2["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; - ClassificationType2[ClassificationType2["bigintLiteral"] = 25] = "bigintLiteral"; - return ClassificationType2; + ClassificationType = /* @__PURE__ */ ((ClassificationType3) => { + ClassificationType3[ClassificationType3["comment"] = 1] = "comment"; + ClassificationType3[ClassificationType3["identifier"] = 2] = "identifier"; + ClassificationType3[ClassificationType3["keyword"] = 3] = "keyword"; + ClassificationType3[ClassificationType3["numericLiteral"] = 4] = "numericLiteral"; + ClassificationType3[ClassificationType3["operator"] = 5] = "operator"; + ClassificationType3[ClassificationType3["stringLiteral"] = 6] = "stringLiteral"; + ClassificationType3[ClassificationType3["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; + ClassificationType3[ClassificationType3["whiteSpace"] = 8] = "whiteSpace"; + ClassificationType3[ClassificationType3["text"] = 9] = "text"; + ClassificationType3[ClassificationType3["punctuation"] = 10] = "punctuation"; + ClassificationType3[ClassificationType3["className"] = 11] = "className"; + ClassificationType3[ClassificationType3["enumName"] = 12] = "enumName"; + ClassificationType3[ClassificationType3["interfaceName"] = 13] = "interfaceName"; + ClassificationType3[ClassificationType3["moduleName"] = 14] = "moduleName"; + ClassificationType3[ClassificationType3["typeParameterName"] = 15] = "typeParameterName"; + ClassificationType3[ClassificationType3["typeAliasName"] = 16] = "typeAliasName"; + ClassificationType3[ClassificationType3["parameterName"] = 17] = "parameterName"; + ClassificationType3[ClassificationType3["docCommentTagName"] = 18] = "docCommentTagName"; + ClassificationType3[ClassificationType3["jsxOpenTagName"] = 19] = "jsxOpenTagName"; + ClassificationType3[ClassificationType3["jsxCloseTagName"] = 20] = "jsxCloseTagName"; + ClassificationType3[ClassificationType3["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; + ClassificationType3[ClassificationType3["jsxAttribute"] = 22] = "jsxAttribute"; + ClassificationType3[ClassificationType3["jsxText"] = 23] = "jsxText"; + ClassificationType3[ClassificationType3["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + ClassificationType3[ClassificationType3["bigintLiteral"] = 25] = "bigintLiteral"; + return ClassificationType3; })(ClassificationType || {}); } }); @@ -129287,7 +130186,7 @@ ${lanes.join("\n")} case 306 /* EnumMember */: return "enum member" /* enumMemberElement */; case 169 /* Parameter */: - return hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + return hasSyntacticModifier(node, 31 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; case 271 /* ImportEqualsDeclaration */: case 276 /* ImportSpecifier */: case 281 /* ExportSpecifier */: @@ -130190,19 +131089,19 @@ ${lanes.join("\n")} function getNodeModifiers(node, excludeFlags = 0 /* None */) { const result = []; const flags = isDeclaration(node) ? getCombinedNodeFlagsAlwaysIncludeJSDoc(node) & ~excludeFlags : 0 /* None */; - if (flags & 8 /* Private */) + if (flags & 2 /* Private */) result.push("private" /* privateMemberModifier */); - if (flags & 16 /* Protected */) + if (flags & 4 /* Protected */) result.push("protected" /* protectedMemberModifier */); - if (flags & 4 /* Public */) + if (flags & 1 /* Public */) result.push("public" /* publicMemberModifier */); - if (flags & 32 /* Static */ || isClassStaticBlockDeclaration(node)) + if (flags & 256 /* Static */ || isClassStaticBlockDeclaration(node)) result.push("static" /* staticModifier */); - if (flags & 256 /* Abstract */) + if (flags & 64 /* Abstract */) result.push("abstract" /* abstractModifier */); - if (flags & 1 /* Export */) + if (flags & 32 /* Export */) result.push("export" /* exportedModifier */); - if (flags & 8192 /* Deprecated */) + if (flags & 65536 /* Deprecated */) result.push("deprecated" /* deprecatedModifier */); if (node.flags & 33554432 /* Ambient */) result.push("declare" /* ambientModifier */); @@ -130410,7 +131309,7 @@ ${lanes.join("\n")} void 0, defaultImport || namedImports ? factory.createImportClause(!!isTypeOnly, defaultImport, namedImports && namedImports.length ? factory.createNamedImports(namedImports) : void 0) : void 0, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier, - /*assertClause*/ + /*attributes*/ void 0 ); } @@ -130593,7 +131492,7 @@ ${lanes.join("\n")} const absoluteMaximumLength = defaultMaximumTruncationLength * 10; let displayParts; let lineStart; - let indent2; + let indent3; let length2; resetWriter(); const unknownWrite = (text) => writeKind(text, 17 /* text */); @@ -130629,12 +131528,12 @@ ${lanes.join("\n")} hasTrailingWhitespace: () => false, hasTrailingComment: () => false, rawWrite: notImplemented, - getIndent: () => indent2, + getIndent: () => indent3, increaseIndent: () => { - indent2++; + indent3++; }, decreaseIndent: () => { - indent2--; + indent3--; }, clear: resetWriter }; @@ -130642,7 +131541,7 @@ ${lanes.join("\n")} if (length2 > absoluteMaximumLength) return; if (lineStart) { - const indentString = getIndentString(indent2); + const indentString = getIndentString(indent3); if (indentString) { length2 += indentString.length; displayParts.push(displayPart(indentString, 16 /* space */)); @@ -130674,7 +131573,7 @@ ${lanes.join("\n")} function resetWriter() { displayParts = []; lineStart = true; - indent2 = 0; + indent3 = 0; length2 = 0; } } @@ -131048,7 +131947,7 @@ ${lanes.join("\n")} return idx === -1 ? -1 : idx + 1; } function needsParentheses(expression) { - return isBinaryExpression(expression) && expression.operatorToken.kind === 28 /* CommaToken */ || isObjectLiteralExpression(expression) || isAsExpression(expression) && isObjectLiteralExpression(expression.expression); + return isBinaryExpression(expression) && expression.operatorToken.kind === 28 /* CommaToken */ || isObjectLiteralExpression(expression) || (isAsExpression(expression) || isSatisfiesExpression(expression)) && isObjectLiteralExpression(expression.expression); } function getContextualTypeFromParent(node, checker, contextFlags) { const parent2 = walkUpParenthesizedExpressions(node.parent); @@ -131407,7 +132306,7 @@ ${lanes.join("\n")} return false; } function getNodeModulesPackageNameFromFileName(importedFileName, moduleSpecifierResolutionHost) { - if (!stringContains(importedFileName, "node_modules")) { + if (!importedFileName.includes("node_modules")) { return void 0; } const specifier = ts_moduleSpecifiers_exports.getNodeModulesPackageName( @@ -131580,7 +132479,7 @@ ${lanes.join("\n")} return isInJSFile(declaration) || !findAncestor(declaration, (d) => isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); } function isDeprecatedDeclaration(decl) { - return !!(getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & 8192 /* Deprecated */); + return !!(getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & 65536 /* Deprecated */); } function shouldUseUriStyleNodeCoreModules(file, program) { const decisionFromFile = firstDefined(file.imports, (node) => { @@ -131873,7 +132772,7 @@ ${lanes.join("\n")} } }; if (Debug.isDebugging) { - Object.defineProperty(cache, "__cache", { get: () => exportInfo }); + Object.defineProperty(cache, "__cache", { value: exportInfo }); } return cache; function rehydrateCachedInfo(info) { @@ -131892,7 +132791,9 @@ ${lanes.join("\n")} }; } const checker = (isFromPackageJson ? host.getPackageJsonAutoImportProvider() : host.getCurrentProgram()).getTypeChecker(); - const moduleSymbol = info.moduleSymbol || cachedModuleSymbol || Debug.checkDefined(info.moduleFile ? checker.getMergedSymbol(info.moduleFile.symbol) : checker.tryFindAmbientModule(info.moduleName)); + const moduleSymbol = info.moduleSymbol || cachedModuleSymbol || Debug.checkDefined( + info.moduleFile ? checker.getMergedSymbol(info.moduleFile.symbol) : checker.tryFindAmbientModule(info.moduleName) + ); const symbol = info.symbol || cachedSymbol || Debug.checkDefined( exportKind === 2 /* ExportEquals */ ? checker.resolveExternalModuleSymbol(moduleSymbol) : checker.tryGetMemberInModuleExportsAndProperties(unescapeLeadingUnderscores(info.symbolTableKey), moduleSymbol), `Could not find symbol '${info.symbolName}' by key '${info.symbolTableKey}' in module ${moduleSymbol.name}` @@ -131909,11 +132810,15 @@ ${lanes.join("\n")} } function key(importedName, symbol, ambientModuleName, checker) { const moduleKey = ambientModuleName || ""; - return `${importedName}|${getSymbolId(skipAlias(symbol, checker))}|${moduleKey}`; + return `${importedName.length} ${getSymbolId(skipAlias(symbol, checker))} ${importedName} ${moduleKey}`; } function parseKey(key2) { - const symbolName2 = key2.substring(0, key2.indexOf("|")); - const moduleKey = key2.substring(key2.lastIndexOf("|") + 1); + const firstSpace = key2.indexOf(" "); + const secondSpace = key2.indexOf(" ", firstSpace + 1); + const symbolNameLength = parseInt(key2.substring(0, firstSpace), 10); + const data = key2.substring(secondSpace + 1); + const symbolName2 = data.substring(0, symbolNameLength); + const moduleKey = data.substring(symbolNameLength + 1); const ambientModuleName = moduleKey === "" ? void 0 : moduleKey; return { symbolName: symbolName2, ambientModuleName }; } @@ -132022,7 +132927,7 @@ ${lanes.join("\n")} var _a; const isExcluded = excludePatterns && ((fileName) => excludePatterns.some((p) => p.test(fileName))); for (const ambient of checker.getAmbientModules()) { - if (!stringContains(ambient.name, "*") && !(excludePatterns && ((_a = ambient.declarations) == null ? void 0 : _a.every((d) => isExcluded(d.getSourceFile().fileName))))) { + if (!ambient.name.includes("*") && !(excludePatterns && ((_a = ambient.declarations) == null ? void 0 : _a.every((d) => isExcluded(d.getSourceFile().fileName))))) { cb( ambient, /*sourceFile*/ @@ -133045,21 +133950,25 @@ ${lanes.join("\n")} "src/services/classifier.ts"() { "use strict"; init_ts4(); - noRegexTable = arrayToNumericMap([ - 80 /* Identifier */, - 11 /* StringLiteral */, - 9 /* NumericLiteral */, - 10 /* BigIntLiteral */, - 14 /* RegularExpressionLiteral */, - 110 /* ThisKeyword */, - 46 /* PlusPlusToken */, - 47 /* MinusMinusToken */, - 22 /* CloseParenToken */, - 24 /* CloseBracketToken */, - 20 /* CloseBraceToken */, - 112 /* TrueKeyword */, - 97 /* FalseKeyword */ - ], (token) => token, () => true); + noRegexTable = arrayToNumericMap( + [ + 80 /* Identifier */, + 11 /* StringLiteral */, + 9 /* NumericLiteral */, + 10 /* BigIntLiteral */, + 14 /* RegularExpressionLiteral */, + 110 /* ThisKeyword */, + 46 /* PlusPlusToken */, + 47 /* MinusMinusToken */, + 22 /* CloseParenToken */, + 24 /* CloseBracketToken */, + 20 /* CloseBraceToken */, + 112 /* TrueKeyword */, + 97 /* FalseKeyword */ + ], + (token) => token, + () => true + ); } }); @@ -133069,7 +133978,7 @@ ${lanes.join("\n")} "src/services/documentHighlights.ts"() { "use strict"; init_ts4(); - ((DocumentHighlights2) => { + ((DocumentHighlights3) => { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { const node = getTouchingPropertyName(sourceFile, position); if (node.parent && (isJsxOpeningElement(node.parent) && node.parent.tagName === node || isJsxClosingElement(node.parent))) { @@ -133079,7 +133988,7 @@ ${lanes.join("\n")} } return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } - DocumentHighlights2.getDocumentHighlights = getDocumentHighlights; + DocumentHighlights3.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { return { fileName: sourceFile.fileName, @@ -133254,7 +134163,7 @@ ${lanes.join("\n")} case 241 /* Block */: case 296 /* CaseClause */: case 297 /* DefaultClause */: - if (modifierFlag & 256 /* Abstract */ && isClassDeclaration(declaration)) { + if (modifierFlag & 64 /* Abstract */ && isClassDeclaration(declaration)) { return [...declaration.members, declaration]; } else { return container.statements; @@ -133268,12 +134177,12 @@ ${lanes.join("\n")} case 264 /* InterfaceDeclaration */: case 187 /* TypeLiteral */: const nodes = container.members; - if (modifierFlag & (28 /* AccessibilityModifier */ | 64 /* Readonly */)) { + if (modifierFlag & (7 /* AccessibilityModifier */ | 8 /* Readonly */)) { const constructor = find(container.members, isConstructorDeclaration); if (constructor) { return [...nodes, ...constructor.parameters]; } - } else if (modifierFlag & 256 /* Abstract */) { + } else if (modifierFlag & 64 /* Abstract */) { return [...nodes, container]; } return nodes; @@ -133480,10 +134389,10 @@ ${lanes.join("\n")} function isDocumentRegistryEntry(entry) { return !!entry.sourceFile; } - function createDocumentRegistry(useCaseSensitiveFileNames2, currentDirectory) { - return createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory); + function createDocumentRegistry(useCaseSensitiveFileNames2, currentDirectory, jsDocParsingMode) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory, jsDocParsingMode); } - function createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory = "", externalCache) { + function createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory = "", jsDocParsingMode, externalCache) { const buckets = /* @__PURE__ */ new Map(); const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames2); function reportStats() { @@ -133567,9 +134476,11 @@ ${lanes.join("\n")} const sourceFileOptions = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions : { languageVersion: scriptTarget, impliedNodeFormat: host && getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getModuleResolutionCache) == null ? void 0 : _c.call(_b)) == null ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings), - setExternalModuleIndicator: getSetExternalModuleIndicator(compilationSettings) + setExternalModuleIndicator: getSetExternalModuleIndicator(compilationSettings), + jsDocParsingMode }; sourceFileOptions.languageVersion = scriptTarget; + Debug.assertEqual(jsDocParsingMode, sourceFileOptions.jsDocParsingMode); const oldBucketCount = buckets.size; const keyWithMode = getDocumentRegistryBucketKeyWithMode(key, sourceFileOptions.impliedNodeFormat); const bucket = getOrUpdate(buckets, keyWithMode, () => /* @__PURE__ */ new Map()); @@ -133615,12 +134526,7 @@ ${lanes.join("\n")} setBucketEntry(); } else { if (entry.sourceFile.version !== version2) { - entry.sourceFile = updateLanguageServiceSourceFile( - entry.sourceFile, - scriptSnapshot, - version2, - scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot) - ); + entry.sourceFile = updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version2, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); if (externalCache) { externalCache.setDocument(keyWithMode, path, entry.sourceFile); } @@ -133810,29 +134716,19 @@ ${lanes.join("\n")} const oldImportFromPath = oldFromNew || sourceFile.fileName; const oldImportFromDirectory = getDirectoryPath(oldImportFromPath); const importingSourceFileMoved = newFromOld !== void 0 || oldFromNew !== void 0; - updateImportsWorker( - sourceFile, - changeTracker, - (referenceText) => { - if (!pathIsRelative(referenceText)) - return void 0; - const oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); - const newAbsolute = oldToNew(oldAbsolute); - return newAbsolute === void 0 ? void 0 : ensurePathIsNonModuleName(getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); - }, - (importLiteral) => { - const importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); - if ((importedModuleSymbol == null ? void 0 : importedModuleSymbol.declarations) && importedModuleSymbol.declarations.some((d) => isAmbientModule(d))) - return void 0; - const toImport = oldFromNew !== void 0 ? getSourceFileToImportFromResolved( - importLiteral, - resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), - oldToNew, - allFiles - ) : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); - return toImport !== void 0 && (toImport.updated || importingSourceFileMoved && pathIsRelative(importLiteral.text)) ? ts_moduleSpecifiers_exports.updateModuleSpecifier(program.getCompilerOptions(), sourceFile, getCanonicalFileName(newImportFromPath), toImport.newFileName, createModuleSpecifierResolutionHost(program, host), importLiteral.text) : void 0; - } - ); + updateImportsWorker(sourceFile, changeTracker, (referenceText) => { + if (!pathIsRelative(referenceText)) + return void 0; + const oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); + const newAbsolute = oldToNew(oldAbsolute); + return newAbsolute === void 0 ? void 0 : ensurePathIsNonModuleName(getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); + }, (importLiteral) => { + const importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); + if ((importedModuleSymbol == null ? void 0 : importedModuleSymbol.declarations) && importedModuleSymbol.declarations.some((d) => isAmbientModule(d))) + return void 0; + const toImport = oldFromNew !== void 0 ? getSourceFileToImportFromResolved(importLiteral, resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, allFiles) : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); + return toImport !== void 0 && (toImport.updated || importingSourceFileMoved && pathIsRelative(importLiteral.text)) ? ts_moduleSpecifiers_exports.updateModuleSpecifier(program.getCompilerOptions(), sourceFile, getCanonicalFileName(newImportFromPath), toImport.newFileName, createModuleSpecifierResolutionHost(program, host), importLiteral.text) : void 0; + }); } } function combineNormal(pathA, pathB) { @@ -133842,14 +134738,13 @@ ${lanes.join("\n")} return ensurePathIsNonModuleName(combineNormal(pathA, pathB)); } function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) { - var _a; if (importedModuleSymbol) { const oldFileName = find(importedModuleSymbol.declarations, isSourceFile).fileName; const newFileName = oldToNew(oldFileName); return newFileName === void 0 ? { newFileName: oldFileName, updated: false } : { newFileName, updated: true }; } else { const mode = getModeForUsageLocation(importingSourceFile, importLiteral); - const resolved = host.resolveModuleNameLiterals || !host.resolveModuleNames ? (_a = importingSourceFile.resolvedModules) == null ? void 0 : _a.get(importLiteral.text, mode) : host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName, mode); + const resolved = host.resolveModuleNameLiterals || !host.resolveModuleNames ? program.getResolvedModule(importingSourceFile, importLiteral.text, mode) : host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName, mode); return getSourceFileToImportFromResolved(importLiteral, resolved, oldToNew, program.getSourceFiles()); } } @@ -133918,6 +134813,21 @@ ${lanes.join("\n")} function createPatternMatcher(pattern) { const stringToWordSpans = /* @__PURE__ */ new Map(); const dotSeparatedSegments = pattern.trim().split(".").map((p) => createSegment(p.trim())); + if (dotSeparatedSegments.length === 1 && dotSeparatedSegments[0].totalTextChunk.text === "") { + return { + getMatchForLastSegmentOfPattern: () => createPatternMatch( + 2 /* substring */, + /*isCaseSensitive*/ + true + ), + getFullMatch: () => createPatternMatch( + 2 /* substring */, + /*isCaseSensitive*/ + true + ), + patternContainsDots: false + }; + } if (dotSeparatedSegments.some((segment) => !segment.subWordTextChunks.length)) return void 0; return { @@ -134754,6 +135664,7 @@ ${lanes.join("\n")} // src/services/suggestionDiagnostics.ts function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { + var _a; program.getSemanticDiagnostics(sourceFile, cancellationToken); const diags = []; const checker = program.getTypeChecker(); @@ -134770,7 +135681,7 @@ ${lanes.join("\n")} const name = importNameForConvertToDefaultImport(importNode); if (!name) continue; - const module2 = getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation(sourceFile, moduleSpecifier)); + const module2 = (_a = program.getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation(sourceFile, moduleSpecifier))) == null ? void 0 : _a.resolvedModule; const resolvedFile = module2 && program.getSourceFile(module2.resolvedFileName); if (resolvedFile && resolvedFile.externalModuleIndicator && resolvedFile.externalModuleIndicator !== true && isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { diags.push(createDiagnosticForNode(name, Diagnostics.Import_may_be_converted_to_a_default_import)); @@ -135023,7 +135934,8 @@ ${lanes.join("\n")} compilerHost, options ), - setExternalModuleIndicator: getSetExternalModuleIndicator(options) + setExternalModuleIndicator: getSetExternalModuleIndicator(options), + jsDocParsingMode: transpileOptions.jsDocParsingMode ?? 0 /* ParseAll */ } ); if (transpileOptions.moduleName) { @@ -135101,30 +136013,37 @@ ${lanes.join("\n")} }); // src/services/navigateTo.ts - function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles, excludeLibFiles) { const patternMatcher = createPatternMatcher(searchValue); if (!patternMatcher) return emptyArray; const rawItems = []; + const singleCurrentFile = sourceFiles.length === 1 ? sourceFiles[0] : void 0; for (const sourceFile of sourceFiles) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { continue; } + if (shouldExcludeFile(sourceFile, !!excludeLibFiles, singleCurrentFile)) { + continue; + } sourceFile.getNamedDeclarations().forEach((declarations, name) => { - getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); + getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, !!excludeLibFiles, singleCurrentFile, rawItems); }); } rawItems.sort(compareNavigateToItems); return (maxResultCount === void 0 ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); } - function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) { + function shouldExcludeFile(file, excludeLibFiles, singleCurrentFile) { + return file !== singleCurrentFile && excludeLibFiles && (isInsideNodeModules(file.path) || file.hasNoDefaultLib); + } + function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, excludeLibFiles, singleCurrentFile, rawItems) { const match = patternMatcher.getMatchForLastSegmentOfPattern(name); if (!match) { return; } for (const declaration of declarations) { - if (!shouldKeepItem(declaration, checker)) + if (!shouldKeepItem(declaration, checker, excludeLibFiles, singleCurrentFile)) continue; if (patternMatcher.patternContainsDots) { const fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); @@ -135136,14 +136055,15 @@ ${lanes.join("\n")} } } } - function shouldKeepItem(declaration, checker) { + function shouldKeepItem(declaration, checker, excludeLibFiles, singleCurrentFile) { + var _a; switch (declaration.kind) { case 273 /* ImportClause */: case 276 /* ImportSpecifier */: case 271 /* ImportEqualsDeclaration */: const importer = checker.getSymbolAtLocation(declaration.name); const imported = checker.getAliasedSymbol(importer); - return importer.escapedName !== imported.escapedName; + return importer.escapedName !== imported.escapedName && !((_a = imported.declarations) == null ? void 0 : _a.every((d) => shouldExcludeFile(d.getSourceFile(), excludeLibFiles, singleCurrentFile))); default: return true; } @@ -135334,7 +136254,14 @@ ${lanes.join("\n")} } } function hasNavigationBarName(node) { - return !hasDynamicName(node) || node.kind !== 226 /* BinaryExpression */ && isPropertyAccessExpression(node.name.expression) && isIdentifier(node.name.expression.expression) && idText(node.name.expression.expression) === "Symbol"; + const name = getNameOfDeclaration(node); + if (name === void 0) + return false; + if (isComputedPropertyName(name)) { + const expression = name.expression; + return isEntityNameExpression(expression) || isNumericLiteral(expression) || isStringOrNumericLiteralLike(expression); + } + return !!name; } function addChildrenRecursively(node) { curCancellationToken.throwIfCancellationRequested(); @@ -135485,11 +136412,7 @@ ${lanes.join("\n")} } } } else if (isFunctionExpression(binaryExpression.right) || isArrowFunction(binaryExpression.right)) { - addNodeWithRecursiveChild( - node, - binaryExpression.right, - className - ); + addNodeWithRecursiveChild(node, binaryExpression.right, className); } else { startNode(binaryExpression, className); addNodeWithRecursiveChild(node, binaryExpression.right, assignmentTarget.name); @@ -135614,16 +136537,19 @@ ${lanes.join("\n")} } } } - lastANode = a.node = setTextRange(factory.createClassDeclaration( - /*modifiers*/ - void 0, - a.name || factory.createIdentifier("__class__"), - /*typeParameters*/ - void 0, - /*heritageClauses*/ - void 0, - [] - ), a.node); + lastANode = a.node = setTextRange( + factory.createClassDeclaration( + /*modifiers*/ + void 0, + a.name || factory.createIdentifier("__class__"), + /*typeParameters*/ + void 0, + /*heritageClauses*/ + void 0, + [] + ), + a.node + ); } else { a.children = concatenate(a.children, b.children); if (a.children) { @@ -135636,16 +136562,19 @@ ${lanes.join("\n")} } else { if (!a.additionalNodes) a.additionalNodes = []; - a.additionalNodes.push(setTextRange(factory.createClassDeclaration( - /*modifiers*/ - void 0, - a.name || factory.createIdentifier("__class__"), - /*typeParameters*/ - void 0, - /*heritageClauses*/ - void 0, - [] - ), b.node)); + a.additionalNodes.push(setTextRange( + factory.createClassDeclaration( + /*modifiers*/ + void 0, + a.name || factory.createIdentifier("__class__"), + /*typeParameters*/ + void 0, + /*heritageClauses*/ + void 0, + [] + ), + b.node + )); } return true; } @@ -135747,7 +136676,7 @@ ${lanes.join("\n")} case 218 /* FunctionExpression */: case 263 /* ClassDeclaration */: case 231 /* ClassExpression */: - if (getSyntacticModifierFlags(node) & 1024 /* Default */) { + if (getSyntacticModifierFlags(node) & 2048 /* Default */) { return "default"; } return getFunctionOrClassName(node); @@ -135897,7 +136826,7 @@ ${lanes.join("\n")} return nodeText(parent2.left).replace(whiteSpaceRegex, ""); } else if (isPropertyAssignment(parent2)) { return nodeText(parent2.name); - } else if (getSyntacticModifierFlags(node) & 1024 /* Default */) { + } else if (getSyntacticModifierFlags(node) & 2048 /* Default */) { return "default"; } else if (isClassLike(node)) { return ""; @@ -136006,15 +136935,15 @@ ${lanes.join("\n")} const { file, program } = context; const span = getRefactorContextSpan(context); const token = getTokenAtPosition(file, span.start); - const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & 1 /* Export */) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span); + const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & 32 /* Export */) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span); if (!exportNode || !isSourceFile(exportNode.parent) && !(isModuleBlock(exportNode.parent) && isAmbientModule(exportNode.parent.parent))) { return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_export_statement) }; } const checker = program.getTypeChecker(); const exportingModuleSymbol = getExportingModuleSymbol(exportNode.parent, checker); - const flags = getSyntacticModifierFlags(exportNode) || (isExportAssignment(exportNode) && !exportNode.isExportEquals ? 1025 /* ExportDefault */ : 0 /* None */); - const wasDefault = !!(flags & 1024 /* Default */); - if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { + const flags = getSyntacticModifierFlags(exportNode) || (isExportAssignment(exportNode) && !exportNode.isExportEquals ? 2080 /* ExportDefault */ : 0 /* None */); + const wasDefault = !!(flags & 2048 /* Default */); + if (!(flags & 32 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { return { error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) }; } const noSymbolError = (id) => isIdentifier(id) && checker.getSymbolAtLocation(id) ? void 0 : { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) }; @@ -136147,7 +137076,7 @@ ${lanes.join("\n")} } case 205 /* ImportType */: const importTypeNode = parent2; - changes.replaceNode(importingSourceFile, parent2, factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); + changes.replaceNode(importingSourceFile, parent2, factory.createImportTypeNode(importTypeNode.argument, importTypeNode.attributes, factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); break; default: Debug.failBadSyntaxKind(parent2); @@ -136235,10 +137164,14 @@ ${lanes.join("\n")} } if (context.preferences.provideRefactorNotApplicableReason) { return [ - { name: refactorName, description: getLocaleSpecificMessage(Diagnostics.Convert_default_export_to_named_export), actions: [ - { ...defaultToNamedAction, notApplicableReason: info.error }, - { ...namedToDefaultAction, notApplicableReason: info.error } - ] } + { + name: refactorName, + description: getLocaleSpecificMessage(Diagnostics.Convert_default_export_to_named_export), + actions: [ + { ...defaultToNamedAction, notApplicableReason: info.error }, + { ...namedToDefaultAction, notApplicableReason: info.error } + ] + } ]; } return emptyArray; @@ -136394,7 +137327,11 @@ ${lanes.join("\n")} } }); } - changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName))); + changes.replaceNode( + sourceFile, + toConvert, + shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName)) + ); if (neededNamedImports.size) { const newNamedImports = arrayFrom(neededNamedImports.values(), (element) => factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.createIdentifier(element.propertyName.text), factory.createIdentifier(element.name.text))); changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport( @@ -136423,7 +137360,7 @@ ${lanes.join("\n")} elements && elements.length ? factory.createNamedImports(elements) : void 0 ), old.moduleSpecifier, - /*assertClause*/ + /*attributes*/ void 0 ); } @@ -136488,26 +137425,50 @@ ${lanes.join("\n")} const current = getTokenAtPosition(file, startPosition); const range = createTextRangeFromSpan(getRefactorContextSpan(context)); const cursorRequest = range.pos === range.end && considerEmptySpans; - const selection = findAncestor(current, (node) => node.parent && isTypeNode(node) && !rangeContainsSkipTrivia(range, node.parent, file) && (cursorRequest || nodeOverlapsWithStartEnd(current, file, range.pos, range.end))); - if (!selection || !isTypeNode(selection)) + const overlappingRange = nodeOverlapsWithStartEnd(current, file, range.pos, range.end); + const firstType = findAncestor(current, (node) => node.parent && isTypeNode(node) && !rangeContainsSkipTrivia(range, node.parent, file) && (cursorRequest || overlappingRange)); + if (!firstType || !isTypeNode(firstType)) return { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }; const checker = context.program.getTypeChecker(); - const enclosingNode = getEnclosingNode(selection, isJS); + const enclosingNode = getEnclosingNode(firstType, isJS); if (enclosingNode === void 0) return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; + const expandedFirstType = getExpandedSelectionNode(firstType, enclosingNode); + if (!isTypeNode(expandedFirstType)) + return { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }; + const typeList = []; + if ((isUnionTypeNode(expandedFirstType.parent) || isIntersectionTypeNode(expandedFirstType.parent)) && range.end > firstType.end) { + addRange( + typeList, + expandedFirstType.parent.types.filter((type) => { + return nodeOverlapsWithStartEnd(type, file, range.pos, range.end); + }) + ); + } + const selection = typeList.length > 1 ? typeList : expandedFirstType; const typeParameters = collectTypeParameters(checker, selection, enclosingNode, file); if (!typeParameters) return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; const typeElements = flattenTypeLiteralNodeReference(checker, selection); return { isJS, selection, enclosingNode, typeParameters, typeElements }; } - function flattenTypeLiteralNodeReference(checker, node) { - if (!node) + function flattenTypeLiteralNodeReference(checker, selection) { + if (!selection) return void 0; - if (isIntersectionTypeNode(node)) { + if (isArray(selection)) { + const result = []; + for (const type of selection) { + const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type); + if (!flattenedTypeMembers) + return void 0; + addRange(result, flattenedTypeMembers); + } + return result; + } + if (isIntersectionTypeNode(selection)) { const result = []; const seen = /* @__PURE__ */ new Map(); - for (const type of node.types) { + for (const type of selection.types) { const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type); if (!flattenedTypeMembers || !flattenedTypeMembers.every((type2) => type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) { return void 0; @@ -136515,10 +137476,10 @@ ${lanes.join("\n")} addRange(result, flattenedTypeMembers); } return result; - } else if (isParenthesizedTypeNode(node)) { - return flattenTypeLiteralNodeReference(checker, node.type); - } else if (isTypeLiteralNode(node)) { - return node.members; + } else if (isParenthesizedTypeNode(selection)) { + return flattenTypeLiteralNodeReference(checker, selection.type); + } else if (isTypeLiteralNode(selection)) { + return selection.members; } return void 0; } @@ -136527,7 +137488,13 @@ ${lanes.join("\n")} } function collectTypeParameters(checker, selection, enclosingNode, file) { const result = []; - return visitor(selection) ? void 0 : result; + const selectionArray = toArray(selection); + const selectionRange = { pos: selectionArray[0].pos, end: selectionArray[selectionArray.length - 1].end }; + for (const t of selectionArray) { + if (visitor(t)) + return void 0; + } + return result; function visitor(node) { if (isTypeReferenceNode(node)) { if (isIdentifier(node.typeName)) { @@ -136541,10 +137508,10 @@ ${lanes.join("\n")} ); for (const decl of (symbol == null ? void 0 : symbol.declarations) || emptyArray) { if (isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) { - if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selection, file)) { + if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selectionRange, file)) { return true; } - if (rangeContainsSkipTrivia(enclosingNode, decl, file) && !rangeContainsSkipTrivia(selection, decl, file)) { + if (rangeContainsSkipTrivia(enclosingNode, decl, file) && !rangeContainsSkipTrivia(selectionRange, decl, file)) { pushIfUnique(result, decl); break; } @@ -136553,12 +137520,12 @@ ${lanes.join("\n")} } } else if (isInferTypeNode(node)) { const conditionalTypeNode = findAncestor(node, (n) => isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file)); - if (!conditionalTypeNode || !rangeContainsSkipTrivia(selection, conditionalTypeNode, file)) { + if (!conditionalTypeNode || !rangeContainsSkipTrivia(selectionRange, conditionalTypeNode, file)) { return true; } } else if (isTypePredicateNode(node) || isThisTypeNode(node)) { const functionLikeNode = findAncestor(node.parent, isFunctionLike); - if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selection, functionLikeNode, file)) { + if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selectionRange, functionLikeNode, file)) { return true; } } else if (isTypeQueryNode(node)) { @@ -136570,11 +137537,11 @@ ${lanes.join("\n")} /*excludeGlobals*/ false ); - if ((symbol == null ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(enclosingNode, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { + if ((symbol == null ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(enclosingNode, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selectionRange, symbol.valueDeclaration, file)) { return true; } } else { - if (isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selection, node.parent, file)) { + if (isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selectionRange, node.parent, file)) { return true; } } @@ -136586,8 +137553,9 @@ ${lanes.join("\n")} } } function doTypeAliasChange(changes, file, name, info) { - const { enclosingNode, selection, typeParameters } = info; - const newTypeNode = factory.createTypeAliasDeclaration( + const { enclosingNode, typeParameters } = info; + const { firstTypeNode, lastTypeNode, newTypeNode } = getNodesToEdit(info); + const newTypeDeclaration = factory.createTypeAliasDeclaration( /*modifiers*/ void 0, name, @@ -136599,16 +137567,16 @@ ${lanes.join("\n")} /*defaultType*/ void 0 )), - selection + newTypeNode ); changes.insertNodeBefore( file, enclosingNode, - ignoreSourceNewlines(newTypeNode), + ignoreSourceNewlines(newTypeDeclaration), /*blankLineBetween*/ true ); - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( + changes.replaceNodeRange(file, firstTypeNode, lastTypeNode, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( id.name, /*typeArguments*/ void 0 @@ -136616,7 +137584,7 @@ ${lanes.join("\n")} } function doInterfaceChange(changes, file, name, info) { var _a; - const { enclosingNode, selection, typeParameters, typeElements } = info; + const { enclosingNode, typeParameters, typeElements } = info; const newTypeNode = factory.createInterfaceDeclaration( /*modifiers*/ void 0, @@ -136634,7 +137602,8 @@ ${lanes.join("\n")} /*blankLineBetween*/ true ); - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( + const { firstTypeNode, lastTypeNode } = getNodesToEdit(info); + changes.replaceNodeRange(file, firstTypeNode, lastTypeNode, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( id.name, /*typeArguments*/ void 0 @@ -136642,11 +137611,14 @@ ${lanes.join("\n")} } function doTypedefChange(changes, context, file, name, info) { var _a; - const { enclosingNode, selection, typeParameters } = info; - setEmitFlags(selection, 3072 /* NoComments */ | 4096 /* NoNestedComments */); + toArray(info.selection).forEach((typeNode) => { + setEmitFlags(typeNode, 3072 /* NoComments */ | 4096 /* NoNestedComments */); + }); + const { enclosingNode, typeParameters } = info; + const { firstTypeNode, lastTypeNode, newTypeNode } = getNodesToEdit(info); const node = factory.createJSDocTypedefTag( factory.createIdentifier("typedef"), - factory.createJSDocTypeExpression(selection), + factory.createJSDocTypeExpression(newTypeNode), factory.createIdentifier(name) ); const templates = []; @@ -136684,15 +137656,39 @@ ${lanes.join("\n")} true ); } - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( + changes.replaceNodeRange(file, firstTypeNode, lastTypeNode, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( id.name, /*typeArguments*/ void 0 )))); } + function getNodesToEdit(info) { + if (isArray(info.selection)) { + return { + firstTypeNode: info.selection[0], + lastTypeNode: info.selection[info.selection.length - 1], + newTypeNode: isUnionTypeNode(info.selection[0].parent) ? factory.createUnionTypeNode(info.selection) : factory.createIntersectionTypeNode(info.selection) + }; + } + return { + firstTypeNode: info.selection, + lastTypeNode: info.selection, + newTypeNode: info.selection + }; + } function getEnclosingNode(node, isJS) { return findAncestor(node, isStatement) || (isJS ? findAncestor(node, isJSDoc) : void 0); } + function getExpandedSelectionNode(firstType, enclosingNode) { + return findAncestor(firstType, (node) => { + if (node === enclosingNode) + return "quit"; + if (isUnionTypeNode(node.parent) || isIntersectionTypeNode(node.parent)) { + return true; + } + return false; + }) ?? firstType; + } var refactorName3, extractToTypeAliasAction, extractToInterfaceAction, extractToTypeDefAction; var init_extractType = __esm({ "src/services/refactors/extractType.ts"() { @@ -137017,7 +138013,7 @@ ${lanes.join("\n")} if (markSeenTop(top)) { addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); } - if (hasSyntacticModifier(decl, 1024 /* Default */)) { + if (hasSyntacticModifier(decl, 2048 /* Default */)) { oldFileDefault = name; } else { oldFileNamedImports.push(name.text); @@ -137048,11 +138044,7 @@ ${lanes.join("\n")} return [{ name: refactorName5, description, actions: [moveToNewFileAction] }]; } if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName5, - description, - actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] - }]; + return [{ name: refactorName5, description, actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] }]; } return emptyArray; }, @@ -137072,14 +138064,13 @@ ${lanes.join("\n")} } function doChange4(context, oldFile, targetFile, program, toMove, changes, host, preferences) { const checker = program.getTypeChecker(); - const usage = getUsageInfo(oldFile, toMove.all, checker); if (!host.fileExists(targetFile)) { - changes.createNewFile(oldFile, targetFile, getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, changes, toMove, program, host, preferences)); + changes.createNewFile(oldFile, targetFile, getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, getUsageInfo(oldFile, toMove.all, checker), changes, toMove, program, host, preferences)); addNewFileToTsconfig(program, changes, oldFile.fileName, targetFile, hostGetCanonicalFileName(host)); } else { const targetSourceFile = Debug.checkDefined(program.getSourceFile(targetFile)); const importAdder = ts_codefix_exports.createImportAdder(targetSourceFile, context.program, context.preferences, context.host); - getNewStatementsAndRemoveFromOldFile2(oldFile, targetSourceFile, usage, changes, toMove, program, host, preferences, importAdder); + getNewStatementsAndRemoveFromOldFile2(oldFile, targetSourceFile, getUsageInfo(oldFile, toMove.all, checker, getExistingImports(targetSourceFile, checker)), changes, toMove, program, host, preferences, importAdder); } } function getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, changes, toMove, program, host, preferences, importAdder) { @@ -137165,10 +138156,10 @@ ${lanes.join("\n")} const targetSourceFile = program.getSourceFile(targetFile); for (const oldStatement of oldFile.statements) { forEachImportInStatement(oldStatement, (i) => { - var _a, _b; + var _a; const moduleSpecifier = moduleSpecifierFromImport(i); - const resolved = (_a = oldFile.resolvedModules) == null ? void 0 : _a.get(moduleSpecifier.text, getModeForUsageLocation(oldFile, moduleSpecifier)); - const fileName = (_b = resolved == null ? void 0 : resolved.resolvedModule) == null ? void 0 : _b.resolvedFileName; + const resolved = program.getResolvedModule(oldFile, moduleSpecifier.text, getModeForUsageLocation(oldFile, moduleSpecifier)); + const fileName = (_a = resolved == null ? void 0 : resolved.resolvedModule) == null ? void 0 : _a.resolvedFileName; if (fileName && targetSourceFile) { const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), targetSourceFile, targetSourceFile.path, fileName, createModuleSpecifierResolutionHost(program, host)); append(copiedOldImports, filterImport(i, makeStringLiteral(newModuleSpecifier, quotePreference), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); @@ -137199,7 +138190,7 @@ ${lanes.join("\n")} if (importAdder && checker.isUnknownSymbol(symbol)) { importAdder.addImportFromExportedSymbol(skipAlias(symbol, checker)); } else { - if (hasSyntacticModifier(decl, 1024 /* Default */)) { + if (hasSyntacticModifier(decl, 2048 /* Default */)) { oldFileDefault = name; } else { oldFileNamedImports.push(name.text); @@ -137313,7 +138304,7 @@ ${lanes.join("\n")} factory.createNamespaceImport(newNamespaceId) ), newModuleString, - /*assertClause*/ + /*attributes*/ void 0 ); case 271 /* ImportEqualsDeclaration */: @@ -137439,7 +138430,7 @@ ${lanes.join("\n")} function isExported(sourceFile, decl, useEs6Exports, name) { var _a; if (useEs6Exports) { - return !isExpressionStatement(decl) && hasSyntacticModifier(decl, 1 /* Export */) || !!(name && sourceFile.symbol && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(name.escapedText))); + return !isExpressionStatement(decl) && hasSyntacticModifier(decl, 32 /* Export */) || !!(name && sourceFile.symbol && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(name.escapedText))); } return !!sourceFile.symbol && !!sourceFile.symbol.exports && getNamesToExportInCommonJS(decl).some((name2) => sourceFile.symbol.exports.has(escapeLeadingUnderscores(name2))); } @@ -137504,10 +138495,7 @@ ${lanes.join("\n")} /*requireStringLiteralLikeArgument*/ true )) { - changes.delete( - sourceFile, - isVariableDeclarationList(varDecl.parent) && length(varDecl.parent.declarations) === 1 ? varDecl.parent.parent : varDecl - ); + changes.delete(sourceFile, isVariableDeclarationList(varDecl.parent) && length(varDecl.parent.declarations) === 1 ? varDecl.parent.parent : varDecl); } else { changes.delete(sourceFile, name); } @@ -137517,10 +138505,7 @@ ${lanes.join("\n")} break; case 206 /* ObjectBindingPattern */: if (name.elements.every((e) => isIdentifier(e.name) && isUnused(e.name))) { - changes.delete( - sourceFile, - isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl - ); + changes.delete(sourceFile, isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); } else { for (const element of name.elements) { if (isIdentifier(element.name) && isUnused(element.name)) { @@ -137608,7 +138593,7 @@ ${lanes.join("\n")} void 0, factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings), getSynthesizedDeepClone(moduleSpecifier), - /*assertClause*/ + /*attributes*/ void 0 ) : void 0; } @@ -137740,7 +138725,7 @@ ${lanes.join("\n")} case 272 /* ImportDeclaration */: return true; case 271 /* ImportEqualsDeclaration */: - return !hasSyntacticModifier(node, 1 /* Export */); + return !hasSyntacticModifier(node, 32 /* Export */); case 243 /* VariableStatement */: return node.declarationList.declarations.every((d) => !!d.initializer && isRequireCall( d.initializer, @@ -137751,7 +138736,7 @@ ${lanes.join("\n")} return false; } } - function getUsageInfo(oldFile, toMove, checker) { + function getUsageInfo(oldFile, toMove, checker, existingTargetImports = /* @__PURE__ */ new Set()) { const movedSymbols = /* @__PURE__ */ new Set(); const oldImportsNeededByTargetFile = /* @__PURE__ */ new Map(); const targetFileImportsFromOldFile = /* @__PURE__ */ new Set(); @@ -137765,10 +138750,16 @@ ${lanes.join("\n")} movedSymbols.add(Debug.checkDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here")); }); } + const unusedImportsFromOldFile = /* @__PURE__ */ new Set(); for (const statement of toMove) { forEachReference(statement, checker, (symbol, isValidTypeOnlyUseSite) => { - if (!symbol.declarations) + if (!symbol.declarations) { return; + } + if (existingTargetImports.has(skipAlias(symbol, checker))) { + unusedImportsFromOldFile.add(symbol); + return; + } for (const decl of symbol.declarations) { if (isInImport(decl)) { const prevIsTypeOnly = oldImportsNeededByTargetFile.get(symbol); @@ -137779,7 +138770,9 @@ ${lanes.join("\n")} } }); } - const unusedImportsFromOldFile = new Set(oldImportsNeededByTargetFile.keys()); + for (const unusedImport of oldImportsNeededByTargetFile.keys()) { + unusedImportsFromOldFile.add(unusedImport); + } const oldFileImportsFromTargetFile = /* @__PURE__ */ new Set(); for (const statement of oldFile.statements) { if (contains(toMove, statement)) @@ -137911,16 +138904,13 @@ ${lanes.join("\n")} const checker = program.getTypeChecker(); const targetToSourceExports = /* @__PURE__ */ new Map(); for (const node of toMove.all) { - if (isTopLevelDeclarationStatement(node) && hasSyntacticModifier(node, 1 /* Export */)) { + if (isTopLevelDeclarationStatement(node) && hasSyntacticModifier(node, 32 /* 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) - ); + targetToSourceExports.set(exportDeclaration, (targetToSourceExports.get(exportDeclaration) || /* @__PURE__ */ new Set()).add(declaration)); } }); } @@ -137935,18 +138925,7 @@ ${lanes.join("\n")} 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 - ) - ); + changes.replaceNode(targetFile, exportDeclaration, factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, exportDeclaration.isTypeOnly, factory.updateNamedExports(exportDeclaration.exportClause, factory.createNodeArray(updatedElements, elements.hasTrailingComma)), exportDeclaration.moduleSpecifier, exportDeclaration.attributes)); } } } @@ -137979,6 +138958,29 @@ ${lanes.join("\n")} } return void 0; } + function getExistingImports(sourceFile, checker) { + const imports = /* @__PURE__ */ new Set(); + for (const moduleSpecifier of sourceFile.imports) { + const declaration = importFromModuleSpecifier(moduleSpecifier); + if (isImportDeclaration(declaration) && declaration.importClause && declaration.importClause.namedBindings && isNamedImports(declaration.importClause.namedBindings)) { + for (const e of declaration.importClause.namedBindings.elements) { + const symbol = checker.getSymbolAtLocation(e.propertyName || e.name); + if (symbol) { + imports.add(skipAlias(symbol, checker)); + } + } + } + if (isVariableDeclarationInitializedToRequire(declaration.parent) && isObjectBindingPattern(declaration.parent.name)) { + for (const e of declaration.parent.name.elements) { + const symbol = checker.getSymbolAtLocation(e.propertyName || e.name); + if (symbol) { + imports.add(skipAlias(symbol, checker)); + } + } + } + } + return imports; + } var refactorNameForMoveToFile, description2, moveToFileAction; var init_moveToFile = __esm({ "src/services/refactors/moveToFile.ts"() { @@ -138004,11 +139006,7 @@ ${lanes.join("\n")} return [{ name: refactorNameForMoveToFile, description: description2, actions: [moveToFileAction] }]; } if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorNameForMoveToFile, - description: description2, - actions: [{ ...moveToFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] - }]; + return [{ name: refactorNameForMoveToFile, description: description2, actions: [{ ...moveToFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] }]; } return emptyArray; }, @@ -138151,12 +139149,15 @@ ${lanes.join("\n")} } function convertParameterToNamedTupleMember(p) { Debug.assert(isIdentifier(p.name)); - const result = setTextRange(factory.createNamedTupleMember( - p.dotDotDotToken, - p.name, - p.questionToken, - p.type || factory.createKeywordTypeNode(133 /* AnyKeyword */) - ), p); + const result = setTextRange( + factory.createNamedTupleMember( + p.dotDotDotToken, + p.name, + p.questionToken, + p.type || factory.createKeywordTypeNode(133 /* AnyKeyword */) + ), + p + ); const parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker); if (parameterDocComment) { const newComment = displayPartsToString(parameterDocComment); @@ -138355,7 +139356,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) { const firstStatement = first(func.body.statements); if (isReturnStatement(firstStatement)) { - return { func, addBraces: false, expression: firstStatement.expression, returnStatement: firstStatement }; + const expression = firstStatement.expression && isObjectLiteralExpression(getLeftmostExpression( + firstStatement.expression, + /*stopAtCallExpressions*/ + false + )) ? factory.createParenthesizedExpression(firstStatement.expression) : firstStatement.expression; + return { func, addBraces: false, expression, returnStatement: firstStatement }; } } return void 0; @@ -138558,7 +139564,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const body = convertToBlock(func.body); const { variableDeclaration, variableDeclarationList, statement, name } = variableInfo; suppressLeadingTrivia(statement); - const modifiersFlags = getCombinedModifierFlags(variableDeclaration) & 1 /* Export */ | getEffectiveModifierFlags(func); + const modifiersFlags = getCombinedModifierFlags(variableDeclaration) & 32 /* Export */ | getEffectiveModifierFlags(func); const modifiers = factory.createModifiersFromModifierFlags(modifiersFlags); const newNode = factory.createFunctionDeclaration(length(modifiers) ? modifiers : void 0, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); if (variableDeclarationList.declarations.length === 1) { @@ -139197,15 +140203,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const { file, startPosition } = context; const node = getNodeOrParentOfParentheses(file, startPosition); const maybeBinary = getParentBinaryExpression(node); + const nodeIsStringLiteral = isStringLiteral(maybeBinary); const refactorInfo = { name: refactorName10, description: refactorDescription6, actions: [] }; - if (isBinaryExpression(maybeBinary) && treeToArray(maybeBinary).isValidConcatenation) { + if (nodeIsStringLiteral && context.triggerReason !== "invoked") { + return emptyArray; + } + if (isExpressionNode(maybeBinary) && (nodeIsStringLiteral || isBinaryExpression(maybeBinary) && treeToArray(maybeBinary).isValidConcatenation)) { refactorInfo.actions.push(convertStringAction); return [refactorInfo]; } else if (context.preferences.provideRefactorNotApplicableReason) { - refactorInfo.actions.push({ - ...convertStringAction, - notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenation) - }); + refactorInfo.actions.push({ ...convertStringAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenations_and_string_literals) }); return [refactorInfo]; } return emptyArray; @@ -139266,12 +140273,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function treeToArray(current) { const loop = (current2) => { if (!isBinaryExpression(current2)) { - return { - nodes: [current2], - operators: [], - validOperators: true, - hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2) - }; + return { nodes: [current2], operators: [], validOperators: true, hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2) }; } const { nodes: nodes2, operators: operators2, hasString: leftHasString, validOperators: leftOperatorValid } = loop(current2.left); if (!(leftHasString || isStringLiteral(current2.right) || isTemplateExpression(current2.right))) { @@ -139337,7 +140339,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const isLastSpan = index === currentNode.templateSpans.length - 1; const text = span.literal.text + (isLastSpan ? subsequentText : ""); const rawText = getRawTextOfTemplate(span.literal) + (isLastSpan ? rawSubsequentText : ""); - return factory.createTemplateSpan(span.expression, isLast && isLastSpan ? factory.createTemplateTail(text, rawText) : factory.createTemplateMiddle(text, rawText)); + return factory.createTemplateSpan( + span.expression, + isLast && isLastSpan ? factory.createTemplateTail(text, rawText) : factory.createTemplateMiddle(text, rawText) + ); }); templateSpans.push(...spans); } else { @@ -139454,10 +140459,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getRefactorEditsToConvertToOptionalChain(context, actionName2) { const info = getInfo3(context); Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with( - context, - (t) => doChange6(context.file, context.program.getTypeChecker(), t, info, actionName2) - ); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange6(context.file, context.program.getTypeChecker(), t, info, actionName2)); return { edits, renameFilename: void 0, renameLocation: void 0 }; } function isValidExpression(node) { @@ -139620,11 +140622,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isBinaryExpression(expression)) { changes.replaceNodeRange(sourceFile, firstOccurrence, finalExpression, convertedChain); } else if (isConditionalExpression(expression)) { - changes.replaceNode( - sourceFile, - expression, - factory.createBinaryExpression(convertedChain, factory.createToken(61 /* QuestionQuestionToken */), expression.whenFalse) - ); + changes.replaceNode(sourceFile, expression, factory.createBinaryExpression(convertedChain, factory.createToken(61 /* QuestionQuestionToken */), expression.whenFalse)); } } } @@ -139940,7 +140938,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (isDeclaration(node2)) { const declaringNode = node2.kind === 260 /* VariableDeclaration */ ? node2.parent.parent : node2; - if (hasSyntacticModifier(declaringNode, 1 /* Export */)) { + if (hasSyntacticModifier(declaringNode, 32 /* Export */)) { (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); return true; } @@ -140652,57 +141650,36 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const paramType = checker.getTypeAtLocation(p); if (paramType === checker.getAnyType()) hasAny = true; - parameters.push(factory.updateParameterDeclaration( - p, - p.modifiers, - p.dotDotDotToken, - p.name, - p.questionToken, - p.type || checker.typeToTypeNode(paramType, scope, 1 /* NoTruncation */), - p.initializer - )); + parameters.push(factory.updateParameterDeclaration(p, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NoTruncation */), p.initializer)); } } if (hasAny) return { variableType: variableType2, initializer: initializer2 }; variableType2 = void 0; if (isArrowFunction(initializer2)) { - initializer2 = factory.updateArrowFunction( - initializer2, - canHaveModifiers(node) ? getModifiers(node) : void 0, - initializer2.typeParameters, - parameters, - initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), - initializer2.equalsGreaterThanToken, - initializer2.body - ); + initializer2 = factory.updateArrowFunction(initializer2, canHaveModifiers(node) ? getModifiers(node) : void 0, initializer2.typeParameters, parameters, initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), initializer2.equalsGreaterThanToken, initializer2.body); } else { if (functionSignature && !!functionSignature.thisParameter) { const firstParameter = firstOrUndefined(parameters); if (!firstParameter || isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this") { const thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); - parameters.splice(0, 0, factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "this", - /*questionToken*/ - void 0, - checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */) - )); + parameters.splice( + 0, + 0, + factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "this", + /*questionToken*/ + void 0, + checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */) + ) + ); } } - initializer2 = factory.updateFunctionExpression( - initializer2, - canHaveModifiers(node) ? getModifiers(node) : void 0, - initializer2.asteriskToken, - initializer2.name, - initializer2.typeParameters, - parameters, - initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), - initializer2.body - ); + initializer2 = factory.updateFunctionExpression(initializer2, canHaveModifiers(node) ? getModifiers(node) : void 0, initializer2.asteriskToken, initializer2.name, initializer2.typeParameters, parameters, initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), initializer2.body); } return { variableType: variableType2, initializer: initializer2 }; } @@ -140969,7 +141946,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} usagesPerScope[i].usages.forEach((value) => { if (value.usage === 2 /* Write */) { hasWrite = true; - if (value.symbol.flags & 106500 /* ClassMember */ && value.symbol.valueDeclaration && hasEffectiveModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { + if (value.symbol.flags & 106500 /* ClassMember */ && value.symbol.valueDeclaration && hasEffectiveModifier(value.symbol.valueDeclaration, 8 /* Readonly */)) { readonlyClassPropertyWrite = value.symbol.valueDeclaration; } } @@ -141115,7 +142092,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return symbolId; } function checkForUsedDeclarations(node) { - if (node === targetRange.range || isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0) { + if (node === targetRange.range || isReadonlyArray(targetRange.range) && targetRange.range.includes(node)) { return; } const sym = isIdentifier(node) ? getSymbolReferencedByIdentifier(node) : checker.getSymbolAtLocation(node); @@ -141388,7 +142365,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getInfo4(context) { if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) return; - const token = getTokenAtPosition(context.file, context.startPosition); + const token = getTouchingPropertyName(context.file, context.startPosition); const declaration = findAncestor(token, (n) => isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === 39 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : isConvertibleDeclaration(n)); if (!declaration || !declaration.body || declaration.type) { return { error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) }; @@ -141591,14 +142568,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (decl) { const modifiers = getCombinedModifierFlags(decl); const nodeFlags = getCombinedNodeFlags(decl); - if (modifiers & 32 /* Static */) { + if (modifiers & 256 /* Static */) { modifierSet |= 1 << 1 /* static */; } - if (modifiers & 512 /* Async */) { + if (modifiers & 1024 /* Async */) { modifierSet |= 1 << 2 /* async */; } if (typeIdx !== 0 /* class */ && typeIdx !== 2 /* interface */) { - if (modifiers & 64 /* Readonly */ || nodeFlags & 2 /* Const */ || symbol.getFlags() & 8 /* EnumMember */) { + if (modifiers & 8 /* Readonly */ || nodeFlags & 2 /* Const */ || symbol.getFlags() & 8 /* EnumMember */) { modifierSet |= 1 << 3 /* readonly */; } } @@ -141967,7 +142944,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const options = { languageVersion: sourceFile.languageVersion, impliedNodeFormat: sourceFile.impliedNodeFormat, - setExternalModuleIndicator: sourceFile.setExternalModuleIndicator + setExternalModuleIndicator: sourceFile.setExternalModuleIndicator, + jsDocParsingMode: sourceFile.jsDocParsingMode }; return createLanguageServiceSourceFile( sourceFile.fileName, @@ -142085,7 +143063,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} resolveTypeReferenceDirectiveReferences: maybeBind(host, host.resolveTypeReferenceDirectiveReferences), resolveLibrary: maybeBind(host, host.resolveLibrary), useSourceOfProjectReferenceRedirect: maybeBind(host, host.useSourceOfProjectReferenceRedirect), - getParsedCommandLine + getParsedCommandLine, + jsDocParsingMode: host.jsDocParsingMode }; const originalGetSourceFile = compilerHost.getSourceFile; const { getSourceFileWithCache } = changeCompilerHostLikeToUseCache( @@ -142348,10 +143327,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} tags: type.symbol ? type.symbol.getJsDocTags(typeChecker) : void 0 }; } - const { symbolKind, displayParts, documentation, tags } = typeChecker.runWithCancellationToken( - cancellationToken, - (typeChecker2) => ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker2, symbol, sourceFile, getContainerNode(nodeForQuickInfo), nodeForQuickInfo) - ); + const { symbolKind, displayParts, documentation, tags } = typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2) => ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker2, symbol, sourceFile, getContainerNode(nodeForQuickInfo), nodeForQuickInfo)); return { kind: symbolKind, kindModifiers: ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol), @@ -142437,19 +143413,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else { const quotePreference = getQuotePreference(sourceFile, preferences ?? emptyOptions); const providePrefixAndSuffixTextForRename = typeof preferences === "boolean" ? preferences : preferences == null ? void 0 : preferences.providePrefixAndSuffixTextForRename; - return getReferencesWorker( - node, - position, - { findInStrings, findInComments, providePrefixAndSuffixTextForRename, use: ts_FindAllReferences_exports.FindReferencesUse.Rename }, - (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference) - ); + return getReferencesWorker2(node, position, { findInStrings, findInComments, providePrefixAndSuffixTextForRename, use: ts_FindAllReferences_exports.FindReferencesUse.Rename }, (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference)); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferencesWorker(getTouchingPropertyName(getValidSourceFile(fileName), position), position, { use: ts_FindAllReferences_exports.FindReferencesUse.References }, ts_FindAllReferences_exports.toReferenceEntry); + return getReferencesWorker2(getTouchingPropertyName(getValidSourceFile(fileName), position), position, { use: ts_FindAllReferences_exports.FindReferencesUse.References }, ts_FindAllReferences_exports.toReferenceEntry); } - function getReferencesWorker(node, position, options, cb) { + function getReferencesWorker2(node, position, options, cb) { synchronizeHostData(); const sourceFiles = options && options.use === ts_FindAllReferences_exports.FindReferencesUse.Rename ? program.getSourceFiles().filter((sourceFile) => !program.isSourceFileDefaultLibrary(sourceFile)) : program.getSourceFiles(); return ts_FindAllReferences_exports.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); @@ -142462,10 +143433,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} synchronizeHostData(); return ts_FindAllReferences_exports.Core.getReferencesForFileName(fileName, program, program.getSourceFiles()).map(ts_FindAllReferences_exports.toReferenceEntry); } - function getNavigateToItems2(searchValue, maxResultCount, fileName, excludeDtsFiles = false) { + function getNavigateToItems2(searchValue, maxResultCount, fileName, excludeDtsFiles = false, excludeLibFiles = false) { synchronizeHostData(); const sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); + return getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles, excludeLibFiles); } function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) { synchronizeHostData(); @@ -142701,15 +143672,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} wordPattern: jsxTagWordPattern }; } else { - const tag = findAncestor( - token.parent, - (n) => { - if (isJsxOpeningElement(n) || isJsxClosingElement(n)) { - return true; - } - return false; + const tag = findAncestor(token.parent, (n) => { + if (isJsxOpeningElement(n) || isJsxClosingElement(n)) { + return true; } - ); + return false; + }); if (!tag) return void 0; Debug.assert(isJsxOpeningElement(tag) || isJsxClosingElement(tag), "tag should be opening or closing element"); @@ -142765,7 +143733,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const lineTextStart = lineTextStarts.get(i.toString()); if (lineTextStart !== void 0) { if (isJsx) { - textChanges2.push.apply(textChanges2, toggleMultilineComment(fileName, { pos: lineStarts[i] + leftMostPosition, end: sourceFile.getLineEndOfPosition(lineStarts[i]) }, isCommenting, isJsx)); + textChanges2.push(...toggleMultilineComment(fileName, { pos: lineStarts[i] + leftMostPosition, end: sourceFile.getLineEndOfPosition(lineStarts[i]) }, isCommenting, isJsx)); } else if (isCommenting) { textChanges2.push({ newText: openComment, @@ -142908,7 +143876,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (commentRange) { switch (commentRange.kind) { case 2 /* SingleLineCommentTrivia */: - textChanges2.push.apply(textChanges2, toggleLineComment( + textChanges2.push(...toggleLineComment( fileName, { end: commentRange.end, pos: commentRange.pos + 1 }, /*insertComment*/ @@ -142916,7 +143884,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} )); break; case 3 /* MultiLineCommentTrivia */: - textChanges2.push.apply(textChanges2, toggleMultilineComment( + textChanges2.push(...toggleMultilineComment( fileName, { end: commentRange.end, pos: commentRange.pos + 1 }, /*insertComment*/ @@ -142992,7 +143960,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return char >= 97 /* a */ && char <= 122 /* z */ || char >= 65 /* A */ && char <= 90 /* Z */ || char >= 48 /* _0 */ && char <= 57 /* _9 */; } function isNodeModulesFile(path) { - return stringContains(path, "/node_modules/"); + return path.includes("/node_modules/"); } } function getRenameInfo2(fileName, position, preferences) { @@ -143739,7 +144707,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} forEachChild(node, visit); break; case 169 /* Parameter */: - if (!hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { + if (!hasSyntacticModifier(node, 31 /* ParameterPropertyModifier */)) { break; } case 260 /* VariableDeclaration */: @@ -143825,7 +144793,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} this.host, this.host.getCompilationSettings() ), - setExternalModuleIndicator: getSetExternalModuleIndicator(this.host.getCompilationSettings()) + setExternalModuleIndicator: getSetExternalModuleIndicator(this.host.getCompilationSettings()), + // These files are used to produce syntax-based highlighting, which reads JSDoc, so we must use ParseAll. + jsDocParsingMode: 0 /* ParseAll */ }; sourceFile = createLanguageServiceSourceFile( fileName, @@ -143964,947 +144934,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } }); - // src/services/shims.ts - function logInternalError(logger, err) { - if (logger) { - logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message); - } - } - function simpleForwardCall(logger, actionDescription2, action, logPerformance) { - let start; - if (logPerformance) { - logger.log(actionDescription2); - start = timestamp(); - } - const result = action(); - if (logPerformance) { - const end = timestamp(); - logger.log(`${actionDescription2} completed in ${end - start} msec`); - if (isString(result)) { - let str = result; - if (str.length > 128) { - str = str.substring(0, 128) + "..."; - } - logger.log(` result.length=${str.length}, result='${JSON.stringify(str)}'`); - } - } - return result; - } - function forwardJSONCall(logger, actionDescription2, action, logPerformance) { - return forwardCall( - logger, - actionDescription2, - /*returnJson*/ - true, - action, - logPerformance - ); - } - function forwardCall(logger, actionDescription2, returnJson, action, logPerformance) { - try { - const result = simpleForwardCall(logger, actionDescription2, action, logPerformance); - return returnJson ? JSON.stringify({ result }) : result; - } catch (err) { - if (err instanceof OperationCanceledException) { - return JSON.stringify({ canceled: true }); - } - logInternalError(logger, err); - err.description = actionDescription2; - return JSON.stringify({ error: err }); - } - } - function realizeDiagnostics(diagnostics, newLine) { - return diagnostics.map((d) => realizeDiagnostic(d, newLine)); - } - function realizeDiagnostic(diagnostic, newLine) { - return { - message: flattenDiagnosticMessageText(diagnostic.messageText, newLine), - start: diagnostic.start, - // TODO: GH#18217 - length: diagnostic.length, - // TODO: GH#18217 - category: diagnosticCategoryName(diagnostic), - code: diagnostic.code, - reportsUnnecessary: diagnostic.reportsUnnecessary, - reportsDeprecated: diagnostic.reportsDeprecated - }; - } - function convertClassifications(classifications) { - return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; - } - var debugObjectHost, ScriptSnapshotShimAdapter, LanguageServiceShimHostAdapter, CoreServicesShimHostAdapter, ShimBase, LanguageServiceShimObject, ClassifierShimObject, CoreServicesShimObject, TypeScriptServicesFactory; - var init_shims = __esm({ - "src/services/shims.ts"() { - "use strict"; - init_ts4(); - debugObjectHost = function() { - return this; - }(); - ScriptSnapshotShimAdapter = class { - constructor(scriptSnapshotShim) { - this.scriptSnapshotShim = scriptSnapshotShim; - } - getText(start, end) { - return this.scriptSnapshotShim.getText(start, end); - } - getLength() { - return this.scriptSnapshotShim.getLength(); - } - getChangeRange(oldSnapshot) { - const oldSnapshotShim = oldSnapshot; - const encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); - if (encoded === null) { - return null; - } - const decoded = JSON.parse(encoded); - return createTextChangeRange( - createTextSpan(decoded.span.start, decoded.span.length), - decoded.newLength - ); - } - dispose() { - if ("dispose" in this.scriptSnapshotShim) { - this.scriptSnapshotShim.dispose(); - } - } - }; - LanguageServiceShimHostAdapter = class { - constructor(shimHost) { - this.shimHost = shimHost; - this.loggingEnabled = false; - this.tracingEnabled = false; - if ("getModuleResolutionsForFile" in this.shimHost) { - this.resolveModuleNames = (moduleNames, containingFile) => { - const resolutionsInFile = JSON.parse(this.shimHost.getModuleResolutionsForFile(containingFile)); - return map(moduleNames, (name) => { - const result = getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result, extension: extensionFromPath(result), isExternalLibraryImport: false } : void 0; - }); - }; - } - if ("directoryExists" in this.shimHost) { - this.directoryExists = (directoryName) => this.shimHost.directoryExists(directoryName); - } - if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { - this.resolveTypeReferenceDirectives = (typeDirectiveNames, containingFile) => { - const typeDirectivesForFile = JSON.parse(this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return map(typeDirectiveNames, (name) => getProperty(typeDirectivesForFile, isString(name) ? name : toFileNameLowerCase(name.fileName))); - }; - } - } - log(s) { - if (this.loggingEnabled) { - this.shimHost.log(s); - } - } - trace(s) { - if (this.tracingEnabled) { - this.shimHost.trace(s); - } - } - error(s) { - this.shimHost.error(s); - } - getProjectVersion() { - if (!this.shimHost.getProjectVersion) { - return void 0; - } - return this.shimHost.getProjectVersion(); - } - getTypeRootsVersion() { - if (!this.shimHost.getTypeRootsVersion) { - return 0; - } - return this.shimHost.getTypeRootsVersion(); - } - useCaseSensitiveFileNames() { - return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; - } - getCompilationSettings() { - const settingsJson = this.shimHost.getCompilationSettings(); - if (settingsJson === null || settingsJson === "") { - throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); - } - const compilerOptions = JSON.parse(settingsJson); - compilerOptions.allowNonTsExtensions = true; - return compilerOptions; - } - getScriptFileNames() { - const encoded = this.shimHost.getScriptFileNames(); - return JSON.parse(encoded); - } - getScriptSnapshot(fileName) { - const scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); - return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); - } - getScriptKind(fileName) { - if ("getScriptKind" in this.shimHost) { - return this.shimHost.getScriptKind(fileName); - } else { - return 0 /* Unknown */; - } - } - getScriptVersion(fileName) { - return this.shimHost.getScriptVersion(fileName); - } - getLocalizedDiagnosticMessages() { - const diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages(); - if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") { - return null; - } - try { - return JSON.parse(diagnosticMessagesJson); - } catch (e) { - this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format"); - return null; - } - } - getCancellationToken() { - const hostCancellationToken = this.shimHost.getCancellationToken(); - return new ThrottledCancellationToken(hostCancellationToken); - } - getCurrentDirectory() { - return this.shimHost.getCurrentDirectory(); - } - getDirectories(path) { - return JSON.parse(this.shimHost.getDirectories(path)); - } - getDefaultLibFileName(options) { - return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); - } - readDirectory(path, extensions, exclude, include, depth) { - const pattern = getFileMatcherPatterns( - path, - exclude, - include, - this.shimHost.useCaseSensitiveFileNames(), - this.shimHost.getCurrentDirectory() - ); - return JSON.parse(this.shimHost.readDirectory( - path, - JSON.stringify(extensions), - JSON.stringify(pattern.basePaths), - pattern.excludePattern, - pattern.includeFilePattern, - pattern.includeDirectoryPattern, - depth - )); - } - readFile(path, encoding) { - return this.shimHost.readFile(path, encoding); - } - fileExists(path) { - return this.shimHost.fileExists(path); - } - }; - CoreServicesShimHostAdapter = class { - constructor(shimHost) { - this.shimHost = shimHost; - this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; - if ("directoryExists" in this.shimHost) { - this.directoryExists = (directoryName) => this.shimHost.directoryExists(directoryName); - } else { - this.directoryExists = void 0; - } - if ("realpath" in this.shimHost) { - this.realpath = (path) => this.shimHost.realpath(path); - } else { - this.realpath = void 0; - } - } - readDirectory(rootDir, extensions, exclude, include, depth) { - const pattern = getFileMatcherPatterns( - rootDir, - exclude, - include, - this.shimHost.useCaseSensitiveFileNames(), - this.shimHost.getCurrentDirectory() - ); - return JSON.parse(this.shimHost.readDirectory( - rootDir, - JSON.stringify(extensions), - JSON.stringify(pattern.basePaths), - pattern.excludePattern, - pattern.includeFilePattern, - pattern.includeDirectoryPattern, - depth - )); - } - fileExists(fileName) { - return this.shimHost.fileExists(fileName); - } - readFile(fileName) { - return this.shimHost.readFile(fileName); - } - getDirectories(path) { - return JSON.parse(this.shimHost.getDirectories(path)); - } - }; - ShimBase = class { - constructor(factory2) { - this.factory = factory2; - factory2.registerShim(this); - } - dispose(_dummy) { - this.factory.unregisterShim(this); - } - }; - LanguageServiceShimObject = class extends ShimBase { - constructor(factory2, host, languageService) { - super(factory2); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; - } - forwardJSONCall(actionDescription2, action) { - return forwardJSONCall(this.logger, actionDescription2, action, this.logPerformance); - } - /// DISPOSE - /** - * Ensure (almost) deterministic release of internal Javascript resources when - * some external native objects holds onto us (e.g. Com/Interop). - */ - dispose(dummy) { - this.logger.log("dispose()"); - this.languageService.dispose(); - this.languageService = null; - if (debugObjectHost && debugObjectHost.CollectGarbage) { - debugObjectHost.CollectGarbage(); - this.logger.log("CollectGarbage()"); - } - this.logger = null; - super.dispose(dummy); - } - /// REFRESH - /** - * Update the list of scripts known to the compiler - */ - refresh(throwOnError) { - this.forwardJSONCall( - `refresh(${throwOnError})`, - () => null - // eslint-disable-line no-null/no-null - ); - } - cleanupSemanticCache() { - this.forwardJSONCall( - "cleanupSemanticCache()", - () => { - this.languageService.cleanupSemanticCache(); - return null; - } - ); - } - realizeDiagnostics(diagnostics) { - const newLine = getNewLineOrDefaultFromHost( - this.host, - /*formatSettings*/ - void 0 - ); - return realizeDiagnostics(diagnostics, newLine); - } - getSyntacticClassifications(fileName, start, length2) { - return this.forwardJSONCall( - `getSyntacticClassifications('${fileName}', ${start}, ${length2})`, - () => this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length2)) - ); - } - getSemanticClassifications(fileName, start, length2) { - return this.forwardJSONCall( - `getSemanticClassifications('${fileName}', ${start}, ${length2})`, - () => this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length2)) - ); - } - getEncodedSyntacticClassifications(fileName, start, length2) { - return this.forwardJSONCall( - `getEncodedSyntacticClassifications('${fileName}', ${start}, ${length2})`, - // directly serialize the spans out to a string. This is much faster to decode - // on the managed side versus a full JSON array. - () => convertClassifications(this.languageService.getEncodedSyntacticClassifications(fileName, createTextSpan(start, length2))) - ); - } - getEncodedSemanticClassifications(fileName, start, length2) { - return this.forwardJSONCall( - `getEncodedSemanticClassifications('${fileName}', ${start}, ${length2})`, - // directly serialize the spans out to a string. This is much faster to decode - // on the managed side versus a full JSON array. - () => convertClassifications(this.languageService.getEncodedSemanticClassifications(fileName, createTextSpan(start, length2))) - ); - } - getSyntacticDiagnostics(fileName) { - return this.forwardJSONCall( - `getSyntacticDiagnostics('${fileName}')`, - () => { - const diagnostics = this.languageService.getSyntacticDiagnostics(fileName); - return this.realizeDiagnostics(diagnostics); - } - ); - } - getSemanticDiagnostics(fileName) { - return this.forwardJSONCall( - `getSemanticDiagnostics('${fileName}')`, - () => { - const diagnostics = this.languageService.getSemanticDiagnostics(fileName); - return this.realizeDiagnostics(diagnostics); - } - ); - } - getSuggestionDiagnostics(fileName) { - return this.forwardJSONCall(`getSuggestionDiagnostics('${fileName}')`, () => this.realizeDiagnostics(this.languageService.getSuggestionDiagnostics(fileName))); - } - getCompilerOptionsDiagnostics() { - return this.forwardJSONCall( - "getCompilerOptionsDiagnostics()", - () => { - const diagnostics = this.languageService.getCompilerOptionsDiagnostics(); - return this.realizeDiagnostics(diagnostics); - } - ); - } - /// QUICKINFO - /** - * Computes a string representation of the type at the requested position - * in the active file. - */ - getQuickInfoAtPosition(fileName, position) { - return this.forwardJSONCall( - `getQuickInfoAtPosition('${fileName}', ${position})`, - () => this.languageService.getQuickInfoAtPosition(fileName, position) - ); - } - /// NAMEORDOTTEDNAMESPAN - /** - * Computes span information of the name or dotted name at the requested position - * in the active file. - */ - getNameOrDottedNameSpan(fileName, startPos, endPos) { - return this.forwardJSONCall( - `getNameOrDottedNameSpan('${fileName}', ${startPos}, ${endPos})`, - () => this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos) - ); - } - /** - * STATEMENTSPAN - * Computes span information of statement at the requested position in the active file. - */ - getBreakpointStatementAtPosition(fileName, position) { - return this.forwardJSONCall( - `getBreakpointStatementAtPosition('${fileName}', ${position})`, - () => this.languageService.getBreakpointStatementAtPosition(fileName, position) - ); - } - /// SIGNATUREHELP - getSignatureHelpItems(fileName, position, options) { - return this.forwardJSONCall( - `getSignatureHelpItems('${fileName}', ${position})`, - () => this.languageService.getSignatureHelpItems(fileName, position, options) - ); - } - /// GOTO DEFINITION - /** - * Computes the definition location and file for the symbol - * at the requested position. - */ - getDefinitionAtPosition(fileName, position) { - return this.forwardJSONCall( - `getDefinitionAtPosition('${fileName}', ${position})`, - () => this.languageService.getDefinitionAtPosition(fileName, position) - ); - } - /** - * Computes the definition location and file for the symbol - * at the requested position. - */ - getDefinitionAndBoundSpan(fileName, position) { - return this.forwardJSONCall( - `getDefinitionAndBoundSpan('${fileName}', ${position})`, - () => this.languageService.getDefinitionAndBoundSpan(fileName, position) - ); - } - /// GOTO Type - /** - * Computes the definition location of the type of the symbol - * at the requested position. - */ - getTypeDefinitionAtPosition(fileName, position) { - return this.forwardJSONCall( - `getTypeDefinitionAtPosition('${fileName}', ${position})`, - () => this.languageService.getTypeDefinitionAtPosition(fileName, position) - ); - } - /// GOTO Implementation - /** - * Computes the implementation location of the symbol - * at the requested position. - */ - getImplementationAtPosition(fileName, position) { - return this.forwardJSONCall( - `getImplementationAtPosition('${fileName}', ${position})`, - () => this.languageService.getImplementationAtPosition(fileName, position) - ); - } - getRenameInfo(fileName, position, preferences) { - return this.forwardJSONCall( - `getRenameInfo('${fileName}', ${position})`, - () => this.languageService.getRenameInfo(fileName, position, preferences) - ); - } - getSmartSelectionRange(fileName, position) { - return this.forwardJSONCall( - `getSmartSelectionRange('${fileName}', ${position})`, - () => this.languageService.getSmartSelectionRange(fileName, position) - ); - } - findRenameLocations(fileName, position, findInStrings, findInComments, preferences) { - return this.forwardJSONCall( - `findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments})`, - () => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, preferences) - ); - } - /// GET BRACE MATCHING - getBraceMatchingAtPosition(fileName, position) { - return this.forwardJSONCall( - `getBraceMatchingAtPosition('${fileName}', ${position})`, - () => this.languageService.getBraceMatchingAtPosition(fileName, position) - ); - } - isValidBraceCompletionAtPosition(fileName, position, openingBrace) { - return this.forwardJSONCall( - `isValidBraceCompletionAtPosition('${fileName}', ${position}, ${openingBrace})`, - () => this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace) - ); - } - getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { - return this.forwardJSONCall( - `getSpanOfEnclosingComment('${fileName}', ${position})`, - () => this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine) - ); - } - /// GET SMART INDENT - getIndentationAtPosition(fileName, position, options) { - return this.forwardJSONCall( - `getIndentationAtPosition('${fileName}', ${position})`, - () => { - const localOptions = JSON.parse(options); - return this.languageService.getIndentationAtPosition(fileName, position, localOptions); - } - ); - } - /// GET REFERENCES - getReferencesAtPosition(fileName, position) { - return this.forwardJSONCall( - `getReferencesAtPosition('${fileName}', ${position})`, - () => this.languageService.getReferencesAtPosition(fileName, position) - ); - } - findReferences(fileName, position) { - return this.forwardJSONCall( - `findReferences('${fileName}', ${position})`, - () => this.languageService.findReferences(fileName, position) - ); - } - getFileReferences(fileName) { - return this.forwardJSONCall( - `getFileReferences('${fileName})`, - () => this.languageService.getFileReferences(fileName) - ); - } - getDocumentHighlights(fileName, position, filesToSearch) { - return this.forwardJSONCall( - `getDocumentHighlights('${fileName}', ${position})`, - () => { - const results = this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch)); - const normalizedName = toFileNameLowerCase(normalizeSlashes(fileName)); - return filter(results, (r) => toFileNameLowerCase(normalizeSlashes(r.fileName)) === normalizedName); - } - ); - } - /// COMPLETION LISTS - /** - * Get a string based representation of the completions - * to provide at the given source position and providing a member completion - * list if requested. - */ - getCompletionsAtPosition(fileName, position, preferences, formattingSettings) { - return this.forwardJSONCall( - `getCompletionsAtPosition('${fileName}', ${position}, ${preferences}, ${formattingSettings})`, - () => this.languageService.getCompletionsAtPosition(fileName, position, preferences, formattingSettings) - ); - } - /** Get a string based representation of a completion list entry details */ - getCompletionEntryDetails(fileName, position, entryName, formatOptions, source, preferences, data) { - return this.forwardJSONCall( - `getCompletionEntryDetails('${fileName}', ${position}, '${entryName}')`, - () => { - const localOptions = formatOptions === void 0 ? void 0 : JSON.parse(formatOptions); - return this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences, data); - } - ); - } - getFormattingEditsForRange(fileName, start, end, options) { - return this.forwardJSONCall( - `getFormattingEditsForRange('${fileName}', ${start}, ${end})`, - () => { - const localOptions = JSON.parse(options); - return this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); - } - ); - } - getFormattingEditsForDocument(fileName, options) { - return this.forwardJSONCall( - `getFormattingEditsForDocument('${fileName}')`, - () => { - const localOptions = JSON.parse(options); - return this.languageService.getFormattingEditsForDocument(fileName, localOptions); - } - ); - } - getFormattingEditsAfterKeystroke(fileName, position, key, options) { - return this.forwardJSONCall( - `getFormattingEditsAfterKeystroke('${fileName}', ${position}, '${key}')`, - () => { - const localOptions = JSON.parse(options); - return this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); - } - ); - } - getDocCommentTemplateAtPosition(fileName, position, options, formatOptions) { - return this.forwardJSONCall( - `getDocCommentTemplateAtPosition('${fileName}', ${position})`, - () => this.languageService.getDocCommentTemplateAtPosition(fileName, position, options, formatOptions) - ); - } - /// NAVIGATE TO - /** Return a list of symbols that are interesting to navigate to */ - getNavigateToItems(searchValue, maxResultCount, fileName) { - return this.forwardJSONCall( - `getNavigateToItems('${searchValue}', ${maxResultCount}, ${fileName})`, - () => this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName) - ); - } - getNavigationBarItems(fileName) { - return this.forwardJSONCall( - `getNavigationBarItems('${fileName}')`, - () => this.languageService.getNavigationBarItems(fileName) - ); - } - getNavigationTree(fileName) { - return this.forwardJSONCall( - `getNavigationTree('${fileName}')`, - () => this.languageService.getNavigationTree(fileName) - ); - } - getOutliningSpans(fileName) { - return this.forwardJSONCall( - `getOutliningSpans('${fileName}')`, - () => this.languageService.getOutliningSpans(fileName) - ); - } - getTodoComments(fileName, descriptors) { - return this.forwardJSONCall( - `getTodoComments('${fileName}')`, - () => this.languageService.getTodoComments(fileName, JSON.parse(descriptors)) - ); - } - /// CALL HIERARCHY - prepareCallHierarchy(fileName, position) { - return this.forwardJSONCall( - `prepareCallHierarchy('${fileName}', ${position})`, - () => this.languageService.prepareCallHierarchy(fileName, position) - ); - } - provideCallHierarchyIncomingCalls(fileName, position) { - return this.forwardJSONCall( - `provideCallHierarchyIncomingCalls('${fileName}', ${position})`, - () => this.languageService.provideCallHierarchyIncomingCalls(fileName, position) - ); - } - provideCallHierarchyOutgoingCalls(fileName, position) { - return this.forwardJSONCall( - `provideCallHierarchyOutgoingCalls('${fileName}', ${position})`, - () => this.languageService.provideCallHierarchyOutgoingCalls(fileName, position) - ); - } - provideInlayHints(fileName, span, preference) { - return this.forwardJSONCall( - `provideInlayHints('${fileName}', '${JSON.stringify(span)}', ${JSON.stringify(preference)})`, - () => this.languageService.provideInlayHints(fileName, span, preference) - ); - } - /// Emit - getEmitOutput(fileName) { - return this.forwardJSONCall( - `getEmitOutput('${fileName}')`, - () => { - const { diagnostics, ...rest } = this.languageService.getEmitOutput(fileName); - return { ...rest, diagnostics: this.realizeDiagnostics(diagnostics) }; - } - ); - } - getEmitOutputObject(fileName) { - return forwardCall( - this.logger, - `getEmitOutput('${fileName}')`, - /*returnJson*/ - false, - () => this.languageService.getEmitOutput(fileName), - this.logPerformance - ); - } - toggleLineComment(fileName, textRange) { - return this.forwardJSONCall( - `toggleLineComment('${fileName}', '${JSON.stringify(textRange)}')`, - () => this.languageService.toggleLineComment(fileName, textRange) - ); - } - toggleMultilineComment(fileName, textRange) { - return this.forwardJSONCall( - `toggleMultilineComment('${fileName}', '${JSON.stringify(textRange)}')`, - () => this.languageService.toggleMultilineComment(fileName, textRange) - ); - } - commentSelection(fileName, textRange) { - return this.forwardJSONCall( - `commentSelection('${fileName}', '${JSON.stringify(textRange)}')`, - () => this.languageService.commentSelection(fileName, textRange) - ); - } - uncommentSelection(fileName, textRange) { - return this.forwardJSONCall( - `uncommentSelection('${fileName}', '${JSON.stringify(textRange)}')`, - () => this.languageService.uncommentSelection(fileName, textRange) - ); - } - }; - ClassifierShimObject = class extends ShimBase { - constructor(factory2, logger) { - super(factory2); - this.logger = logger; - this.logPerformance = false; - this.classifier = createClassifier(); - } - getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent = false) { - return forwardJSONCall( - this.logger, - "getEncodedLexicalClassifications", - () => convertClassifications(this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)), - this.logPerformance - ); - } - /// COLORIZATION - getClassificationsForLine(text, lexState, classifyKeywordsInGenerics = false) { - const classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); - let result = ""; - for (const item of classification.entries) { - result += item.length + "\n"; - result += item.classification + "\n"; - } - result += classification.finalLexState; - return result; - } - }; - CoreServicesShimObject = class extends ShimBase { - constructor(factory2, logger, host) { - super(factory2); - this.logger = logger; - this.host = host; - this.logPerformance = false; - } - forwardJSONCall(actionDescription2, action) { - return forwardJSONCall(this.logger, actionDescription2, action, this.logPerformance); - } - resolveModuleName(fileName, moduleName, compilerOptionsJson) { - return this.forwardJSONCall(`resolveModuleName('${fileName}')`, () => { - const compilerOptions = JSON.parse(compilerOptionsJson); - const result = resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host); - let resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : void 0; - if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */) { - resolvedFileName = void 0; - } - return { - resolvedFileName, - failedLookupLocations: result.failedLookupLocations, - affectingLocations: result.affectingLocations - }; - }); - } - resolveTypeReferenceDirective(fileName, typeReferenceDirective, compilerOptionsJson) { - return this.forwardJSONCall(`resolveTypeReferenceDirective(${fileName})`, () => { - const compilerOptions = JSON.parse(compilerOptionsJson); - const result = resolveTypeReferenceDirective(typeReferenceDirective, normalizeSlashes(fileName), compilerOptions, this.host); - return { - resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : void 0, - primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true, - failedLookupLocations: result.failedLookupLocations - }; - }); - } - getPreProcessedFileInfo(fileName, sourceTextSnapshot) { - return this.forwardJSONCall( - `getPreProcessedFileInfo('${fileName}')`, - () => { - const result = preProcessFile( - getSnapshotText(sourceTextSnapshot), - /*readImportFiles*/ - true, - /*detectJavaScriptImports*/ - true - ); - return { - referencedFiles: this.convertFileReferences(result.referencedFiles), - importedFiles: this.convertFileReferences(result.importedFiles), - ambientExternalModules: result.ambientExternalModules, - isLibFile: result.isLibFile, - typeReferenceDirectives: this.convertFileReferences(result.typeReferenceDirectives), - libReferenceDirectives: this.convertFileReferences(result.libReferenceDirectives) - }; - } - ); - } - getAutomaticTypeDirectiveNames(compilerOptionsJson) { - return this.forwardJSONCall( - `getAutomaticTypeDirectiveNames('${compilerOptionsJson}')`, - () => { - const compilerOptions = JSON.parse(compilerOptionsJson); - return getAutomaticTypeDirectiveNames(compilerOptions, this.host); - } - ); - } - convertFileReferences(refs) { - if (!refs) { - return void 0; - } - const result = []; - for (const ref of refs) { - result.push({ - path: normalizeSlashes(ref.fileName), - position: ref.pos, - length: ref.end - ref.pos - }); - } - return result; - } - getTSConfigFileInfo(fileName, sourceTextSnapshot) { - return this.forwardJSONCall( - `getTSConfigFileInfo('${fileName}')`, - () => { - const result = parseJsonText(fileName, getSnapshotText(sourceTextSnapshot)); - const normalizedFileName = normalizeSlashes(fileName); - const configFile = parseJsonSourceFileConfigFileContent( - result, - this.host, - getDirectoryPath(normalizedFileName), - /*existingOptions*/ - {}, - normalizedFileName - ); - return { - options: configFile.options, - typeAcquisition: configFile.typeAcquisition, - files: configFile.fileNames, - raw: configFile.raw, - errors: realizeDiagnostics([...result.parseDiagnostics, ...configFile.errors], "\r\n") - }; - } - ); - } - getDefaultCompilationSettings() { - return this.forwardJSONCall( - "getDefaultCompilationSettings()", - () => getDefaultCompilerOptions2() - ); - } - discoverTypings(discoverTypingsJson) { - const getCanonicalFileName = createGetCanonicalFileName( - /*useCaseSensitiveFileNames*/ - false - ); - return this.forwardJSONCall("discoverTypings()", () => { - const info = JSON.parse(discoverTypingsJson); - if (this.safeList === void 0) { - this.safeList = ts_JsTyping_exports.loadSafeList(this.host, toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); - } - return ts_JsTyping_exports.discoverTypings( - this.host, - (msg) => this.logger.log(msg), - info.fileNames, - toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), - this.safeList, - info.packageNameToTypingLocation, - info.typeAcquisition, - info.unresolvedImports, - info.typesRegistry, - emptyOptions - ); - }); - } - }; - TypeScriptServicesFactory = class { - constructor() { - this._shims = []; - } - /* - * Returns script API version. - */ - getServicesVersion() { - return servicesVersion; - } - createLanguageServiceShim(host) { - try { - if (this.documentRegistry === void 0) { - this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); - } - const hostAdapter = new LanguageServiceShimHostAdapter(host); - const languageService = createLanguageService( - hostAdapter, - this.documentRegistry, - /*syntaxOnlyOrLanguageServiceMode*/ - false - ); - return new LanguageServiceShimObject(this, host, languageService); - } catch (err) { - logInternalError(host, err); - throw err; - } - } - createClassifierShim(logger) { - try { - return new ClassifierShimObject(this, logger); - } catch (err) { - logInternalError(logger, err); - throw err; - } - } - createCoreServicesShim(host) { - try { - const adapter = new CoreServicesShimHostAdapter(host); - return new CoreServicesShimObject(this, host, adapter); - } catch (err) { - logInternalError(host, err); - throw err; - } - } - close() { - clear(this._shims); - this.documentRegistry = void 0; - } - registerShim(shim) { - this._shims.push(shim); - } - unregisterShim(shim) { - for (let i = 0; i < this._shims.length; i++) { - if (this._shims[i] === shim) { - delete this._shims[i]; - return; - } - } - throw new Error("Invalid operation"); - } - }; - } - }); - // src/services/breakpoints.ts function spanInSourceFileAtLocation(sourceFile, position) { if (sourceFile.isDeclarationFile) { @@ -145165,7 +145194,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isBindingPattern(variableDeclaration.name)) { return spanInBindingPattern(variableDeclaration.name); } - if (hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer || hasSyntacticModifier(variableDeclaration, 1 /* Export */) || parent2.parent.kind === 250 /* ForOfStatement */) { + if (hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer || hasSyntacticModifier(variableDeclaration, 32 /* Export */) || parent2.parent.kind === 250 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] !== variableDeclaration) { @@ -145173,7 +145202,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function canHaveSpanInParameterDeclaration(parameter) { - return !!parameter.initializer || parameter.dotDotDotToken !== void 0 || hasSyntacticModifier(parameter, 4 /* Public */ | 8 /* Private */); + return !!parameter.initializer || parameter.dotDotDotToken !== void 0 || hasSyntacticModifier(parameter, 1 /* Public */ | 2 /* Private */); } function spanInParameterDeclaration(parameter) { if (isBindingPattern(parameter.name)) { @@ -145192,7 +145221,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return hasSyntacticModifier(functionDeclaration, 1 /* Export */) || functionDeclaration.parent.kind === 263 /* ClassDeclaration */ && functionDeclaration.kind !== 176 /* Constructor */; + return hasSyntacticModifier(functionDeclaration, 32 /* Export */) || functionDeclaration.parent.kind === 263 /* ClassDeclaration */ && functionDeclaration.kind !== 176 /* Constructor */; } function spanInFunctionDeclaration(functionDeclaration) { if (!functionDeclaration.body) { @@ -145248,10 +145277,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function spanInBindingPattern(bindingPattern) { - const firstBindingElement = forEach( - bindingPattern.elements, - (element) => element.kind !== 232 /* OmittedExpression */ ? element : void 0 - ); + const firstBindingElement = forEach(bindingPattern.elements, (element) => element.kind !== 232 /* OmittedExpression */ ? element : void 0); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -145263,10 +145289,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node2) { Debug.assert(node2.kind !== 207 /* ArrayBindingPattern */ && node2.kind !== 206 /* ObjectBindingPattern */); const elements = node2.kind === 209 /* ArrayLiteralExpression */ ? node2.elements : node2.properties; - const firstBindingElement = forEach( - elements, - (element) => element.kind !== 232 /* OmittedExpression */ ? element : void 0 - ); + const firstBindingElement = forEach(elements, (element) => element.kind !== 232 /* OmittedExpression */ ? element : void 0); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -145769,7 +145792,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} forEach(node.statements, collect); } function collectCallSitesOfModuleDeclaration(node, collect) { - if (!hasSyntacticModifier(node, 2 /* Ambient */) && node.body && isModuleBlock(node.body)) { + if (!hasSyntacticModifier(node, 128 /* Ambient */) && node.body && isModuleBlock(node.body)) { forEach(node.body.statements, collect); } } @@ -146070,13 +146093,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } fixedDeclarations == null ? void 0 : fixedDeclarations.add(getNodeId(insertionSite)); - const cloneWithModifier = factory.updateModifiers( + const cloneWithModifier = factory.replaceModifiers( getSynthesizedDeepClone( insertionSite, /*includeTrivia*/ true ), - factory.createNodeArray(factory.createModifiersFromModifierFlags(getSyntacticModifierFlags(insertionSite) | 512 /* Async */)) + factory.createNodeArray(factory.createModifiersFromModifierFlags(getSyntacticModifierFlags(insertionSite) | 1024 /* Async */)) ); changeTracker.replaceNode( sourceFile, @@ -146188,7 +146211,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const declaration = tryCast(symbol.valueDeclaration, isVariableDeclaration); const variableName = declaration && tryCast(declaration.name, isIdentifier); const variableStatement = getAncestor(declaration, 243 /* VariableStatement */); - if (!declaration || !variableStatement || declaration.type || !declaration.initializer || variableStatement.getSourceFile() !== sourceFile || hasSyntacticModifier(variableStatement, 1 /* Export */) || !variableName || !isInsideAwaitableBody(declaration.initializer)) { + if (!declaration || !variableStatement || declaration.type || !declaration.initializer || variableStatement.getSourceFile() !== sourceFile || hasSyntacticModifier(variableStatement, 32 /* Export */) || !variableName || !isInsideAwaitableBody(declaration.initializer)) { isCompleteFix = false; continue; } @@ -146246,7 +146269,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} checker.getTypeAtLocation(errorNode).flags & 1 /* Any */; } function isInsideAwaitableBody(node) { - return node.kind & 65536 /* AwaitContext */ || !!findAncestor(node, (ancestor) => ancestor.parent && isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || isBlock(ancestor) && (ancestor.parent.kind === 262 /* FunctionDeclaration */ || ancestor.parent.kind === 218 /* FunctionExpression */ || ancestor.parent.kind === 219 /* ArrowFunction */ || ancestor.parent.kind === 174 /* MethodDeclaration */)); + return node.flags & 65536 /* AwaitContext */ || !!findAncestor(node, (ancestor) => ancestor.parent && isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || isBlock(ancestor) && (ancestor.parent.kind === 262 /* FunctionDeclaration */ || ancestor.parent.kind === 218 /* FunctionExpression */ || ancestor.parent.kind === 219 /* ArrowFunction */ || ancestor.parent.kind === 174 /* MethodDeclaration */)); } function makeChange3(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { if (isForOfStatement(insertionSite.parent) && !insertionSite.parent.awaitModifier) { @@ -146375,10 +146398,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/addMissingConst.ts function makeChange4(changeTracker, sourceFile, pos, program, fixedNodes) { const token = getTokenAtPosition(sourceFile, pos); - const forInitializer = findAncestor( - token, - (node) => isForInOrOfStatement(node.parent) ? node.parent.initializer === node : isPossiblyPartOfDestructuring(node) ? false : "quit" - ); + const forInitializer = findAncestor(token, (node) => isForInOrOfStatement(node.parent) ? node.parent.initializer === node : isPossiblyPartOfDestructuring(node) ? false : "quit"); if (forInitializer) return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes); const parent2 = token.parent; @@ -146392,10 +146412,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return applyChange(changeTracker, parent2, sourceFile, fixedNodes); } - const commaExpression = findAncestor( - token, - (node) => isExpressionStatement(node.parent) ? true : isPossiblyPartOfCommaSeperatedInitializer(node) ? false : "quit" - ); + const commaExpression = findAncestor(token, (node) => isExpressionStatement(node.parent) ? true : isPossiblyPartOfCommaSeperatedInitializer(node) ? false : "quit"); if (commaExpression) { const checker = program.getTypeChecker(); if (!expressionCouldBeVariableDeclaration(commaExpression, checker)) { @@ -146549,8 +146566,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }); // src/services/codefixes/addNameToNamelessParameter.ts - function makeChange7(changeTracker, sourceFile, pos) { - const token = getTokenAtPosition(sourceFile, pos); + function makeChange7(changeTracker, sourceFile, start) { + const token = getTokenAtPosition(sourceFile, start); const param = token.parent; if (!isParameter(param)) { return Debug.fail("Tried to add a parameter name to a non-parameter: " + Debug.formatSyntaxKind(token.kind)); @@ -146558,20 +146575,34 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const i = param.parent.parameters.indexOf(param); Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); Debug.assert(i > -1, "Parameter not found in parent parameter list."); - const typeNode = factory.createTypeReferenceNode( + let end = param.name.getEnd(); + let typeNode = factory.createTypeReferenceNode( param.name, /*typeArguments*/ void 0 ); + let nextParam = tryGetNextParam(sourceFile, param); + while (nextParam) { + typeNode = factory.createArrayTypeNode(typeNode); + end = nextParam.getEnd(); + nextParam = tryGetNextParam(sourceFile, nextParam); + } const replacement = factory.createParameterDeclaration( param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, - param.dotDotDotToken ? factory.createArrayTypeNode(typeNode) : typeNode, + param.dotDotDotToken && !isArrayTypeNode(typeNode) ? factory.createArrayTypeNode(typeNode) : typeNode, param.initializer ); - changeTracker.replaceNode(sourceFile, param, replacement); + changeTracker.replaceRange(sourceFile, createRange(param.getStart(sourceFile), end), replacement); + } + function tryGetNextParam(sourceFile, param) { + const nextToken = findNextToken(param.name, param.parent, sourceFile); + if (nextToken && nextToken.kind === 23 /* OpenBracketToken */ && isArrayBindingPattern(nextToken.parent) && isParameter(nextToken.parent.parent)) { + return nextToken.parent.parent; + } + return void 0; } var fixId7, errorCodes7; var init_addNameToNamelessParameter = __esm({ @@ -147431,19 +147462,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} statements.push(factory.createVariableStatement( /*modifiers*/ void 0, - factory.createVariableDeclarationList( - [ - factory.createVariableDeclaration( - getSynthesizedDeepClone(declareSynthBindingPattern(continuationArgName)), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - varDeclIdentifier - ) - ], - 2 /* Const */ - ) + factory.createVariableDeclarationList([ + factory.createVariableDeclaration( + getSynthesizedDeepClone(declareSynthBindingPattern(continuationArgName)), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + varDeclIdentifier + ) + ], 2 /* Const */) )); } return statements; @@ -147579,18 +147607,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} factory.createVariableStatement( /*modifiers*/ void 0, - factory.createVariableDeclarationList( - [ - factory.createVariableDeclaration( - getSynthesizedDeepClone(declareSynthBindingName(variableName)), - /*exclamationToken*/ - void 0, - typeAnnotation, - rightHandSide - ) - ], - 2 /* Const */ - ) + factory.createVariableDeclarationList([ + factory.createVariableDeclaration( + getSynthesizedDeepClone(declareSynthBindingName(variableName)), + /*exclamationToken*/ + void 0, + typeAnnotation, + rightHandSide + ) + ], 2 /* Const */) ) ]; } @@ -147869,9 +147894,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }); // src/services/codefixes/convertToEsModule.ts - function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { + function fixImportOfModuleExports(importingFile, exportingFile, program, changes, quotePreference) { + var _a; for (const moduleSpecifier of importingFile.imports) { - const imported = getResolvedModule(importingFile, moduleSpecifier.text, getModeForUsageLocation(importingFile, moduleSpecifier)); + const imported = (_a = program.getResolvedModule(importingFile, moduleSpecifier.text, getModeForUsageLocation(importingFile, moduleSpecifier))) == null ? void 0 : _a.resolvedModule; if (!imported || imported.resolvedFileName !== exportingFile.fileName) { continue; } @@ -148154,13 +148180,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (semi) changes.delete(sourceFile, semi); } else { - changes.replaceNodeRangeWithNodes( - sourceFile, - left.expression, - findChildOfKind(left, 25 /* DotToken */, sourceFile), - [factory.createToken(95 /* ExportKeyword */), factory.createToken(87 /* ConstKeyword */)], - { joiner: " ", suffix: " " } - ); + changes.replaceNodeRangeWithNodes(sourceFile, left.expression, findChildOfKind(left, 25 /* DotToken */, sourceFile), [factory.createToken(95 /* ExportKeyword */), factory.createToken(87 /* ConstKeyword */)], { joiner: " ", suffix: " " }); } } function convertExportsDotXEquals_replaceNode(name, exported, useSitesToUnqualify) { @@ -148405,7 +148425,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const moduleExportsChangedToDefault = convertFileToEsModule(sourceFile, program.getTypeChecker(), changes2, getEmitScriptTarget(program.getCompilerOptions()), getQuotePreference(sourceFile, preferences)); if (moduleExportsChangedToDefault) { for (const importingFile of program.getSourceFiles()) { - fixImportOfModuleExports(importingFile, sourceFile, changes2, getQuotePreference(importingFile, preferences)); + fixImportOfModuleExports(importingFile, sourceFile, program, changes2, getQuotePreference(importingFile, preferences)); } } }); @@ -148483,7 +148503,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} false, factory.updateNamedExports(exportClause, filter(exportClause.elements, (e) => !contains(typeExportSpecifiers, e))), exportDeclaration.moduleSpecifier, - /*assertClause*/ + /*attributes*/ void 0 ); const typeExportDeclaration = factory.createExportDeclaration( @@ -148493,7 +148513,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} true, factory.createNamedExports(typeExportSpecifiers), exportDeclaration.moduleSpecifier, - /*assertClause*/ + /*attributes*/ void 0 ); changes.replaceNode(context.sourceFile, exportDeclaration, valueExportDeclaration, { @@ -148608,7 +148628,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} true ), getSynthesizedDeepClone( - declaration.assertClause, + declaration.attributes, /*includeTrivia*/ true ) @@ -148636,7 +148656,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} true ), getSynthesizedDeepClone( - declaration.assertClause, + declaration.attributes, /*includeTrivia*/ true ) @@ -148653,19 +148673,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} e.name )) ) : importClause.namedBindings; - const importDeclaration = factory.updateImportDeclaration( - declaration, - declaration.modifiers, - factory.updateImportClause( - importClause, - /*isTypeOnly*/ - true, - importClause.name, - newNamedBindings - ), - declaration.moduleSpecifier, - declaration.assertClause - ); + const importDeclaration = factory.updateImportDeclaration(declaration, declaration.modifiers, factory.updateImportClause( + importClause, + /*isTypeOnly*/ + true, + importClause.name, + newNamedBindings + ), declaration.moduleSpecifier, declaration.attributes); changes.replaceNode(sourceFile, declaration, importDeclaration); } } @@ -148929,23 +148943,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; } function doChange13(changes, sourceFile, { container, typeNode, constraint, name }) { - changes.replaceNode(sourceFile, container, factory.createMappedTypeNode( - /*readonlyToken*/ - void 0, - factory.createTypeParameterDeclaration( - /*modifiers*/ + changes.replaceNode( + sourceFile, + container, + factory.createMappedTypeNode( + /*readonlyToken*/ void 0, - name, - factory.createTypeReferenceNode(constraint) - ), - /*nameType*/ - void 0, - /*questionToken*/ - void 0, - typeNode, - /*members*/ - void 0 - )); + factory.createTypeParameterDeclaration( + /*modifiers*/ + void 0, + name, + factory.createTypeReferenceNode(constraint) + ), + /*nameType*/ + void 0, + /*questionToken*/ + void 0, + typeNode, + /*members*/ + void 0 + ) + ); } var fixId15, errorCodes16; var init_convertLiteralTypeToMappedType = __esm({ @@ -148983,7 +149001,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return Debug.checkDefined(getContainingClass(getTokenAtPosition(sourceFile, pos)), "There should be a containing class"); } function symbolPointsToNonPrivateMember(symbol) { - return !symbol.valueDeclaration || !(getEffectiveModifierFlags(symbol.valueDeclaration) & 8 /* Private */); + return !symbol.valueDeclaration || !(getEffectiveModifierFlags(symbol.valueDeclaration) & 2 /* Private */); } function addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { const checker = context.program.getTypeChecker(); @@ -149254,7 +149272,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} defaultImport, namedImports && arrayFrom(namedImports.entries(), ([name, addAsTypeOnly]) => ({ addAsTypeOnly, name })), namespaceLikeImport, - compilerOptions + compilerOptions, + preferences ); newDeclarations = combine(newDeclarations, declarations); }); @@ -149296,7 +149315,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getImportCompletionAction(targetSymbol, moduleSymbol, exportMapKey, sourceFile, symbolName2, isJsxTagName, host, program, formatContext, position, preferences, cancellationToken) { - const compilerOptions = program.getCompilerOptions(); let exportInfos; if (exportMapKey) { exportInfos = getExportInfoMap(sourceFile, host, program, preferences, cancellationToken).get(sourceFile.path, exportMapKey); @@ -149317,7 +149335,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} fix, /*includeSymbolNameInDescription*/ false, - compilerOptions, + program, preferences )) }; @@ -149327,7 +149345,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const symbolName2 = single(getSymbolNamesToImport(sourceFile, program.getTypeChecker(), symbolToken, compilerOptions)); const fix = getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName2, program); const includeSymbolNameInDescription = symbolName2 !== symbolToken.text; - return fix && codeFixActionToCodeAction(codeActionForFix({ host, formatContext, preferences }, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences)); + return fix && codeFixActionToCodeAction(codeActionForFix( + { host, formatContext, preferences }, + sourceFile, + symbolName2, + fix, + includeSymbolNameInDescription, + program, + preferences + )); } function getImportFixForSymbol(sourceFile, exportInfos, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences) { const packageJsonImportFilter = createPackageJsonImportFilter(sourceFile, preferences, host); @@ -149554,7 +149580,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const getChecker = createGetChecker(program, host); const moduleResolution = getEmitModuleResolutionKind(compilerOptions); const rejectNodeModulesRelativePaths = moduleResolutionUsesNodeModules(moduleResolution); - const getModuleSpecifiers2 = fromCacheOnly ? (moduleSymbol) => ({ moduleSpecifiers: ts_moduleSpecifiers_exports.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), computedWithoutCache: false }) : (moduleSymbol, checker) => ts_moduleSpecifiers_exports.getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences); + const getModuleSpecifiers2 = fromCacheOnly ? (moduleSymbol) => ({ moduleSpecifiers: ts_moduleSpecifiers_exports.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), computedWithoutCache: false }) : (moduleSymbol, checker) => ts_moduleSpecifiers_exports.getModuleSpecifiersWithCacheInfo( + moduleSymbol, + checker, + compilerOptions, + sourceFile, + moduleSpecifierResolutionHost, + preferences, + /*options*/ + void 0, + /*forAutoImport*/ + true + ); let computedWithoutCacheCount = 0; const fixes = flatMap(exportInfo, (exportInfo2, i) => { const checker = getChecker(exportInfo2.isFromPackageJson); @@ -149897,14 +149934,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } - function codeActionForFix(context, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences) { + function codeActionForFix(context, sourceFile, symbolName2, fix, includeSymbolNameInDescription, program, preferences) { let diag2; const changes = ts_textChanges_exports.ChangeTracker.with(context, (tracker) => { - diag2 = codeActionForFixWorker(tracker, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences); + diag2 = codeActionForFixWorker(tracker, sourceFile, symbolName2, fix, includeSymbolNameInDescription, program, preferences); }); return createCodeFixAction(importFixName, changes, diag2, importFixId, Diagnostics.Add_all_missing_imports); } - function codeActionForFixWorker(changes, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences) { + function codeActionForFixWorker(changes, sourceFile, symbolName2, fix, includeSymbolNameInDescription, program, preferences) { const quotePreference = getQuotePreference(sourceFile, preferences); switch (fix.kind) { case 0 /* UseNamespace */: @@ -149941,7 +149978,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} defaultImport, namedImports, namespaceLikeImport, - compilerOptions + program.getCompilerOptions(), + preferences ), /*blankLineBetween*/ true, @@ -149954,7 +149992,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } case 4 /* PromoteTypeOnly */: { const { typeOnlyAliasDeclaration } = fix; - const promotedDeclaration = promoteFromTypeOnly(changes, typeOnlyAliasDeclaration, compilerOptions, sourceFile, preferences); + const promotedDeclaration = promoteFromTypeOnly(changes, typeOnlyAliasDeclaration, program, sourceFile, preferences); return promotedDeclaration.kind === 276 /* ImportSpecifier */ ? [Diagnostics.Remove_type_from_import_of_0_from_1, symbolName2, getModuleSpecifierText(promotedDeclaration.parent.parent)] : [Diagnostics.Remove_type_from_import_declaration_from_0, getModuleSpecifierText(promotedDeclaration)]; } default: @@ -149965,14 +150003,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var _a, _b; return promotedDeclaration.kind === 271 /* ImportEqualsDeclaration */ ? ((_b = tryCast((_a = tryCast(promotedDeclaration.moduleReference, isExternalModuleReference)) == null ? void 0 : _a.expression, isStringLiteralLike)) == null ? void 0 : _b.text) || promotedDeclaration.moduleReference.getText() : cast(promotedDeclaration.parent.moduleSpecifier, isStringLiteral).text; } - function promoteFromTypeOnly(changes, aliasDeclaration, compilerOptions, sourceFile, preferences) { + function promoteFromTypeOnly(changes, aliasDeclaration, program, sourceFile, preferences) { + const compilerOptions = program.getCompilerOptions(); const convertExistingToTypeOnly = importNameElisionDisabled(compilerOptions); switch (aliasDeclaration.kind) { case 276 /* ImportSpecifier */: if (aliasDeclaration.isTypeOnly) { const sortKind = ts_OrganizeImports_exports.detectImportSpecifierSorting(aliasDeclaration.parent.elements, preferences); if (aliasDeclaration.parent.elements.length > 1 && sortKind) { - changes.delete(sourceFile, aliasDeclaration); const newSpecifier = factory.updateImportSpecifier( aliasDeclaration, /*isTypeOnly*/ @@ -149982,10 +150020,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} ); const comparer = ts_OrganizeImports_exports.getOrganizeImportsComparer(preferences, sortKind === 2 /* CaseInsensitive */); const insertionIndex = ts_OrganizeImports_exports.getImportSpecifierInsertionIndex(aliasDeclaration.parent.elements, newSpecifier, comparer); - changes.insertImportSpecifierAtIndex(sourceFile, newSpecifier, aliasDeclaration.parent, insertionIndex); - } else { - changes.deleteRange(sourceFile, aliasDeclaration.getFirstToken()); + if (aliasDeclaration.parent.elements.indexOf(aliasDeclaration) !== insertionIndex) { + changes.delete(sourceFile, aliasDeclaration); + changes.insertImportSpecifierAtIndex(sourceFile, newSpecifier, aliasDeclaration.parent, insertionIndex); + return aliasDeclaration; + } } + changes.deleteRange(sourceFile, aliasDeclaration.getFirstToken()); return aliasDeclaration; } else { Debug.assert(aliasDeclaration.parent.parent.isTypeOnly); @@ -150005,10 +150046,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} Debug.failBadSyntaxKind(aliasDeclaration); } function promoteImportClause(importClause) { + var _a; changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(importClause, sourceFile)); if (!compilerOptions.allowImportingTsExtensions) { const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(importClause.parent); - const resolvedModule = moduleSpecifier && getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation(sourceFile, moduleSpecifier)); + const resolvedModule = moduleSpecifier && ((_a = program.getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation(sourceFile, moduleSpecifier))) == null ? void 0 : _a.resolvedModule); if (resolvedModule == null ? void 0 : resolvedModule.resolvedUsingTsExtension) { const changedExtension = changeAnyExtension(moduleSpecifier.text, getOutputExtension(moduleSpecifier.text, compilerOptions)); changes.replaceNode(sourceFile, moduleSpecifier, factory.createStringLiteral(changedExtension)); @@ -150067,12 +150109,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const comparer = ts_OrganizeImports_exports.getOrganizeImportsComparer(preferences, ignoreCaseForSorting); const newSpecifiers = stableSort( - namedImports.map((namedImport) => factory.createImportSpecifier( - (!clause.isTypeOnly || promoteFromTypeOnly2) && needsTypeOnly(namedImport), - /*propertyName*/ - void 0, - factory.createIdentifier(namedImport.name) - )), + namedImports.map( + (namedImport) => factory.createImportSpecifier( + (!clause.isTypeOnly || promoteFromTypeOnly2) && shouldUseTypeOnly(namedImport, preferences), + /*propertyName*/ + void 0, + factory.createIdentifier(namedImport.name) + ) + ), (s1, s2) => ts_OrganizeImports_exports.compareImportOrExportSpecifiers(s1, s2, comparer) ); const specifierSort = (existingSpecifiers == null ? void 0 : existingSpecifiers.length) && ts_OrganizeImports_exports.detectImportSpecifierSorting(existingSpecifiers, preferences); @@ -150131,42 +150175,50 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function needsTypeOnly({ addAsTypeOnly }) { return addAsTypeOnly === 2 /* Required */; } - function getNewImports(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport, compilerOptions) { + function shouldUseTypeOnly(info, preferences) { + return needsTypeOnly(info) || !!preferences.preferTypeOnlyAutoImports && info.addAsTypeOnly !== 4 /* NotAllowed */; + } + function getNewImports(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport, compilerOptions, preferences) { const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference); let statements; if (defaultImport !== void 0 || (namedImports == null ? void 0 : namedImports.length)) { - const topLevelTypeOnly = (!defaultImport || needsTypeOnly(defaultImport)) && every(namedImports, needsTypeOnly) || compilerOptions.verbatimModuleSyntax && (defaultImport == null ? void 0 : defaultImport.addAsTypeOnly) !== 4 /* NotAllowed */ && !some(namedImports, (i) => i.addAsTypeOnly === 4 /* NotAllowed */); - statements = combine(statements, makeImport( - defaultImport && factory.createIdentifier(defaultImport.name), - namedImports == null ? void 0 : namedImports.map(({ addAsTypeOnly, name }) => factory.createImportSpecifier( - !topLevelTypeOnly && addAsTypeOnly === 2 /* Required */, - /*propertyName*/ - void 0, - factory.createIdentifier(name) - )), - moduleSpecifier, - quotePreference, - topLevelTypeOnly - )); + const topLevelTypeOnly = (!defaultImport || needsTypeOnly(defaultImport)) && every(namedImports, needsTypeOnly) || (compilerOptions.verbatimModuleSyntax || preferences.preferTypeOnlyAutoImports) && (defaultImport == null ? void 0 : defaultImport.addAsTypeOnly) !== 4 /* NotAllowed */ && !some(namedImports, (i) => i.addAsTypeOnly === 4 /* NotAllowed */); + statements = combine( + statements, + makeImport( + defaultImport && factory.createIdentifier(defaultImport.name), + namedImports == null ? void 0 : namedImports.map( + (namedImport) => factory.createImportSpecifier( + !topLevelTypeOnly && shouldUseTypeOnly(namedImport, preferences), + /*propertyName*/ + void 0, + factory.createIdentifier(namedImport.name) + ) + ), + moduleSpecifier, + quotePreference, + topLevelTypeOnly + ) + ); } if (namespaceLikeImport) { const declaration = namespaceLikeImport.importKind === 3 /* CommonJS */ ? factory.createImportEqualsDeclaration( /*modifiers*/ void 0, - needsTypeOnly(namespaceLikeImport), + shouldUseTypeOnly(namespaceLikeImport, preferences), factory.createIdentifier(namespaceLikeImport.name), factory.createExternalModuleReference(quotedModuleSpecifier) ) : factory.createImportDeclaration( /*modifiers*/ void 0, factory.createImportClause( - needsTypeOnly(namespaceLikeImport), + shouldUseTypeOnly(namespaceLikeImport, preferences), /*name*/ void 0, factory.createNamespaceImport(factory.createIdentifier(namespaceLikeImport.name)) ), quotedModuleSpecifier, - /*assertClause*/ + /*attributes*/ void 0 ); statements = combine(statements, declaration); @@ -150205,24 +150257,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return factory.createVariableStatement( /*modifiers*/ void 0, - factory.createVariableDeclarationList( - [ - factory.createVariableDeclaration( - typeof name === "string" ? factory.createIdentifier(name) : name, - /*exclamationToken*/ + factory.createVariableDeclarationList([ + factory.createVariableDeclaration( + typeof name === "string" ? factory.createIdentifier(name) : name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory.createCallExpression( + factory.createIdentifier("require"), + /*typeArguments*/ void 0, - /*type*/ - void 0, - factory.createCallExpression( - factory.createIdentifier("require"), - /*typeArguments*/ - void 0, - [quotedModuleSpecifier] - ) + [quotedModuleSpecifier] ) - ], - 2 /* Const */ - ) + ) + ], 2 /* Const */) ); } function symbolHasMeaning({ declarations }, meaning) { @@ -150290,16 +150339,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} ); if (!info) return void 0; - return info.map(({ fix, symbolName: symbolName2, errorIdentifierText }) => codeActionForFix( - context, - sourceFile, - symbolName2, - fix, - /*includeSymbolNameInDescription*/ - symbolName2 !== errorIdentifierText, - program.getCompilerOptions(), - preferences - )); + return info.map( + ({ fix, symbolName: symbolName2, errorIdentifierText }) => codeActionForFix( + context, + sourceFile, + symbolName2, + fix, + /*includeSymbolNameInDescription*/ + symbolName2 !== errorIdentifierText, + program, + preferences + ) + ); }, fixIds: [importFixId], getAllCodeActions: (context) => { @@ -150709,7 +150760,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/fixImportNonExportedMember.ts function getInfo7(sourceFile, pos, program) { - var _a; + var _a, _b; const token = getTokenAtPosition(sourceFile, pos); if (isIdentifier(token)) { const importDeclaration = findAncestor(token, isImportDeclaration); @@ -150718,19 +150769,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const moduleSpecifier = isStringLiteral(importDeclaration.moduleSpecifier) ? importDeclaration.moduleSpecifier.text : void 0; if (moduleSpecifier === void 0) return void 0; - const resolvedModule = getResolvedModule( + const resolvedModule = (_a = program.getResolvedModule( sourceFile, moduleSpecifier, /*mode*/ void 0 - ); + )) == null ? void 0 : _a.resolvedModule; if (resolvedModule === void 0) return void 0; const moduleSourceFile = program.getSourceFile(resolvedModule.resolvedFileName); if (moduleSourceFile === void 0 || isSourceFileFromLibrary(program, moduleSourceFile)) return void 0; const moduleSymbol = moduleSourceFile.symbol; - const locals = (_a = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _a.locals; + const locals = (_b = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _b.locals; if (locals === void 0) return void 0; const localSymbol = locals.get(token.escapedText); @@ -150785,30 +150836,26 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} ) ), node.moduleSpecifier, - node.assertClause + node.attributes ) ); } function createExport(changes, program, sourceFile, names) { - changes.insertNodeAtEndOfScope( - sourceFile, - sourceFile, - factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports(createExportSpecifiers( - names, - /*allowTypeModifier*/ - getIsolatedModules(program.getCompilerOptions()) - )), - /*moduleSpecifier*/ - void 0, - /*assertClause*/ - void 0 - ) - ); + changes.insertNodeAtEndOfScope(sourceFile, sourceFile, factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports(createExportSpecifiers( + names, + /*allowTypeModifier*/ + getIsolatedModules(program.getCompilerOptions()) + )), + /*moduleSpecifier*/ + void 0, + /*attributes*/ + void 0 + )); } function createExportSpecifiers(names, allowTypeModifier) { return factory.createNodeArray(map(names, (n) => factory.createExportSpecifier( @@ -150982,7 +151029,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const tag = findAncestor(node, isJsxOpeningLikeElement); const props = checker.getContextualTypeForArgumentAtIndex(tag, 0); suggestedSymbol = checker.getSuggestedSymbolForNonexistentJSXAttribute(node, props); - } else if (hasSyntacticModifier(parent2, 16384 /* Override */) && isClassElement(parent2) && parent2.name === node) { + } else if (hasOverrideModifier(parent2) && isClassElement(parent2) && parent2.name === node) { const baseDeclaration = findAncestor(node, isClassLike); const baseTypeNode = baseDeclaration ? getEffectiveBaseTypeNode(baseDeclaration) : void 0; const baseType = baseTypeNode ? checker.getTypeAtLocation(baseTypeNode) : void 0; @@ -151024,9 +151071,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return flags; } function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) { + var _a; if (!importDeclaration || !isStringLiteralLike(importDeclaration.moduleSpecifier)) return void 0; - const resolvedModule = getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text, getModeForUsageLocation(sourceFile, importDeclaration.moduleSpecifier)); + const resolvedModule = (_a = context.program.getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text, getModeForUsageLocation(sourceFile, importDeclaration.moduleSpecifier))) == null ? void 0 : _a.resolvedModule; if (!resolvedModule) return void 0; return context.program.getSourceFile(resolvedModule.resolvedFileName); @@ -151143,7 +151191,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isFunctionType) { const sig = checker.getSignatureFromDeclaration(declaration); if (sig) { - if (hasSyntacticModifier(declaration, 512 /* Async */)) { + if (hasSyntacticModifier(declaration, 1024 /* Async */)) { exprType = checker.createPromiseType(exprType); } const newSig = checker.createSignature( @@ -151415,13 +151463,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const moduleDeclaration = find(symbol.declarations, isModuleDeclaration); const moduleDeclarationSourceFile = moduleDeclaration == null ? void 0 : moduleDeclaration.getSourceFile(); if (moduleDeclaration && moduleDeclarationSourceFile && !isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) { - return { kind: 2 /* Function */, token, call: parent2.parent, sourceFile, modifierFlags: 1 /* Export */, parentDeclaration: moduleDeclaration }; + return { kind: 2 /* Function */, token, call: parent2.parent, sourceFile, modifierFlags: 32 /* Export */, parentDeclaration: moduleDeclaration }; } const moduleSourceFile = find(symbol.declarations, isSourceFile); if (sourceFile.commonJsModuleIndicator) return void 0; if (moduleSourceFile && !isSourceFileFromLibrary(program, moduleSourceFile)) { - return { kind: 2 /* Function */, token, call: parent2.parent, sourceFile: moduleSourceFile, modifierFlags: 1 /* Export */, parentDeclaration: moduleSourceFile }; + return { kind: 2 /* Function */, token, call: parent2.parent, sourceFile: moduleSourceFile, modifierFlags: 32 /* Export */, parentDeclaration: moduleSourceFile }; } } const classDeclaration = find(symbol.declarations, isClassLike); @@ -151433,7 +151481,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (makeStatic && (isPrivateIdentifier(token) || isInterfaceDeclaration(declaration))) return void 0; const declSourceFile = declaration.getSourceFile(); - const modifierFlags = isTypeLiteralNode(declaration) ? 0 /* None */ : (makeStatic ? 32 /* Static */ : 0 /* None */) | (startsWithUnderscore(token.text) ? 8 /* Private */ : 0 /* None */); + const modifierFlags = isTypeLiteralNode(declaration) ? 0 /* None */ : (makeStatic ? 256 /* Static */ : 0 /* None */) | (startsWithUnderscore(token.text) ? 2 /* Private */ : 0 /* None */); const isJSFile = isSourceFileJS(declSourceFile); const call = tryCast(parent2.parent, isCallExpression); return { kind: 0 /* TypeLikeDeclaration */, token, call, modifierFlags, parentDeclaration: declaration, declSourceFile, isJSFile }; @@ -151451,11 +151499,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isInterfaceDeclaration(parentDeclaration) || isTypeLiteralNode(parentDeclaration)) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingMemberInJs(t, declSourceFile, parentDeclaration, token, !!(modifierFlags & 32 /* Static */))); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingMemberInJs(t, declSourceFile, parentDeclaration, token, !!(modifierFlags & 256 /* Static */))); if (changes.length === 0) { return void 0; } - const diagnostic = modifierFlags & 32 /* Static */ ? Diagnostics.Initialize_static_property_0 : isPrivateIdentifier(token) ? Diagnostics.Declare_a_private_field_named_0 : Diagnostics.Initialize_property_0_in_the_constructor; + const diagnostic = modifierFlags & 256 /* Static */ ? Diagnostics.Initialize_static_property_0 : isPrivateIdentifier(token) ? Diagnostics.Declare_a_private_field_named_0 : Diagnostics.Initialize_property_0_in_the_constructor; return createCodeFixAction(fixMissingMember, changes, [diagnostic, token.text], fixMissingMember, Diagnostics.Add_all_missing_members); } function addMissingMemberInJs(changeTracker, sourceFile, classDeclaration, token, makeStatic) { @@ -151499,15 +151547,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function createActionsForAddMissingMemberInTypeScriptFile(context, { parentDeclaration, declSourceFile, modifierFlags, token }) { const memberName = token.text; - const isStatic2 = modifierFlags & 32 /* Static */; + const isStatic2 = modifierFlags & 256 /* Static */; const typeNode = getTypeNode2(context.program.getTypeChecker(), parentDeclaration, token); const addPropertyDeclarationChanges = (modifierFlags2) => ts_textChanges_exports.ChangeTracker.with(context, (t) => addPropertyDeclaration(t, declSourceFile, parentDeclaration, memberName, typeNode, modifierFlags2)); - const actions2 = [createCodeFixAction(fixMissingMember, addPropertyDeclarationChanges(modifierFlags & 32 /* Static */), [isStatic2 ? Diagnostics.Declare_static_property_0 : Diagnostics.Declare_property_0, memberName], fixMissingMember, Diagnostics.Add_all_missing_members)]; + const actions2 = [createCodeFixAction(fixMissingMember, addPropertyDeclarationChanges(modifierFlags & 256 /* Static */), [isStatic2 ? Diagnostics.Declare_static_property_0 : Diagnostics.Declare_property_0, memberName], fixMissingMember, Diagnostics.Add_all_missing_members)]; if (isStatic2 || isPrivateIdentifier(token)) { return actions2; } - if (modifierFlags & 8 /* Private */) { - actions2.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addPropertyDeclarationChanges(8 /* Private */), [Diagnostics.Declare_private_property_0, memberName])); + if (modifierFlags & 2 /* Private */) { + actions2.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addPropertyDeclarationChanges(2 /* Private */), [Diagnostics.Declare_private_property_0, memberName])); } actions2.push(createAddIndexSignatureAction(context, declSourceFile, parentDeclaration, token.text, typeNode)); return actions2; @@ -151594,9 +151642,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const methodName = token.text; const addMethodDeclarationChanges = (modifierFlags2) => ts_textChanges_exports.ChangeTracker.with(context, (t) => addMethodDeclaration(context, t, call, token, modifierFlags2, parentDeclaration, declSourceFile)); - const actions2 = [createCodeFixAction(fixMissingMember, addMethodDeclarationChanges(modifierFlags & 32 /* Static */), [modifierFlags & 32 /* Static */ ? Diagnostics.Declare_static_method_0 : Diagnostics.Declare_method_0, methodName], fixMissingMember, Diagnostics.Add_all_missing_members)]; - if (modifierFlags & 8 /* Private */) { - actions2.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addMethodDeclarationChanges(8 /* Private */), [Diagnostics.Declare_private_method_0, methodName])); + const actions2 = [createCodeFixAction(fixMissingMember, addMethodDeclarationChanges(modifierFlags & 256 /* Static */), [modifierFlags & 256 /* Static */ ? Diagnostics.Declare_static_method_0 : Diagnostics.Declare_method_0, methodName], fixMissingMember, Diagnostics.Add_all_missing_members)]; + if (modifierFlags & 2 /* Private */) { + actions2.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addMethodDeclarationChanges(2 /* Private */), [Diagnostics.Declare_private_method_0, methodName])); } return actions2; } @@ -151618,15 +151666,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return !!(type && type.flags & 402653316 /* StringLike */); }); const enumMember = factory.createEnumMember(token, hasStringInitializer ? factory.createStringLiteral(token.text) : void 0); - changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, factory.updateEnumDeclaration( + changes.replaceNode( + parentDeclaration.getSourceFile(), parentDeclaration, - parentDeclaration.modifiers, - parentDeclaration.name, - concatenate(parentDeclaration.members, singleElementArray(enumMember)) - ), { - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude - }); + factory.updateEnumDeclaration( + parentDeclaration, + parentDeclaration.modifiers, + parentDeclaration.name, + concatenate(parentDeclaration.members, singleElementArray(enumMember)) + ), + { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude + } + ); } function addFunctionDeclaration(changes, context, info) { const quotePreference = getQuotePreference(context.sourceFile, context.preferences); @@ -151861,7 +151914,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (prop && isComputedPropertyName(prop)) return prop; } - return createPropertyNameNodeForIdentifierOrLiteral(symbol.name, target, quotePreference === 0 /* Single */); + return createPropertyNameNodeForIdentifierOrLiteral( + symbol.name, + target, + quotePreference === 0 /* Single */, + /*stringNamed*/ + false, + /*isMethod*/ + false + ); } function findScope(node) { if (findAncestor(node, isJsxExpression)) { @@ -151957,13 +152018,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} continue; const { parentDeclaration, declSourceFile, modifierFlags, token, call, isJSFile } = info; if (call && !isPrivateIdentifier(token)) { - addMethodDeclaration(context, changes, call, token, modifierFlags & 32 /* Static */, parentDeclaration, declSourceFile); + addMethodDeclaration(context, changes, call, token, modifierFlags & 256 /* Static */, parentDeclaration, declSourceFile); } else { if (isJSFile && !isInterfaceDeclaration(parentDeclaration) && !isTypeLiteralNode(parentDeclaration)) { - addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token, !!(modifierFlags & 32 /* Static */)); + addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token, !!(modifierFlags & 256 /* Static */)); } else { const typeNode = getTypeNode2(checker, parentDeclaration, token); - addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, modifierFlags & 32 /* Static */); + addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, modifierFlags & 256 /* Static */); } } } @@ -152095,7 +152156,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function symbolPointsToNonPrivateAndAbstractMember(symbol) { const flags = getSyntacticModifierFlags(first(symbol.getDeclarations())); - return !(flags & 8 /* Private */) && !!(flags & 256 /* Abstract */); + return !(flags & 2 /* Private */) && !!(flags & 64 /* Abstract */); } var errorCodes30, fixId25; var init_fixClassDoesntImplementInheritedAbstractMember = __esm({ @@ -152238,10 +152299,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (configFile === void 0) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with( - context, - (changeTracker) => doChange21(changeTracker, configFile) - ); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => doChange21(changeTracker, configFile)); return [ createCodeFixActionWithoutFixAll(fixID, changes, Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) ]; @@ -152872,7 +152930,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function isCallbackLike(checker, sourceFile, name) { - return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(name, checker, sourceFile, (reference) => isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.indexOf(reference) >= 0); + return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(name, checker, sourceFile, (reference) => isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.includes(reference)); } function isLastParameter(func, parameter, isFixAll) { const parameters = func.parameters; @@ -154517,11 +154575,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return [createCodeFixAction( fixId39, changes, - [ - Diagnostics.Replace_0_with_Promise_1, - checker.typeToString(returnType), - checker.typeToString(promisedType) - ], + [Diagnostics.Replace_0_with_Promise_1, checker.typeToString(returnType), checker.typeToString(promisedType)], fixId39, Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions )]; @@ -154568,7 +154622,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} createCodeFixActionWithoutFixAll( fixName4, [createFileTextChanges(sourceFile.fileName, [ - createTextChange(sourceFile.checkJsDirective ? createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : createTextSpan(0, 0), `// @ts-nocheck${newLineCharacter}`) + createTextChange( + sourceFile.checkJsDirective ? createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : createTextSpan(0, 0), + `// @ts-nocheck${newLineCharacter}` + ) ])], Diagnostics.Disable_checking_for_this_file ) @@ -154624,10 +154681,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const kind = (declaration == null ? void 0 : declaration.kind) ?? 171 /* PropertySignature */; 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 */; + let modifierFlags = effectiveModifierFlags & 256 /* Static */; + modifierFlags |= effectiveModifierFlags & 1 /* Public */ ? 1 /* Public */ : effectiveModifierFlags & 4 /* Protected */ ? 4 /* Protected */ : 0 /* None */; if (declaration && isAutoAccessorPropertyDeclaration(declaration)) { - modifierFlags |= 128 /* Accessor */; + modifierFlags |= 512 /* Accessor */; } const modifiers = createModifiers(); const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -155160,14 +155217,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; const compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); if (compilerOptionsProperty === void 0) { - changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment( - "compilerOptions", - factory.createObjectLiteralExpression( - options.map(([optionName, optionValue]) => createJsonPropertyAssignment(optionName, optionValue)), - /*multiLine*/ - true + changeTracker.insertNodeAtObjectStart( + configFile, + tsconfigObjectLiteral, + createJsonPropertyAssignment( + "compilerOptions", + factory.createObjectLiteralExpression( + options.map(([optionName, optionValue]) => createJsonPropertyAssignment(optionName, optionValue)), + /*multiLine*/ + true + ) ) - )); + ); return; } const compilerOptions = compilerOptionsProperty.initializer; @@ -155302,24 +155363,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return isIdentifier(fieldName) ? factory.createPropertyAccessExpression(leftHead, fieldName) : factory.createElementAccessExpression(leftHead, factory.createStringLiteralFromNode(fieldName)); } function prepareModifierFlagsForAccessor(modifierFlags) { - modifierFlags &= ~64 /* Readonly */; - modifierFlags &= ~8 /* Private */; - if (!(modifierFlags & 16 /* Protected */)) { - modifierFlags |= 4 /* Public */; + modifierFlags &= ~8 /* Readonly */; + modifierFlags &= ~2 /* Private */; + if (!(modifierFlags & 4 /* Protected */)) { + modifierFlags |= 1 /* Public */; } return modifierFlags; } function prepareModifierFlagsForField(modifierFlags) { - modifierFlags &= ~4 /* Public */; - modifierFlags &= ~16 /* Protected */; - modifierFlags |= 8 /* Private */; + modifierFlags &= ~1 /* Public */; + modifierFlags &= ~4 /* Protected */; + modifierFlags |= 2 /* Private */; return modifierFlags; } function getAccessorConvertiblePropertyAtPosition(file, program, start, end, considerEmptySpans = true) { const node = getTokenAtPosition(file, start); const cursorRequest = start === end && considerEmptySpans; const declaration = findAncestor(node.parent, isAcceptedDeclaration); - const meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; + const meaning = 7 /* AccessibilityModifier */ | 256 /* Static */ | 8 /* Readonly */; if (!declaration || !(nodeOverlapsWithStartEnd(declaration.name, file, start, end) || cursorRequest)) { return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_property_for_which_to_generate_accessor) @@ -155330,7 +155391,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} error: getLocaleSpecificMessage(Diagnostics.Name_is_not_valid) }; } - if ((getEffectiveModifierFlags(declaration) & 126975 /* Modifier */ | meaning) !== meaning) { + if ((getEffectiveModifierFlags(declaration) & 98303 /* Modifier */ | meaning) !== meaning) { return { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_property_with_modifier) }; @@ -155424,11 +155485,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else if (isPropertyAssignment(declaration)) { updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); } else { - changeTracker.replaceNode( - file, - declaration, - factory.updateParameterDeclaration(declaration, modifiers, declaration.dotDotDotToken, cast(fieldName, isIdentifier), declaration.questionToken, declaration.type, declaration.initializer) - ); + changeTracker.replaceNode(file, declaration, factory.updateParameterDeclaration(declaration, modifiers, declaration.dotDotDotToken, cast(fieldName, isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); } } function insertAccessor(changeTracker, file, accessor, declaration, container) { @@ -155498,14 +155555,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} getQuotePreference(sourceFile, context.preferences) ))); if (getEmitModuleKind(opts) === 1 /* CommonJS */) { - variations.push(createAction(context, sourceFile, node, factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - namespace.name, - factory.createExternalModuleReference(node.moduleSpecifier) - ))); + variations.push(createAction( + context, + sourceFile, + node, + factory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + namespace.name, + factory.createExternalModuleReference(node.moduleSpecifier) + ) + )); } return variations; } @@ -155670,7 +155732,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return firstDefined(type.types, (t) => getDefaultValueFromType(checker, t)); } else if (type.isClass()) { const classDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); - if (!classDeclaration || hasSyntacticModifier(classDeclaration, 256 /* Abstract */)) + if (!classDeclaration || hasSyntacticModifier(classDeclaration, 64 /* Abstract */)) return void 0; const constructorDeclaration = getFirstConstructorWithBody(classDeclaration); if (constructorDeclaration && constructorDeclaration.parameters.length) @@ -155742,26 +155804,30 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/requireInTs.ts function doChange34(changes, sourceFile, info) { const { allowSyntheticDefaults, defaultImportName, namedImports, statement, required } = info; - changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults ? factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - defaultImportName, - factory.createExternalModuleReference(required) - ) : factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( + changes.replaceNode( + sourceFile, + statement, + defaultImportName && !allowSyntheticDefaults ? factory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, /*isTypeOnly*/ false, defaultImportName, - namedImports - ), - required, - /*assertClause*/ - void 0 - )); + factory.createExternalModuleReference(required) + ) : factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause( + /*isTypeOnly*/ + false, + defaultImportName, + namedImports + ), + required, + /*attributes*/ + void 0 + ) + ); } function getInfo17(sourceFile, program, pos) { const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); @@ -155927,7 +155993,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const newTypeNode = factory.updateImportTypeNode( importType, importType.argument, - importType.assertions, + importType.attributes, importType.qualifier, importType.typeArguments, /*isTypeOf*/ @@ -156181,32 +156247,40 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return; } const importClause = Debug.checkDefined(importDeclaration.importClause); - changes.replaceNode(context.sourceFile, importDeclaration, factory.updateImportDeclaration( + changes.replaceNode( + context.sourceFile, importDeclaration, - importDeclaration.modifiers, - factory.updateImportClause( - importClause, - importClause.isTypeOnly, - importClause.name, - /*namedBindings*/ - void 0 - ), - importDeclaration.moduleSpecifier, - importDeclaration.assertClause - )); - changes.insertNodeAfter(context.sourceFile, importDeclaration, factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.updateImportClause( - importClause, - importClause.isTypeOnly, - /*name*/ + factory.updateImportDeclaration( + importDeclaration, + importDeclaration.modifiers, + factory.updateImportClause( + importClause, + importClause.isTypeOnly, + importClause.name, + /*namedBindings*/ + void 0 + ), + importDeclaration.moduleSpecifier, + importDeclaration.attributes + ) + ); + changes.insertNodeAfter( + context.sourceFile, + importDeclaration, + factory.createImportDeclaration( + /*modifiers*/ void 0, - importClause.namedBindings - ), - importDeclaration.moduleSpecifier, - importDeclaration.assertClause - )); + factory.updateImportClause( + importClause, + importClause.isTypeOnly, + /*name*/ + void 0, + importClause.namedBindings + ), + importDeclaration.moduleSpecifier, + importDeclaration.attributes + ) + ); } var errorCodes60, fixId48; var init_splitTypeOnlyImport = __esm({ @@ -157148,7 +157222,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} ); if (keywordFilters !== 0 /* None */) { for (const keywordEntry of getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && isSourceFileJS(sourceFile))) { - if (isTypeOnlyLocation && isTypeKeyword(stringToToken(keywordEntry.name)) || !uniqueNames.has(keywordEntry.name)) { + if (isTypeOnlyLocation && isTypeKeyword(stringToToken(keywordEntry.name)) || !isTypeOnlyLocation && isContextualKeywordInAutoImportableExpressionSpace(keywordEntry.name) || !uniqueNames.has(keywordEntry.name)) { uniqueNames.add(keywordEntry.name); insertSorted( entries, @@ -157575,7 +157649,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } let modifiers = 0 /* None */; const { modifiers: presentModifiers, range: eraseRange, decorators: presentDecorators } = getPresentModifiers(contextToken, sourceFile, position); - const isAbstract = presentModifiers & 256 /* Abstract */ && classLikeDeclaration.modifierFlagsCache & 256 /* Abstract */; + const isAbstract = presentModifiers & 64 /* Abstract */ && classLikeDeclaration.modifierFlagsCache & 64 /* Abstract */; let completionNodes = []; ts_codefix_exports.addNewNodeForMemberSymbol( symbol, @@ -157594,15 +157668,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} (node) => { let requiredModifiers = 0 /* None */; if (isAbstract) { - requiredModifiers |= 256 /* Abstract */; + requiredModifiers |= 64 /* Abstract */; } if (isClassElement(node) && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node, symbol) === 1 /* NeedsOverride */) { - requiredModifiers |= 16384 /* Override */; + requiredModifiers |= 16 /* Override */; } if (!completionNodes.length) { modifiers = node.modifierFlagsCache | requiredModifiers; } - node = factory.updateModifiers(node, modifiers); + node = factory.replaceModifiers(node, modifiers); completionNodes.push(node); }, body, @@ -157611,28 +157685,28 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} ); if (completionNodes.length) { const isMethod = symbol.flags & 8192 /* Method */; - let allowedModifiers = modifiers | 16384 /* Override */ | 4 /* Public */; + let allowedModifiers = modifiers | 16 /* Override */ | 1 /* Public */; if (!isMethod) { - allowedModifiers |= 2 /* Ambient */ | 64 /* Readonly */; + allowedModifiers |= 128 /* Ambient */ | 8 /* Readonly */; } else { - allowedModifiers |= 512 /* Async */; + allowedModifiers |= 1024 /* Async */; } const allowedAndPresent = presentModifiers & allowedModifiers; if (presentModifiers & ~allowedModifiers) { return void 0; } - if (modifiers & 16 /* Protected */ && allowedAndPresent & 4 /* Public */) { - modifiers &= ~16 /* Protected */; + if (modifiers & 4 /* Protected */ && allowedAndPresent & 1 /* Public */) { + modifiers &= ~4 /* Protected */; } - if (allowedAndPresent !== 0 /* None */ && !(allowedAndPresent & 4 /* Public */)) { - modifiers &= ~4 /* Public */; + if (allowedAndPresent !== 0 /* None */ && !(allowedAndPresent & 1 /* Public */)) { + modifiers &= ~1 /* Public */; } modifiers |= allowedAndPresent; - completionNodes = completionNodes.map((node) => factory.updateModifiers(node, modifiers)); + completionNodes = completionNodes.map((node) => factory.replaceModifiers(node, modifiers)); if (presentDecorators == null ? void 0 : presentDecorators.length) { const lastNode = completionNodes[completionNodes.length - 1]; if (canHaveDecorators(lastNode)) { - completionNodes[completionNodes.length - 1] = factory.updateModifierLike(lastNode, presentDecorators.concat(getModifiers(lastNode) || [])); + completionNodes[completionNodes.length - 1] = factory.replaceDecoratorsAndModifiers(lastNode, presentDecorators.concat(getModifiers(lastNode) || [])); } } const format = 1 /* MultiLine */ | 131072 /* NoTrailingNewLine */; @@ -157662,7 +157736,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let contextMod; const range = { pos: position, end: position }; if (isPropertyDeclaration(contextToken.parent) && contextToken.parent.modifiers) { - modifiers |= modifiersToFlags(contextToken.parent.modifiers) & 126975 /* Modifier */; + modifiers |= modifiersToFlags(contextToken.parent.modifiers) & 98303 /* Modifier */; decorators = contextToken.parent.modifiers.filter(isDecorator) || []; range.pos = Math.min(range.pos, contextToken.parent.modifiers.pos); } @@ -157787,17 +157861,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} true ); } - const parameters = typeNode.parameters.map((typedParam) => factory.createParameterDeclaration( - /*modifiers*/ - void 0, - typedParam.dotDotDotToken, - typedParam.name, - /*questionToken*/ - void 0, - /*type*/ - void 0, - typedParam.initializer - )); + const parameters = typeNode.parameters.map( + (typedParam) => factory.createParameterDeclaration( + /*modifiers*/ + void 0, + typedParam.dotDotDotToken, + typedParam.name, + /*questionToken*/ + void 0, + /*type*/ + void 0, + typedParam.initializer + ) + ); return factory.createMethodDeclaration( /*modifiers*/ void 0, @@ -158235,7 +158311,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return createSimpleDetails(completionNameForLiteral(sourceFile, preferences, literal), "string" /* string */, typeof literal === "string" ? 8 /* stringLiteral */ : 7 /* numericLiteral */); } case "cases": { - const { entry, importAdder } = getExhaustiveCaseSnippets( + const snippets = getExhaustiveCaseSnippets( contextToken.parent, sourceFile, preferences, @@ -158245,7 +158321,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} /*formatContext*/ void 0 ); - if (importAdder.hasFixes()) { + if (snippets == null ? void 0 : snippets.importAdder.hasFixes()) { + const { entry, importAdder } = snippets; const changes = ts_textChanges_exports.ChangeTracker.with( { host, formatContext, preferences }, importAdder.writeFixes @@ -158263,7 +158340,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }; } return { - name: entry.name, + name, kind: "" /* unknown */, kindModifiers: "", displayParts: [], @@ -158280,10 +158357,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return createCompletionDetails(name, "" /* none */, kind, [displayPart(name, kind2)]); } function createCompletionDetailsForSymbol(symbol, name, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) { - const { displayParts, documentation, symbolKind, tags } = checker.runWithCancellationToken( - cancellationToken, - (checker2) => ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker2, symbol, sourceFile, location, location, 7 /* All */) - ); + const { displayParts, documentation, symbolKind, tags } = checker.runWithCancellationToken(cancellationToken, (checker2) => ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker2, symbol, sourceFile, location, location, 7 /* All */)); return createCompletionDetails(name, ts_SymbolDisplay_exports.getSymbolModifiers(checker, symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { @@ -158839,14 +158913,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) }; } else { const fileName = isExternalModuleNameRelative(stripQuotes(moduleSymbol.name)) ? (_a = getSourceFileOfModule(moduleSymbol)) == null ? void 0 : _a.fileName : void 0; - const { moduleSpecifier } = (importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences))).getModuleSpecifierForBestExportInfo([{ - exportKind: 0 /* Named */, - moduleFileName: fileName, - isFromPackageJson: false, - moduleSymbol, - symbol: firstAccessibleSymbol, - targetFlags: skipAlias(firstAccessibleSymbol, typeChecker).flags - }], position, isValidTypeOnlyAliasUseSite(location)) || {}; + const { moduleSpecifier } = (importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences))).getModuleSpecifierForBestExportInfo( + [{ + exportKind: 0 /* Named */, + moduleFileName: fileName, + isFromPackageJson: false, + moduleSymbol, + symbol: firstAccessibleSymbol, + targetFlags: skipAlias(firstAccessibleSymbol, typeChecker).flags + }], + position, + isValidTypeOnlyAliasUseSite(location) + ) || {}; if (moduleSpecifier) { const origin = { kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), @@ -159399,24 +159477,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (contextToken.kind === 80 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { switch (contextToken.getText()) { case "private": - classElementModifierFlags = classElementModifierFlags | 8 /* Private */; + classElementModifierFlags = classElementModifierFlags | 2 /* Private */; break; case "static": - classElementModifierFlags = classElementModifierFlags | 32 /* Static */; + classElementModifierFlags = classElementModifierFlags | 256 /* Static */; break; case "override": - classElementModifierFlags = classElementModifierFlags | 16384 /* Override */; + classElementModifierFlags = classElementModifierFlags | 16 /* Override */; break; } } if (isClassStaticBlockDeclaration(classElement)) { - classElementModifierFlags |= 32 /* Static */; + classElementModifierFlags |= 256 /* Static */; } - if (!(classElementModifierFlags & 8 /* Private */)) { - const baseTypeNodes = isClassLike(decl) && classElementModifierFlags & 16384 /* Override */ ? singleElementArray(getEffectiveBaseTypeNode(decl)) : getAllSuperTypeNodes(decl); + if (!(classElementModifierFlags & 2 /* Private */)) { + const baseTypeNodes = isClassLike(decl) && classElementModifierFlags & 16 /* Override */ ? singleElementArray(getEffectiveBaseTypeNode(decl)) : getAllSuperTypeNodes(decl); const baseSymbols = flatMap(baseTypeNodes, (baseTypeNode) => { const type = typeChecker.getTypeAtLocation(baseTypeNode); - return classElementModifierFlags & 32 /* Static */ ? (type == null ? void 0 : type.symbol) && typeChecker.getPropertiesOfType(typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl)) : type && typeChecker.getPropertiesOfType(type); + return classElementModifierFlags & 256 /* Static */ ? (type == null ? void 0 : type.symbol) && typeChecker.getPropertiesOfType(typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl)) : type && typeChecker.getPropertiesOfType(type); }); symbols = concatenate(symbols, filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags)); forEach(symbols, (symbol, index) => { @@ -159719,10 +159797,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isCurrentlyEditingNode(m)) { continue; } - if (hasEffectiveModifier(m, 8 /* Private */)) { + if (hasEffectiveModifier(m, 2 /* Private */)) { continue; } - if (isStatic(m) !== !!(currentClassElementModifierFlags & 32 /* Static */)) { + if (isStatic(m) !== !!(currentClassElementModifierFlags & 256 /* Static */)) { continue; } const existingName = getPropertyNameForPropertyNameNode(m.name); @@ -159730,7 +159808,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} existingMemberNames.add(existingName); } } - return baseSymbols.filter((propertySymbol) => !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */) && !(propertySymbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration))); + return baseSymbols.filter( + (propertySymbol) => !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & 2 /* Private */) && !(propertySymbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration)) + ); } function filterJsxAttributes(symbols2, attributes) { const seenNames = /* @__PURE__ */ new Set(); @@ -159978,7 +160058,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return checker.getAllPossiblePropertiesOfTypes(filter(type.types, (memberType) => !(memberType.flags & 402784252 /* Primitive */ || checker.isArrayLikeType(memberType) || checker.isTypeInvalidDueToUnionDiscriminant(memberType, node) || checker.typeHasCallOrConstructSignatures(memberType) || memberType.isClass() && containsNonPublicProperties(memberType.getApparentProperties())))); } function containsNonPublicProperties(props) { - return some(props, (p) => !!(getDeclarationModifierFlagsFromSymbol(p) & 24 /* NonPublicAccessibilityModifier */)); + return some(props, (p) => !!(getDeclarationModifierFlagsFromSymbol(p) & 6 /* NonPublicAccessibilityModifier */)); } function getPropertiesForCompletion(type, checker) { return type.isUnion() ? Debug.checkEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") : Debug.checkEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); @@ -160138,7 +160218,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return false; } function isStaticProperty(symbol) { - return !!(symbol.valueDeclaration && getEffectiveModifierFlags(symbol.valueDeclaration) & 32 /* Static */ && isClassLike(symbol.valueDeclaration.parent)); + return !!(symbol.valueDeclaration && getEffectiveModifierFlags(symbol.valueDeclaration) & 256 /* Static */ && isClassLike(symbol.valueDeclaration.parent)); } function tryGetObjectLiteralContextualType(node, typeChecker) { const type = typeChecker.getContextualType(node); @@ -160309,6 +160389,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return charCode; } + function isContextualKeywordInAutoImportableExpressionSpace(keyword) { + return keyword === "abstract" || keyword === "async" || keyword === "await" || keyword === "declare" || keyword === "module" || keyword === "namespace" || keyword === "type"; + } var moduleSpecifierResolutionLimit, moduleSpecifierResolutionCacheAttemptLimit, SortText, CompletionSource, SymbolOriginInfoKind, CompletionKind, _keywordCompletions, allKeywordsCompletions; var init_completions = __esm({ "src/services/completions.ts"() { @@ -160467,8 +160550,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan, entries }; } case 2 /* Types */: { + const quoteChar = contextToken.kind === 15 /* NoSubstitutionTemplateLiteral */ ? 96 /* backtick */ : startsWith(getTextOfNode(contextToken), "'") ? 39 /* singleQuote */ : 34 /* doubleQuote */; const entries = completion.types.map((type) => ({ - name: type.value, + name: escapeString(type.value, quoteChar), kindModifiers: "" /* none */, kind: "string" /* string */, sortText: SortText.LocationPriority, @@ -160569,7 +160653,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 291 /* JsxAttribute */: if (!isRequireCallArgument(node) && !isImportCall(parent2)) { const argumentInfo = ts_SignatureHelp_exports.getArgumentInfoForCompletions(parent2.kind === 291 /* JsxAttribute */ ? parent2.parent : node, position, sourceFile); - return argumentInfo && (getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker) || getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker, 0 /* Normal */)) || fromContextualType(0 /* None */); + return argumentInfo && getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker) || fromContextualType(0 /* None */); } case 272 /* ImportDeclaration */: case 278 /* ExportDeclaration */: @@ -160638,12 +160722,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getAlreadyUsedTypesInStringLiteralUnion(union, current) { return mapDefined(union.types, (type) => type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : void 0); } - function getStringLiteralCompletionsFromSignature(call, arg, argumentInfo, checker, checkMode = 32 /* IsForStringLiteralArgumentCompletions */) { + function getStringLiteralCompletionsFromSignature(call, arg, argumentInfo, checker) { let isNewIdentifier = false; const uniques = /* @__PURE__ */ new Map(); - const candidates = []; const editingArgument = isJsxOpeningLikeElement(call) ? Debug.checkDefined(findAncestor(arg.parent, isJsxAttribute)) : arg; - checker.getResolvedSignatureForStringLiteralCompletions(call, editingArgument, candidates, checkMode); + const candidates = checker.getCandidateSignaturesForStringLiteralCompletions(call, editingArgument); const types = flatMap(candidates, (candidate) => { if (!signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; @@ -160703,7 +160786,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function addReplacementSpans(text, textStart, names) { const span = getDirectoryFragmentTextSpan(text, textStart); const wholeSpan = text.length === 0 ? void 0 : createTextSpan(textStart, text.length); - return names.map(({ name, kind, extension }) => Math.max(name.indexOf(directorySeparator), name.indexOf(altDirectorySeparator)) !== -1 ? { name, kind, extension, span: wholeSpan } : { name, kind, extension, span }); + return names.map(({ name, kind, extension }) => name.includes(directorySeparator) || name.includes(altDirectorySeparator) ? { name, kind, extension, span: wholeSpan } : { name, kind, extension, span }); } function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) { return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences)); @@ -160749,24 +160832,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getSupportedExtensionsForModuleResolution(compilerOptions, typeChecker) { - const ambientModulesExtensions = !typeChecker ? [] : mapDefined( - typeChecker.getAmbientModules(), - (module2) => { - const name = module2.name.slice(1, -1); - if (!name.startsWith("*.") || name.includes("/")) - return; - return name.slice(1); - } - ); + const ambientModulesExtensions = !typeChecker ? [] : mapDefined(typeChecker.getAmbientModules(), (module2) => { + const name = module2.name.slice(1, -1); + if (!name.startsWith("*.") || name.includes("/")) + return; + return name.slice(1); + }); const extensions = [...getSupportedExtensions(compilerOptions), ambientModulesExtensions]; const moduleResolution = getEmitModuleResolutionKind(compilerOptions); return moduleResolutionUsesNodeModules(moduleResolution) ? getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, extensions) : extensions; } function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) { - rootDirs = rootDirs.map((rootDirectory) => normalizePath(isRootedDiskPath(rootDirectory) ? rootDirectory : combinePaths(basePath, rootDirectory))); + rootDirs = rootDirs.map((rootDirectory) => ensureTrailingDirectorySeparator(normalizePath(isRootedDiskPath(rootDirectory) ? rootDirectory : combinePaths(basePath, rootDirectory)))); const relativeDirectory = firstDefined(rootDirs, (rootDirectory) => containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : void 0); return deduplicate( - [...rootDirs.map((rootDirectory) => combinePaths(rootDirectory, relativeDirectory)), scriptDirectory], + [...rootDirs.map((rootDirectory) => combinePaths(rootDirectory, relativeDirectory)), scriptDirectory].map((baseDir) => removeTrailingDirectorySeparator(baseDir)), equateStringsCaseSensitive, compareStringsCaseSensitive ); @@ -161004,7 +161084,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const keys = getOwnKeys(exports); const fragmentSubpath = components.join("/") + (components.length && hasTrailingDirectorySeparator(fragment) ? "/" : ""); - const conditions = getConditions(compilerOptions, mode === 99 /* ESNext */); + const conditions = getConditions(compilerOptions, mode); addCompletionEntriesFromPathsOrExports( result, fragmentSubpath, @@ -161032,7 +161112,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (target && typeof target === "object" && !isArray(target)) { for (const condition in target) { - if (condition === "default" || conditions.indexOf(condition) > -1 || isApplicableVersionedTypesKey(conditions, condition)) { + if (condition === "default" || conditions.includes(condition) || isApplicableVersionedTypesKey(conditions, condition)) { const pattern = target[condition]; return getPatternFromFirstMatchingCondition(pattern, conditions); } @@ -161044,7 +161124,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, host) { if (!endsWith(path, "*")) { - return !stringContains(path, "*") ? justPathMappingName(path, "script" /* scriptElement */) : emptyArray; + return !path.includes("*") ? justPathMappingName(path, "script" /* scriptElement */) : emptyArray; } const pathPrefix = path.slice(0, path.length - 1); const remainingFragment = tryRemovePrefix(fragment, pathPrefix); @@ -161114,7 +161194,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) { const ambientModules = checker.getAmbientModules().map((sym) => stripQuotes(sym.name)); - const nonRelativeModuleNames = ambientModules.filter((moduleName) => startsWith(moduleName, fragment) && moduleName.indexOf("*") < 0); + const nonRelativeModuleNames = ambientModules.filter((moduleName) => startsWith(moduleName, fragment) && !moduleName.includes("*")); if (fragmentDirectory !== void 0) { const moduleNameWithSeparator = ensureTrailingDirectorySeparator(fragmentDirectory); return nonRelativeModuleNames.map((nonRelativeModuleName) => removePrefix(nonRelativeModuleName, moduleNameWithSeparator)); @@ -161228,7 +161308,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return false; } function containsSlash(fragment) { - return stringContains(fragment, directorySeparator); + return fragment.includes(directorySeparator); } function isRequireCallArgument(node) { return isCallExpression(node.parent) && firstOrUndefined(node.parent.arguments) === node && isIdentifier(node.parent.expression) && node.parent.expression.escapedText === "require"; @@ -161349,7 +161429,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} handleNamespaceImport( direct, direct.name, - hasSyntacticModifier(direct, 1 /* Export */), + hasSyntacticModifier(direct, 32 /* Export */), /*alreadyAddedDirect*/ false ); @@ -161664,7 +161744,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } else { const exportNode = getExportNode(parent2, node); - if (exportNode && hasSyntacticModifier(exportNode, 1 /* Export */)) { + if (exportNode && hasSyntacticModifier(exportNode, 32 /* Export */)) { if (isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) { if (comingFromExport) { return void 0; @@ -161741,7 +161821,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return exportInfo2 && { kind: 1 /* Export */, symbol: symbol2, exportInfo: exportInfo2 }; } function getExportKindForDeclaration(node2) { - return hasSyntacticModifier(node2, 1024 /* Default */) ? 1 /* Default */ : 0 /* Named */; + return hasSyntacticModifier(node2, 2048 /* Default */) ? 1 /* Default */ : 0 /* Named */; } } function getExportEqualsLocalSymbol(importedSymbol, checker) { @@ -161875,10 +161955,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else if (isStringLiteralLike(node)) { const validImport = tryGetImportFromModuleSpecifier(node); if (validImport) { - const declOrStatement = findAncestor( - validImport, - (node2) => isDeclaration(node2) || isStatement(node2) || isJSDocTag(node2) - ); + const declOrStatement = findAncestor(validImport, (node2) => isDeclaration(node2) || isStatement(node2) || isJSDocTag(node2)); return isDeclaration(declOrStatement) ? getContextNode(declOrStatement) : declOrStatement; } } @@ -161888,7 +161965,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (node.parent.name === node || // node is name of declaration, use parent isConstructorDeclaration(node.parent) || isExportAssignment(node.parent) || // Property name of the import export specifier or binding pattern, use parent (isImportOrExportSpecifier(node.parent) || isBindingElement(node.parent)) && node.parent.propertyName === node || // Is default export - node.kind === 90 /* DefaultKeyword */ && hasSyntacticModifier(node.parent, 1025 /* ExportDefault */)) { + node.kind === 90 /* DefaultKeyword */ && hasSyntacticModifier(node.parent, 2080 /* ExportDefault */)) { return getContextNode(node.parent); } return void 0; @@ -161920,10 +161997,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 303 /* PropertyAssignment */: case 304 /* ShorthandPropertyAssignment */: return isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ? getContextNode( - findAncestor( - node.parent, - (node2) => isBinaryExpression(node2) || isForInOrOfStatement(node2) - ) + findAncestor(node.parent, (node2) => isBinaryExpression(node2) || isForInOrOfStatement(node2)) ) : node; default: return node; @@ -162316,7 +162390,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} })(FindReferencesUse || {}); ((Core2) => { function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options = {}, sourceFilesSet = new Set(sourceFiles.map((f) => f.fileName))) { - var _a, _b, _c; + var _a, _b; node = getAdjustedNode2(node, options); if (isSourceFile(node)) { const resolvedRef = ts_GoToDefinition_exports.getReferenceAtPosition(node, position, program); @@ -162355,7 +162429,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!options.implementations && isStringLiteralLike(node)) { if (isModuleSpecifierLike(node)) { const fileIncludeReasons = program.getFileIncludeReasons(); - const referencedFileName = (_c = (_b = (_a = node.getSourceFile().resolvedModules) == null ? void 0 : _a.get(node.text, getModeForUsageLocation(node.getSourceFile(), node))) == null ? void 0 : _b.resolvedModule) == null ? void 0 : _c.resolvedFileName; + const referencedFileName = (_b = (_a = program.getResolvedModule(node.getSourceFile(), node.text, getModeForUsageLocation(node.getSourceFile(), node))) == null ? void 0 : _a.resolvedModule) == null ? void 0 : _b.resolvedFileName; const referencedFile = referencedFileName ? program.getSourceFile(referencedFileName) : void 0; if (referencedFile) { return [{ definition: { type: 4 /* String */, node }, references: getReferencesForNonModule(referencedFile, fileIncludeReasons, program) || emptyArray }]; @@ -162418,7 +162492,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} for (const ref of references) { if (isReferencedFile(ref)) { const referencingFile = program.getSourceFileByPath(ref.file); - const location = getReferencedFileLocation(program.getSourceFileByPath, ref); + const location = getReferencedFileLocation(program, ref); if (isReferenceFileLocation(location)) { entries = append(entries, { kind: 0 /* Span */, @@ -162874,7 +162948,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; } if (flags & (4 /* Property */ | 8192 /* Method */)) { - const privateDeclaration = find(declarations, (d) => hasEffectiveModifier(d, 8 /* Private */) || isPrivateIdentifierClassElementDeclaration(d)); + const privateDeclaration = find(declarations, (d) => hasEffectiveModifier(d, 2 /* Private */) || isPrivateIdentifierClassElementDeclaration(d)); if (privateDeclaration) { return getAncestor(privateDeclaration, 263 /* ClassDeclaration */); } @@ -163366,10 +163440,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return cached; } cachedResults.set(key, false); - const inherits = !!symbol.declarations && symbol.declarations.some((declaration) => getAllSuperTypeNodes(declaration).some((typeReference) => { - const type = checker.getTypeAtLocation(typeReference); - return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent2, cachedResults, checker); - })); + const inherits = !!symbol.declarations && symbol.declarations.some( + (declaration) => getAllSuperTypeNodes(declaration).some((typeReference) => { + const type = checker.getTypeAtLocation(typeReference); + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent2, cachedResults, checker); + }) + ); cachedResults.set(key, inherits); return inherits; } @@ -163382,7 +163458,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!searchSpaceNode) { return void 0; } - let staticFlag = 32 /* Static */; + let staticFlag = 256 /* Static */; switch (searchSpaceNode.kind) { case 172 /* PropertyDeclaration */: case 171 /* PropertySignature */: @@ -163422,7 +163498,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} /*includeClassComputedPropertyName*/ false ); - let staticFlag = 32 /* Static */; + let staticFlag = 256 /* Static */; switch (searchSpaceNode.kind) { case 174 /* MethodDeclaration */: case 173 /* MethodSignature */: @@ -163664,7 +163740,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!symbol.valueDeclaration) return false; const modifierFlags = getEffectiveModifierFlags(symbol.valueDeclaration); - return !!(modifierFlags & 32 /* Static */); + return !!(modifierFlags & 256 /* Static */); } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { const { checker } = state; @@ -163783,7 +163859,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/goToDefinition.ts function getDefinitionAtPosition(program, sourceFile, position, searchOtherFilesOnly, stopAtAlias) { - var _a, _b; + var _a; const resolvedRef = getReferenceAtPosition(sourceFile, position, program); const fileReferenceDefinition = resolvedRef && [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.fileName, resolvedRef.unverified)] || emptyArray; if (resolvedRef == null ? void 0 : resolvedRef.file) { @@ -163856,7 +163932,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } if (!symbol && isModuleSpecifierLike(fallbackNode)) { - const ref = (_b = (_a = sourceFile.resolvedModules) == null ? void 0 : _a.get(fallbackNode.text, getModeForUsageLocation(sourceFile, fallbackNode))) == null ? void 0 : _b.resolvedModule; + const ref = (_a = program.getResolvedModule(sourceFile, fallbackNode.text, getModeForUsageLocation(sourceFile, fallbackNode))) == null ? void 0 : _a.resolvedModule; if (ref) { return [{ name: fallbackNode.text, @@ -163951,7 +164027,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return getDefinitionFromSymbol(typeChecker, symbol, node); } function getReferenceAtPosition(sourceFile, position, program) { - var _a, _b, _c, _d; + var _a, _b; const referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { const file = program.getSourceFileFromReference(sourceFile, referencePath); @@ -163968,10 +164044,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const file = program.getLibFileFromReference(libReferenceDirective); return file && { reference: libReferenceDirective, fileName: file.fileName, file, unverified: false }; } - if ((_b = sourceFile.resolvedModules) == null ? void 0 : _b.size()) { + if (sourceFile.imports.length || sourceFile.moduleAugmentations.length) { const node = getTouchingToken(sourceFile, position); - if (isModuleSpecifierLike(node) && isExternalModuleNameRelative(node.text) && sourceFile.resolvedModules.has(node.text, getModeForUsageLocation(sourceFile, node))) { - const verifiedFileName = (_d = (_c = sourceFile.resolvedModules.get(node.text, getModeForUsageLocation(sourceFile, node))) == null ? void 0 : _c.resolvedModule) == null ? void 0 : _d.resolvedFileName; + let resolution; + if (isModuleSpecifierLike(node) && isExternalModuleNameRelative(node.text) && (resolution = program.getResolvedModule(sourceFile, node.text, getModeForUsageLocation(sourceFile, node)))) { + const verifiedFileName = (_b = resolution.resolvedModule) == null ? void 0 : _b.resolvedFileName; const fileName = verifiedFileName || resolvePath(getDirectoryPath(sourceFile.fileName), node.text); return { file: program.getSourceFile(fileName), @@ -164219,7 +164296,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 177 /* GetAccessor */: case 178 /* SetAccessor */: case 174 /* MethodDeclaration */: - if (hasEffectiveModifier(declaration, 8 /* Private */)) + if (hasEffectiveModifier(declaration, 2 /* Private */)) return false; case 176 /* Constructor */: case 303 /* PropertyAssignment */: @@ -164339,6 +164416,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const { file, program, span, cancellationToken, preferences } = context; const sourceFileText = file.text; const compilerOptions = program.getCompilerOptions(); + const quotePreference = getQuotePreference(file, preferences); const checker = program.getTypeChecker(); const result = []; visitor(file); @@ -164402,9 +164480,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} displayParts }); } - function addTypeHints(text, position) { + function addTypeHints(hintText, position) { result.push({ - text: `: ${text.length > maxTypeHintLength ? text.substr(0, maxTypeHintLength - "...".length) + "..." : text}`, + text: typeof hintText === "string" ? `: ${hintText}` : "", + displayParts: typeof hintText === "string" ? void 0 : [{ text: ": " }, ...hintText], position, kind: "Type" /* Type */, whitespaceBefore: true @@ -164442,13 +164521,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isModuleReferenceType(declarationType)) { return; } - const typeDisplayString = printTypeInSingleLine(declarationType); - if (typeDisplayString) { - const isVariableNameMatchesType = preferences.includeInlayVariableTypeHintsWhenTypeMatchesName === false && equateStringsCaseInsensitive(decl.name.getText(), typeDisplayString); + const hintParts = typeToInlayHintParts(declarationType); + if (hintParts) { + const hintText = typeof hintParts === "string" ? hintParts : hintParts.map((part) => part.text).join(""); + const isVariableNameMatchesType = preferences.includeInlayVariableTypeHintsWhenTypeMatchesName === false && equateStringsCaseInsensitive(decl.name.getText(), hintText); if (isVariableNameMatchesType) { return; } - addTypeHints(typeDisplayString, decl.name.end); + addTypeHints(hintParts, decl.name.end); } } function visitCallOrNewExpression(expr) { @@ -164465,6 +164545,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} for (const originalArg of args) { const arg = skipParentheses(originalArg); if (shouldShowLiteralParameterNameHintsOnly(preferences) && !isHintableLiteral(arg)) { + signatureParamPos++; continue; } let spreadArgs = 0; @@ -164555,11 +164636,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isModuleReferenceType(returnType)) { return; } - const typeDisplayString = printTypeInSingleLine(returnType); - if (!typeDisplayString) { - return; + const hintParts = typeToInlayHintParts(returnType); + if (hintParts) { + addTypeHints(hintParts, getTypeAnnotationPosition(decl)); } - addTypeHints(typeDisplayString, getTypeAnnotationPosition(decl)); } function getTypeAnnotationPosition(decl) { const closeParenToken = findChildOfKind(decl, 22 /* CloseParenToken */, file); @@ -164582,14 +164662,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (effectiveTypeAnnotation) { continue; } - const typeDisplayString = getParameterDeclarationTypeDisplayString(signature.parameters[i]); - if (!typeDisplayString) { + const typeHints = getParameterDeclarationTypeHints(signature.parameters[i]); + if (!typeHints) { continue; } - addTypeHints(typeDisplayString, param.questionToken ? param.questionToken.end : param.name.end); + addTypeHints(typeHints, param.questionToken ? param.questionToken.end : param.name.end); } } - function getParameterDeclarationTypeDisplayString(symbol) { + function getParameterDeclarationTypeHints(symbol) { const valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || !isParameter(valueDeclaration)) { return void 0; @@ -164598,7 +164678,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isModuleReferenceType(signatureParamType)) { return void 0; } - return printTypeInSingleLine(signatureParamType); + return typeToInlayHintParts(signatureParamType); } function printTypeInSingleLine(type) { const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; @@ -164620,6 +164700,307 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} ); }); } + function typeToInlayHintParts(type) { + if (!shouldUseInteractiveInlayHints(preferences)) { + return printTypeInSingleLine(type); + } + const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + const typeNode = checker.typeToTypeNode( + type, + /*enclosingDeclaration*/ + void 0, + flags + ); + Debug.assertIsDefined(typeNode, "should always get typenode"); + const parts = []; + visitForDisplayParts(typeNode); + return parts; + function visitForDisplayParts(node) { + if (!node) { + return; + } + const tokenString = tokenToString(node.kind); + if (tokenString) { + parts.push({ text: tokenString }); + return; + } + if (isLiteralExpression(node)) { + parts.push({ text: getLiteralText2(node) }); + return; + } + switch (node.kind) { + case 80 /* Identifier */: + const identifier = node; + const identifierText = idText(identifier); + const name = identifier.symbol && identifier.symbol.declarations && identifier.symbol.declarations.length && getNameOfDeclaration(identifier.symbol.declarations[0]); + if (name) { + parts.push(getNodeDisplayPart(identifierText, name)); + } else { + parts.push({ text: identifierText }); + } + break; + case 166 /* QualifiedName */: + const qualifiedName = node; + visitForDisplayParts(qualifiedName.left); + parts.push({ text: "." }); + visitForDisplayParts(qualifiedName.right); + break; + case 182 /* TypePredicate */: + const predicate = node; + if (predicate.assertsModifier) { + parts.push({ text: "asserts " }); + } + visitForDisplayParts(predicate.parameterName); + if (predicate.type) { + parts.push({ text: " is " }); + visitForDisplayParts(predicate.type); + } + break; + case 183 /* TypeReference */: + const typeReference = node; + visitForDisplayParts(typeReference.typeName); + if (typeReference.typeArguments) { + parts.push({ text: "<" }); + visitDisplayPartList(typeReference.typeArguments, ", "); + parts.push({ text: ">" }); + } + break; + case 168 /* TypeParameter */: + const typeParameter = node; + if (typeParameter.modifiers) { + visitDisplayPartList(typeParameter.modifiers, " "); + } + visitForDisplayParts(typeParameter.name); + if (typeParameter.constraint) { + parts.push({ text: " extends " }); + visitForDisplayParts(typeParameter.constraint); + } + if (typeParameter.default) { + parts.push({ text: " = " }); + visitForDisplayParts(typeParameter.default); + } + break; + case 169 /* Parameter */: + const parameter = node; + if (parameter.modifiers) { + visitDisplayPartList(parameter.modifiers, " "); + } + if (parameter.dotDotDotToken) { + parts.push({ text: "..." }); + } + visitForDisplayParts(parameter.name); + if (parameter.questionToken) { + parts.push({ text: "?" }); + } + if (parameter.type) { + parts.push({ text: ": " }); + visitForDisplayParts(parameter.type); + } + break; + case 185 /* ConstructorType */: + const constructorType = node; + parts.push({ text: "new " }); + if (constructorType.typeParameters) { + parts.push({ text: "<" }); + visitDisplayPartList(constructorType.typeParameters, ", "); + parts.push({ text: ">" }); + } + parts.push({ text: "(" }); + visitDisplayPartList(constructorType.parameters, ", "); + parts.push({ text: ")" }); + parts.push({ text: " => " }); + visitForDisplayParts(constructorType.type); + break; + case 186 /* TypeQuery */: + const typeQuery = node; + parts.push({ text: "typeof " }); + visitForDisplayParts(typeQuery.exprName); + if (typeQuery.typeArguments) { + parts.push({ text: "<" }); + visitDisplayPartList(typeQuery.typeArguments, ", "); + parts.push({ text: ">" }); + } + break; + case 187 /* TypeLiteral */: + const typeLiteral = node; + parts.push({ text: "{" }); + if (typeLiteral.members.length) { + parts.push({ text: " " }); + visitDisplayPartList(typeLiteral.members, "; "); + parts.push({ text: " " }); + } + parts.push({ text: "}" }); + break; + case 188 /* ArrayType */: + visitForDisplayParts(node.elementType); + parts.push({ text: "[]" }); + break; + case 189 /* TupleType */: + parts.push({ text: "[" }); + visitDisplayPartList(node.elements, ", "); + parts.push({ text: "]" }); + break; + case 202 /* NamedTupleMember */: + const member = node; + if (member.dotDotDotToken) { + parts.push({ text: "..." }); + } + visitForDisplayParts(member.name); + if (member.questionToken) { + parts.push({ text: "?" }); + } + parts.push({ text: ": " }); + visitForDisplayParts(member.type); + break; + case 190 /* OptionalType */: + visitForDisplayParts(node.type); + parts.push({ text: "?" }); + break; + case 191 /* RestType */: + parts.push({ text: "..." }); + visitForDisplayParts(node.type); + break; + case 192 /* UnionType */: + visitDisplayPartList(node.types, " | "); + break; + case 193 /* IntersectionType */: + visitDisplayPartList(node.types, " & "); + break; + case 194 /* ConditionalType */: + const conditionalType = node; + visitForDisplayParts(conditionalType.checkType); + parts.push({ text: " extends " }); + visitForDisplayParts(conditionalType.extendsType); + parts.push({ text: " ? " }); + visitForDisplayParts(conditionalType.trueType); + parts.push({ text: " : " }); + visitForDisplayParts(conditionalType.falseType); + break; + case 195 /* InferType */: + parts.push({ text: "infer " }); + visitForDisplayParts(node.typeParameter); + break; + case 196 /* ParenthesizedType */: + parts.push({ text: "(" }); + visitForDisplayParts(node.type); + parts.push({ text: ")" }); + break; + case 198 /* TypeOperator */: + const typeOperator = node; + parts.push({ text: `${tokenToString(typeOperator.operator)} ` }); + visitForDisplayParts(typeOperator.type); + break; + case 199 /* IndexedAccessType */: + const indexedAccess = node; + visitForDisplayParts(indexedAccess.objectType); + parts.push({ text: "[" }); + visitForDisplayParts(indexedAccess.indexType); + parts.push({ text: "]" }); + break; + case 200 /* MappedType */: + const mappedType = node; + parts.push({ text: "{ " }); + if (mappedType.readonlyToken) { + if (mappedType.readonlyToken.kind === 40 /* PlusToken */) { + parts.push({ text: "+" }); + } else if (mappedType.readonlyToken.kind === 41 /* MinusToken */) { + parts.push({ text: "-" }); + } + parts.push({ text: "readonly " }); + } + parts.push({ text: "[" }); + visitForDisplayParts(mappedType.typeParameter); + if (mappedType.nameType) { + parts.push({ text: " as " }); + visitForDisplayParts(mappedType.nameType); + } + parts.push({ text: "]" }); + if (mappedType.questionToken) { + if (mappedType.questionToken.kind === 40 /* PlusToken */) { + parts.push({ text: "+" }); + } else if (mappedType.questionToken.kind === 41 /* MinusToken */) { + parts.push({ text: "-" }); + } + parts.push({ text: "?" }); + } + parts.push({ text: ": " }); + if (mappedType.type) { + visitForDisplayParts(mappedType.type); + } + parts.push({ text: "; }" }); + break; + case 201 /* LiteralType */: + visitForDisplayParts(node.literal); + break; + case 184 /* FunctionType */: + const functionType = node; + if (functionType.typeParameters) { + parts.push({ text: "<" }); + visitDisplayPartList(functionType.typeParameters, ", "); + parts.push({ text: ">" }); + } + parts.push({ text: "(" }); + visitDisplayPartList(functionType.parameters, ", "); + parts.push({ text: ")" }); + parts.push({ text: " => " }); + visitForDisplayParts(functionType.type); + break; + case 205 /* ImportType */: + const importType = node; + if (importType.isTypeOf) { + parts.push({ text: "typeof " }); + } + parts.push({ text: "import(" }); + visitForDisplayParts(importType.argument); + if (importType.assertions) { + parts.push({ text: ", { assert: " }); + visitDisplayPartList(importType.assertions.assertClause.elements, ", "); + parts.push({ text: " }" }); + } + parts.push({ text: ")" }); + if (importType.qualifier) { + parts.push({ text: "." }); + visitForDisplayParts(importType.qualifier); + } + if (importType.typeArguments) { + parts.push({ text: "<" }); + visitDisplayPartList(importType.typeArguments, ", "); + parts.push({ text: ">" }); + } + break; + case 171 /* PropertySignature */: + const propertySignature = node; + if (propertySignature.modifiers) { + visitDisplayPartList(propertySignature.modifiers, " "); + } + visitForDisplayParts(propertySignature.name); + if (propertySignature.questionToken) { + parts.push({ text: "?" }); + } + if (propertySignature.type) { + parts.push({ text: ": " }); + visitForDisplayParts(propertySignature.type); + } + break; + default: + Debug.failBadSyntaxKind(node); + } + } + function visitDisplayPartList(nodes, separator) { + nodes.forEach((node, index) => { + if (index > 0) { + parts.push({ text: separator }); + } + visitForDisplayParts(node); + }); + } + function getLiteralText2(node) { + if (isStringLiteral(node)) { + return quotePreference === 0 /* Single */ ? `'${escapeString(node.text, 39 /* singleQuote */)}'` : `"${escapeString(node.text, 34 /* doubleQuote */)}"`; + } + return node.text; + } + } function isUndefined(name) { return name === "undefined"; } @@ -164639,12 +165020,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }; } } - var maxTypeHintLength, leadingParameterNameCommentRegexFactory; + var leadingParameterNameCommentRegexFactory; var init_inlayHints = __esm({ "src/services/inlayHints.ts"() { "use strict"; init_ts4(); - maxTypeHintLength = 30; leadingParameterNameCommentRegexFactory = (name) => { return new RegExp(`^\\s?/\\*\\*?\\s?${name}\\s?\\*\\/\\s?$`); }; @@ -164694,6 +165074,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 345 /* JSDocCallbackTag */: case 353 /* JSDocTypedefTag */: return [declaration, declaration.parent]; + case 330 /* JSDocSignature */: + if (isJSDocOverloadTag(declaration.parent)) { + return [declaration.parent.parent]; + } default: return getJSDocCommentsAndTags(declaration); } @@ -164707,6 +165091,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } for (const tag of tags) { infos.push({ name: tag.tagName.text, text: getCommentDisplayParts(tag, checker) }); + if (isJSDocPropertyLikeTag(tag) && tag.isNameFirst && tag.typeExpression && isJSDocTypeLiteral(tag.typeExpression.type)) { + forEach(tag.typeExpression.type.jsDocPropertyTags, (propTag) => { + infos.push({ name: propTag.tagName.text, text: getCommentDisplayParts(propTag, checker) }); + }); + } } }); return infos; @@ -165230,7 +165619,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} /*importClause*/ void 0, moduleSpecifier, - /*assertClause*/ + /*attributes*/ void 0 )); } else { @@ -165396,7 +165785,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} exportDecl.isTypeOnly, exportDecl.exportClause && (isNamedExports(exportDecl.exportClause) ? factory.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) : factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)), exportDecl.moduleSpecifier, - exportDecl.assertClause + exportDecl.attributes ) ); } @@ -165428,7 +165817,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), // TODO: GH#18217 importDeclaration.moduleSpecifier, - importDeclaration.assertClause + importDeclaration.attributes ); } function sortSpecifiers(specifiers, comparer) { @@ -165570,19 +165959,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getNewImportSpecifiers(namedImports) { - return flatMap( - namedImports, - (namedImport) => map( - tryGetNamedBindingElements(namedImport), - (importSpecifier) => importSpecifier.name && importSpecifier.propertyName && importSpecifier.name.escapedText === importSpecifier.propertyName.escapedText ? factory.updateImportSpecifier( - importSpecifier, - importSpecifier.isTypeOnly, - /*propertyName*/ - void 0, - importSpecifier.name - ) : importSpecifier - ) - ); + return flatMap(namedImports, (namedImport) => map(tryGetNamedBindingElements(namedImport), (importSpecifier) => importSpecifier.name && importSpecifier.propertyName && importSpecifier.name.escapedText === importSpecifier.propertyName.escapedText ? factory.updateImportSpecifier( + importSpecifier, + importSpecifier.isTypeOnly, + /*propertyName*/ + void 0, + importSpecifier.name + ) : importSpecifier)); } function tryGetNamedBindingElements(namedImport) { var _a; @@ -165816,11 +166199,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function isRegionDelimiter(lineText) { - lineText = trimStringStart(lineText); + lineText = lineText.trimStart(); if (!startsWith(lineText, "//")) { return null; } - lineText = trimString(lineText.slice(2)); + lineText = lineText.slice(2).trim(); return regionDelimiterRegExp.exec(lineText); } function addOutliningForLeadingCommentsForPos(pos, sourceFile, cancellationToken, out) { @@ -165952,10 +166335,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return spanForParenthesizedExpression(n); case 275 /* NamedImports */: case 279 /* NamedExports */: - case 300 /* AssertClause */: - return spanForNamedImportsOrExportsOrAssertClause(n); + case 300 /* ImportAttributes */: + return spanForImportExportElements(n); } - function spanForNamedImportsOrExportsOrAssertClause(node) { + function spanForImportExportElements(node) { if (!node.elements.length) { return void 0; } @@ -166916,10 +167299,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} Debug.assertEqual(openBraceToken.kind, 19 /* OpenBraceToken */); Debug.assertEqual(closeBraceToken.kind, 20 /* CloseBraceToken */); const groupedWithPlusMinusTokens = groupChildren(children, (child) => child === node.readonlyToken || child.kind === 148 /* ReadonlyKeyword */ || child === node.questionToken || child.kind === 58 /* QuestionToken */); - const groupedWithBrackets = groupChildren( - groupedWithPlusMinusTokens, - ({ kind }) => kind === 23 /* OpenBracketToken */ || kind === 168 /* TypeParameter */ || kind === 24 /* CloseBracketToken */ - ); + const groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, ({ kind }) => kind === 23 /* OpenBracketToken */ || kind === 168 /* TypeParameter */ || kind === 24 /* CloseBracketToken */); return [ openBraceToken, // Pivot on `:` @@ -167120,7 +167500,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getNormalizedSymbolModifiers(symbol) { if (symbol.declarations && symbol.declarations.length) { const [declaration, ...declarations] = symbol.declarations; - const excludeFlags = length(declarations) && isDeprecatedDeclaration(declaration) && some(declarations, (d) => !isDeprecatedDeclaration(d)) ? 8192 /* Deprecated */ : 0 /* None */; + const excludeFlags = length(declarations) && isDeprecatedDeclaration(declaration) && some(declarations, (d) => !isDeprecatedDeclaration(d)) ? 65536 /* Deprecated */ : 0 /* None */; const modifiers = getNodeModifiers(declaration, excludeFlags); if (modifiers) { return modifiers.split(","); @@ -167277,7 +167657,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 179 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); + addPrefixForAnyFunctionOrVar( + functionDeclaration.kind === 179 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, + symbolKind + ); } if (signature) { addSignatureDisplayParts(signature, allSignatures); @@ -167381,10 +167764,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} displayParts.push(spacePart()); displayParts.push(operatorPart(64 /* EqualsToken */)); displayParts.push(spacePart()); - displayParts.push(displayPart( - getTextOfConstantValue(constantValue), - typeof constantValue === "number" ? 7 /* numericLiteral */ : 8 /* stringLiteral */ - )); + displayParts.push(displayPart(getTextOfConstantValue(constantValue), typeof constantValue === "number" ? 7 /* numericLiteral */ : 8 /* stringLiteral */)); } } } @@ -167396,7 +167776,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const resolvedNode = resolvedSymbol.declarations[0]; const declarationName = getNameOfDeclaration(resolvedNode); if (declarationName && !hasAddedSymbolInfo) { - const isExternalModuleDeclaration = isModuleWithStringLiteralName(resolvedNode) && hasSyntacticModifier(resolvedNode, 2 /* Ambient */); + const isExternalModuleDeclaration = isModuleWithStringLiteralName(resolvedNode) && hasSyntacticModifier(resolvedNode, 128 /* Ambient */); const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKindWorker( typeChecker, @@ -167528,11 +167908,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (documentation.length === 0 && isIdentifier(location) && symbol.valueDeclaration && isBindingElement(symbol.valueDeclaration)) { const declaration = symbol.valueDeclaration; const parent2 = declaration.parent; - if (isIdentifier(declaration.name) && isObjectBindingPattern(parent2)) { - const name = getTextOfIdentifierOrLiteral(declaration.name); + const name = declaration.propertyName || declaration.name; + if (isIdentifier(name) && isObjectBindingPattern(parent2)) { + const propertyName = getTextOfIdentifierOrLiteral(name); const objectType = typeChecker.getTypeAtLocation(parent2); documentation = firstDefined(objectType.isUnion() ? objectType.types : [objectType], (t) => { - const prop = t.getProperty(name); + const prop = t.getProperty(propertyName); return prop ? prop.getDocumentationComment(typeChecker) : void 0; }) || emptyArray; } @@ -168465,8 +168846,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const startPosition = getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); const insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); const token = getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position); - const indent2 = sourceFile.text.slice(lineStartPosition, startPosition); - const text = `${insertAtLineStart ? "" : this.newLineCharacter}//${commentText}${this.newLineCharacter}${indent2}`; + const indent3 = sourceFile.text.slice(lineStartPosition, startPosition); + const text = `${insertAtLineStart ? "" : this.newLineCharacter}//${commentText}${this.newLineCharacter}${indent3}`; this.insertText(sourceFile, token.getStart(sourceFile), text); } insertJsdocCommentBefore(sourceFile, node, tag) { @@ -168485,8 +168866,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } const startPosition = getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1); - const indent2 = sourceFile.text.slice(startPosition, fnStart); - this.insertNodeAt(sourceFile, fnStart, tag, { suffix: this.newLineCharacter + indent2 }); + const indent3 = sourceFile.text.slice(startPosition, fnStart); + this.insertNodeAt(sourceFile, fnStart, tag, { suffix: this.newLineCharacter + indent3 }); } createJSDocText(sourceFile, node) { const comments = flatMap(node.jsDoc, (jsDoc2) => isString(jsDoc2.comment) ? factory.createJSDocText(jsDoc2.comment) : jsDoc2.comment); @@ -168498,12 +168879,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } addJSDocTags(sourceFile, parent2, newTags) { const oldTags = flatMapToMutable(parent2.jsDoc, (j) => j.tags); - const unmergedNewTags = newTags.filter((newTag) => !oldTags.some((tag, i) => { - const merged = tryMergeJsdocTags(tag, newTag); - if (merged) - oldTags[i] = merged; - return !!merged; - })); + const unmergedNewTags = newTags.filter( + (newTag) => !oldTags.some((tag, i) => { + const merged = tryMergeJsdocTags(tag, newTag); + if (merged) + oldTags[i] = merged; + return !!merged; + }) + ); this.replaceJSDocComment(sourceFile, parent2, [...oldTags, ...unmergedNewTags]); } filterJSDocTags(sourceFile, parent2, predicate) { @@ -168880,7 +169263,7 @@ ${options.prefix}` : "\n" : options.prefix const sourceFile = createSourceFile( "any file name", nonFormattedText, - 99 /* ESNext */, + { languageVersion: 99 /* ESNext */, jsDocParsingMode: 1 /* ParseNone */ }, /*setParentNodes*/ true, scriptKind @@ -169491,12 +169874,12 @@ ${options.prefix}` : "\n" : options.prefix rule("IgnoreBeforeComment", anyToken, comments, anyContext, 1 /* StopProcessingSpaceActions */), rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, anyContext, 1 /* StopProcessingSpaceActions */), rule("NotSpaceBeforeColon", anyToken, 59 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 16 /* DeleteSpace */), - rule("SpaceAfterColon", 59 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 4 /* InsertSpace */), + rule("SpaceAfterColon", 59 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNextTokenParentNotJsxNamespacedName], 4 /* InsertSpace */), rule("NoSpaceBeforeQuestionMark", anyToken, 58 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 16 /* DeleteSpace */), // insert space after '?' only when it is used in conditional operator rule("SpaceAfterQuestionMarkInConditionalOperator", 58 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */), // in other cases there should be no space between '?' and next token - rule("NoSpaceAfterQuestionMark", 58 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceAfterQuestionMark", 58 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isNonOptionalPropertyContext], 16 /* DeleteSpace */), rule("NoSpaceBeforeDot", anyToken, [25 /* DotToken */, 29 /* QuestionDotToken */], [isNonJsxSameLineTokenContext, isNotPropertyAccessOnIntegerLiteral], 16 /* DeleteSpace */), rule("NoSpaceAfterDot", [25 /* DotToken */, 29 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBetweenImportParenInImportType", 102 /* ImportKeyword */, 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */), @@ -169562,6 +169945,8 @@ ${options.prefix}` : "\n" : options.prefix rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 44 /* SlashToken */, 32 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 64 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceAfterEqualInJsxAttribute", 64 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceBeforeJsxNamespaceColon", 80 /* Identifier */, 59 /* ColonToken */, [isNextTokenParentJsxNamespacedName], 16 /* DeleteSpace */), + rule("NoSpaceAfterJsxNamespaceColon", 59 /* ColonToken */, 80 /* Identifier */, [isNextTokenParentJsxNamespacedName], 16 /* DeleteSpace */), // TypeScript-specific rules // Use of module as a function call. e.g.: import m2 = module("m2"); rule("NoSpaceAfterModuleImport", [144 /* ModuleKeyword */, 149 /* RequireKeyword */], 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), @@ -169624,6 +170009,7 @@ ${options.prefix}` : "\n" : options.prefix isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext, + /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/ isNonTypeAssertionContext ], 16 /* DeleteSpace */), // decorators @@ -169838,6 +170224,12 @@ ${options.prefix}` : "\n" : options.prefix const contextKind = context.contextNode.kind; return contextKind === 172 /* PropertyDeclaration */ || contextKind === 171 /* PropertySignature */ || contextKind === 169 /* Parameter */ || contextKind === 260 /* VariableDeclaration */ || isFunctionLikeKind(contextKind); } + function isOptionalPropertyContext(context) { + return isPropertyDeclaration(context.contextNode) && context.contextNode.questionToken; + } + function isNonOptionalPropertyContext(context) { + return !isOptionalPropertyContext(context); + } function isConditionalOperatorContext(context) { return context.contextNode.kind === 227 /* ConditionalExpression */ || context.contextNode.kind === 194 /* ConditionalType */; } @@ -169991,11 +170383,17 @@ ${options.prefix}` : "\n" : options.prefix return context.contextNode.kind === 294 /* JsxExpression */ || context.contextNode.kind === 293 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 291 /* JsxAttribute */; + return context.nextTokenParent.kind === 291 /* JsxAttribute */ || context.nextTokenParent.kind === 295 /* JsxNamespacedName */ && context.nextTokenParent.parent.kind === 291 /* JsxAttribute */; } function isJsxAttributeContext(context) { return context.contextNode.kind === 291 /* JsxAttribute */; } + function isNextTokenParentNotJsxNamespacedName(context) { + return context.nextTokenParent.kind !== 295 /* JsxNamespacedName */; + } + function isNextTokenParentJsxNamespacedName(context) { + return context.nextTokenParent.kind === 295 /* JsxNamespacedName */; + } function isJsxSelfClosingElementContext(context) { return context.contextNode.kind === 285 /* JsxSelfClosingElement */; } @@ -170121,7 +170519,7 @@ ${options.prefix}` : "\n" : options.prefix return positionIsASICandidate(context.currentTokenSpan.end, context.currentTokenParent, context.sourceFile); } function isNotPropertyAccessOnIntegerLiteral(context) { - return !isPropertyAccessExpression(context.contextNode) || !isNumericLiteral(context.contextNode.expression) || context.contextNode.expression.getText().indexOf(".") !== -1; + return !isPropertyAccessExpression(context.contextNode) || !isNumericLiteral(context.contextNode.expression) || context.contextNode.expression.getText().includes("."); } var init_rules = __esm({ "src/services/formatting/rules.ts"() { @@ -170851,17 +171249,12 @@ ${options.prefix}` : "\n" : options.prefix let indentNextTokenOrTrivia = true; if (currentTokenInfo.leadingTrivia) { const commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); - indentNextTokenOrTrivia = indentTriviaItems( - currentTokenInfo.leadingTrivia, + indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation, indentNextTokenOrTrivia, (item) => insertIndentation( + item.pos, commentIndentation, - indentNextTokenOrTrivia, - (item) => insertIndentation( - item.pos, - commentIndentation, - /*lineAdded*/ - false - ) - ); + /*lineAdded*/ + false + )); } if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) { insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */); @@ -171322,7 +171715,7 @@ ${options.prefix}` : "\n" : options.prefix } const containerList = getListByPosition(position, precedingToken.parent, sourceFile); if (containerList && !rangeContainsRange(containerList, precedingToken)) { - const useTheSameBaseIndentation = [218 /* FunctionExpression */, 219 /* ArrowFunction */].indexOf(currentToken.parent.kind) !== -1; + const useTheSameBaseIndentation = [218 /* FunctionExpression */, 219 /* ArrowFunction */].includes(currentToken.parent.kind); const indentSize = useTheSameBaseIndentation ? 0 : options.indentSize; return getActualIndentationForListStartLine(containerList, sourceFile, options) + indentSize; } @@ -171857,7 +172250,6 @@ ${options.prefix}` : "\n" : options.prefix init_transpile(); init_services(); init_transform(); - init_shims(); init_ts_BreakpointResolver(); init_ts_CallHierarchy(); init_ts_classifier(); @@ -171890,7 +172282,7 @@ ${options.prefix}` : "\n" : options.prefix deprecationMessage += `'${name}' `; deprecationMessage += since ? `has been deprecated since v${since}` : "is deprecated"; deprecationMessage += error2 ? " and can no longer be used." : errorAfter ? ` and will no longer be usable after v${errorAfter}.` : "."; - deprecationMessage += message ? ` ${formatStringFromArgs(message, [name], 0)}` : ""; + deprecationMessage += message ? ` ${formatStringFromArgs(message, [name])}` : ""; return deprecationMessage; } function createErrorDeprecation(name, errorAfter, since, message) { @@ -172050,7 +172442,11542 @@ ${options.prefix}` : "\n" : options.prefix } }); - // src/typescript/_namespaces/ts.ts + // src/typingsInstallerCore/_namespaces/ts.ts + var init_ts6 = __esm({ + "src/typingsInstallerCore/_namespaces/ts.ts"() { + "use strict"; + init_ts2(); + init_ts3(); + init_ts_server2(); + } + }); + + // src/typingsInstallerCore/typingsInstaller.ts + function typingToFileName(cachePath, packageName, installTypingHost, log) { + try { + const result = resolveModuleName(packageName, combinePaths(cachePath, "index.d.ts"), { moduleResolution: 2 /* Node10 */ }, installTypingHost); + return result.resolvedModule && result.resolvedModule.resolvedFileName; + } catch (e) { + if (log.isEnabled()) { + log.writeLine(`Failed to resolve ${packageName} in folder '${cachePath}': ${e.message}`); + } + return void 0; + } + } + function installNpmPackages(npmPath, tsVersion, packageNames, install) { + let hasError = false; + for (let remaining = packageNames.length; remaining > 0; ) { + const result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining); + remaining = result.remaining; + hasError = install(result.command) || hasError; + } + return hasError; + } + function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) { + const sliceStart = packageNames.length - remaining; + let command, toSlice = remaining; + while (true) { + command = `${npmPath} install --ignore-scripts ${(toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ")} --save-dev --user-agent="typesInstaller/${tsVersion}"`; + if (command.length < 8e3) { + break; + } + toSlice = toSlice - Math.floor(toSlice / 2); + } + return { command, remaining: remaining - toSlice }; + } + function typingsName(packageName) { + return `@types/${packageName}@ts${versionMajorMinor}`; + } + var nullLog, TypingsInstaller; + var init_typingsInstaller = __esm({ + "src/typingsInstallerCore/typingsInstaller.ts"() { + "use strict"; + init_ts6(); + init_ts_server2(); + nullLog = { + isEnabled: () => false, + writeLine: noop + }; + TypingsInstaller = class { + constructor(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log = nullLog) { + this.installTypingHost = installTypingHost; + this.globalCachePath = globalCachePath; + this.safeListPath = safeListPath; + this.typesMapLocation = typesMapLocation; + this.throttleLimit = throttleLimit; + this.log = log; + this.packageNameToTypingLocation = /* @__PURE__ */ new Map(); + this.missingTypingsSet = /* @__PURE__ */ new Set(); + this.knownCachesSet = /* @__PURE__ */ new Set(); + this.projectWatchers = /* @__PURE__ */ new Map(); + /** @internal */ + this.pendingRunRequests = []; + this.installRunCount = 1; + this.inFlightRequestCount = 0; + this.latestDistTag = "latest"; + const isLoggingEnabled = this.log.isEnabled(); + if (isLoggingEnabled) { + this.log.writeLine(`Global cache location '${globalCachePath}', safe file path '${safeListPath}', types map path ${typesMapLocation}`); + } + this.processCacheLocation(this.globalCachePath); + } + closeProject(req) { + this.closeWatchers(req.projectName); + } + closeWatchers(projectName) { + if (this.log.isEnabled()) { + this.log.writeLine(`Closing file watchers for project '${projectName}'`); + } + const watchers = this.projectWatchers.get(projectName); + if (!watchers) { + if (this.log.isEnabled()) { + this.log.writeLine(`No watchers are registered for project '${projectName}'`); + } + return; + } + this.projectWatchers.delete(projectName); + this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: [] }); + if (this.log.isEnabled()) { + this.log.writeLine(`Closing file watchers for project '${projectName}' - done.`); + } + } + install(req) { + if (this.log.isEnabled()) { + this.log.writeLine(`Got install request${stringifyIndented(req)}`); + } + if (req.cachePath) { + if (this.log.isEnabled()) { + this.log.writeLine(`Request specifies cache path '${req.cachePath}', loading cached information...`); + } + this.processCacheLocation(req.cachePath); + } + if (this.safeList === void 0) { + this.initializeSafeList(); + } + const discoverTypingsResult = ts_JsTyping_exports.discoverTypings( + this.installTypingHost, + this.log.isEnabled() ? (s) => this.log.writeLine(s) : void 0, + req.fileNames, + req.projectRootPath, + this.safeList, + this.packageNameToTypingLocation, + req.typeAcquisition, + req.unresolvedImports, + this.typesRegistry, + req.compilerOptions + ); + this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch); + if (discoverTypingsResult.newTypingNames.length) { + this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames); + } else { + this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths)); + if (this.log.isEnabled()) { + this.log.writeLine(`No new typings were requested as a result of typings discovery`); + } + } + } + initializeSafeList() { + if (this.typesMapLocation) { + const safeListFromMap = ts_JsTyping_exports.loadTypesMap(this.installTypingHost, this.typesMapLocation); + if (safeListFromMap) { + this.log.writeLine(`Loaded safelist from types map file '${this.typesMapLocation}'`); + this.safeList = safeListFromMap; + return; + } + this.log.writeLine(`Failed to load safelist from types map file '${this.typesMapLocation}'`); + } + this.safeList = ts_JsTyping_exports.loadSafeList(this.installTypingHost, this.safeListPath); + } + processCacheLocation(cacheLocation) { + if (this.log.isEnabled()) { + this.log.writeLine(`Processing cache location '${cacheLocation}'`); + } + if (this.knownCachesSet.has(cacheLocation)) { + if (this.log.isEnabled()) { + this.log.writeLine(`Cache location was already processed...`); + } + return; + } + const packageJson = combinePaths(cacheLocation, "package.json"); + const packageLockJson = combinePaths(cacheLocation, "package-lock.json"); + if (this.log.isEnabled()) { + this.log.writeLine(`Trying to find '${packageJson}'...`); + } + if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) { + const npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson)); + const npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson)); + if (this.log.isEnabled()) { + this.log.writeLine(`Loaded content of '${packageJson}':${stringifyIndented(npmConfig)}`); + this.log.writeLine(`Loaded content of '${packageLockJson}':${stringifyIndented(npmLock)}`); + } + if (npmConfig.devDependencies && npmLock.dependencies) { + for (const key in npmConfig.devDependencies) { + if (!hasProperty(npmLock.dependencies, key)) { + continue; + } + const packageName = getBaseFileName(key); + if (!packageName) { + continue; + } + const typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log); + if (!typingFile) { + this.missingTypingsSet.add(packageName); + continue; + } + const existingTypingFile = this.packageNameToTypingLocation.get(packageName); + if (existingTypingFile) { + if (existingTypingFile.typingLocation === typingFile) { + continue; + } + if (this.log.isEnabled()) { + this.log.writeLine(`New typing for package ${packageName} from '${typingFile}' conflicts with existing typing file '${existingTypingFile}'`); + } + } + if (this.log.isEnabled()) { + this.log.writeLine(`Adding entry into typings cache: '${packageName}' => '${typingFile}'`); + } + const info = getProperty(npmLock.dependencies, key); + const version2 = info && info.version; + if (!version2) { + continue; + } + const newTyping = { typingLocation: typingFile, version: new Version(version2) }; + this.packageNameToTypingLocation.set(packageName, newTyping); + } + } + } + if (this.log.isEnabled()) { + this.log.writeLine(`Finished processing cache location '${cacheLocation}'`); + } + this.knownCachesSet.add(cacheLocation); + } + filterTypings(typingsToInstall) { + return mapDefined(typingsToInstall, (typing) => { + const typingKey = mangleScopedPackageName(typing); + if (this.missingTypingsSet.has(typingKey)) { + if (this.log.isEnabled()) + this.log.writeLine(`'${typing}':: '${typingKey}' is in missingTypingsSet - skipping...`); + return void 0; + } + const validationResult = ts_JsTyping_exports.validatePackageName(typing); + if (validationResult !== ts_JsTyping_exports.NameValidationResult.Ok) { + this.missingTypingsSet.add(typingKey); + if (this.log.isEnabled()) + this.log.writeLine(ts_JsTyping_exports.renderPackageNameValidationFailure(validationResult, typing)); + return void 0; + } + if (!this.typesRegistry.has(typingKey)) { + if (this.log.isEnabled()) + this.log.writeLine(`'${typing}':: Entry for package '${typingKey}' does not exist in local types registry - skipping...`); + return void 0; + } + if (this.packageNameToTypingLocation.get(typingKey) && ts_JsTyping_exports.isTypingUpToDate(this.packageNameToTypingLocation.get(typingKey), this.typesRegistry.get(typingKey))) { + if (this.log.isEnabled()) + this.log.writeLine(`'${typing}':: '${typingKey}' already has an up-to-date typing - skipping...`); + return void 0; + } + return typingKey; + }); + } + ensurePackageDirectoryExists(directory) { + const npmConfigPath = combinePaths(directory, "package.json"); + if (this.log.isEnabled()) { + this.log.writeLine(`Npm config file: ${npmConfigPath}`); + } + if (!this.installTypingHost.fileExists(npmConfigPath)) { + if (this.log.isEnabled()) { + this.log.writeLine(`Npm config file: '${npmConfigPath}' is missing, creating new one...`); + } + this.ensureDirectoryExists(directory, this.installTypingHost); + this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }'); + } + } + installTypings(req, cachePath, currentlyCachedTypings, typingsToInstall) { + if (this.log.isEnabled()) { + this.log.writeLine(`Installing typings ${JSON.stringify(typingsToInstall)}`); + } + const filteredTypings = this.filterTypings(typingsToInstall); + if (filteredTypings.length === 0) { + if (this.log.isEnabled()) { + this.log.writeLine(`All typings are known to be missing or invalid - no need to install more typings`); + } + this.sendResponse(this.createSetTypings(req, currentlyCachedTypings)); + return; + } + this.ensurePackageDirectoryExists(cachePath); + const requestId = this.installRunCount; + this.installRunCount++; + this.sendResponse({ + kind: EventBeginInstallTypes, + eventId: requestId, + typingsInstallerVersion: version, + projectName: req.projectName + }); + const scopedTypings = filteredTypings.map(typingsName); + this.installTypingsAsync(requestId, scopedTypings, cachePath, (ok) => { + try { + if (!ok) { + if (this.log.isEnabled()) { + this.log.writeLine(`install request failed, marking packages as missing to prevent repeated requests: ${JSON.stringify(filteredTypings)}`); + } + for (const typing of filteredTypings) { + this.missingTypingsSet.add(typing); + } + return; + } + if (this.log.isEnabled()) { + this.log.writeLine(`Installed typings ${JSON.stringify(scopedTypings)}`); + } + const installedTypingFiles = []; + for (const packageName of filteredTypings) { + const typingFile = typingToFileName(cachePath, packageName, this.installTypingHost, this.log); + if (!typingFile) { + this.missingTypingsSet.add(packageName); + continue; + } + const distTags = this.typesRegistry.get(packageName); + const newVersion = new Version(distTags[`ts${versionMajorMinor}`] || distTags[this.latestDistTag]); + const newTyping = { typingLocation: typingFile, version: newVersion }; + this.packageNameToTypingLocation.set(packageName, newTyping); + installedTypingFiles.push(typingFile); + } + if (this.log.isEnabled()) { + this.log.writeLine(`Installed typing files ${JSON.stringify(installedTypingFiles)}`); + } + this.sendResponse(this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles))); + } finally { + const response = { + kind: EventEndInstallTypes, + eventId: requestId, + projectName: req.projectName, + packagesToInstall: scopedTypings, + installSuccess: ok, + typingsInstallerVersion: version + }; + this.sendResponse(response); + } + }); + } + ensureDirectoryExists(directory, host) { + const directoryName = getDirectoryPath(directory); + if (!host.directoryExists(directoryName)) { + this.ensureDirectoryExists(directoryName, host); + } + if (!host.directoryExists(directory)) { + host.createDirectory(directory); + } + } + watchFiles(projectName, files) { + if (!files.length) { + this.closeWatchers(projectName); + return; + } + const existing = this.projectWatchers.get(projectName); + const newSet = new Set(files); + if (!existing || forEachKey(newSet, (s) => !existing.has(s)) || forEachKey(existing, (s) => !newSet.has(s))) { + this.projectWatchers.set(projectName, newSet); + this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files }); + } else { + this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: void 0 }); + } + } + createSetTypings(request, typings) { + return { + projectName: request.projectName, + typeAcquisition: request.typeAcquisition, + compilerOptions: request.compilerOptions, + typings, + unresolvedImports: request.unresolvedImports, + kind: ActionSet + }; + } + installTypingsAsync(requestId, packageNames, cwd, onRequestCompleted) { + this.pendingRunRequests.unshift({ requestId, packageNames, cwd, onRequestCompleted }); + this.executeWithThrottling(); + } + executeWithThrottling() { + while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) { + this.inFlightRequestCount++; + const request = this.pendingRunRequests.pop(); + this.installWorker(request.requestId, request.packageNames, request.cwd, (ok) => { + this.inFlightRequestCount--; + request.onRequestCompleted(ok); + this.executeWithThrottling(); + }); + } + } + }; + } + }); + + // src/typingsInstallerCore/_namespaces/ts.server.typingsInstaller.ts + var ts_server_typingsInstaller_exports = {}; + __export(ts_server_typingsInstaller_exports, { + TypingsInstaller: () => TypingsInstaller, + getNpmCommandForInstallation: () => getNpmCommandForInstallation, + installNpmPackages: () => installNpmPackages, + typingsName: () => typingsName + }); + var init_ts_server_typingsInstaller = __esm({ + "src/typingsInstallerCore/_namespaces/ts.server.typingsInstaller.ts"() { + "use strict"; + init_typingsInstaller(); + } + }); + + // src/typingsInstallerCore/_namespaces/ts.server.ts + var init_ts_server2 = __esm({ + "src/typingsInstallerCore/_namespaces/ts.server.ts"() { + "use strict"; + init_ts_server(); + init_ts_server_typingsInstaller(); + } + }); + + // src/server/types.ts + var init_types4 = __esm({ + "src/server/types.ts"() { + "use strict"; + } + }); + + // src/server/utilitiesPublic.ts + function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { + return { + projectName: project.getProjectName(), + fileNames: project.getFileNames( + /*excludeFilesFromExternalLibraries*/ + true, + /*excludeConfigFiles*/ + true + ).concat(project.getExcludedFiles()), + compilerOptions: project.getCompilationSettings(), + typeAcquisition, + unresolvedImports, + projectRootPath: project.getCurrentDirectory(), + cachePath, + kind: "discover" + }; + } + function toNormalizedPath(fileName) { + return normalizePath(fileName); + } + function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) { + const f = isRootedDiskPath(normalizedPath) ? normalizedPath : getNormalizedAbsolutePath(normalizedPath, currentDirectory); + return getCanonicalFileName(f); + } + function asNormalizedPath(fileName) { + return fileName; + } + function createNormalizedPathMap() { + const map2 = /* @__PURE__ */ new Map(); + return { + get(path) { + return map2.get(path); + }, + set(path, value) { + map2.set(path, value); + }, + contains(path) { + return map2.has(path); + }, + remove(path) { + map2.delete(path); + } + }; + } + function isInferredProjectName(name) { + return /dev\/null\/inferredProject\d+\*/.test(name); + } + function makeInferredProjectName(counter) { + return `/dev/null/inferredProject${counter}*`; + } + function makeAutoImportProviderProjectName(counter) { + return `/dev/null/autoImportProviderProject${counter}*`; + } + function makeAuxiliaryProjectName(counter) { + return `/dev/null/auxiliaryProject${counter}*`; + } + function createSortedArray2() { + return []; + } + var LogLevel2, emptyArray2, Msg, Errors; + var init_utilitiesPublic3 = __esm({ + "src/server/utilitiesPublic.ts"() { + "use strict"; + init_ts7(); + LogLevel2 = /* @__PURE__ */ ((LogLevel3) => { + LogLevel3[LogLevel3["terse"] = 0] = "terse"; + LogLevel3[LogLevel3["normal"] = 1] = "normal"; + LogLevel3[LogLevel3["requestTime"] = 2] = "requestTime"; + LogLevel3[LogLevel3["verbose"] = 3] = "verbose"; + return LogLevel3; + })(LogLevel2 || {}); + emptyArray2 = createSortedArray2(); + Msg = /* @__PURE__ */ ((Msg2) => { + Msg2["Err"] = "Err"; + Msg2["Info"] = "Info"; + Msg2["Perf"] = "Perf"; + return Msg2; + })(Msg || {}); + ((Errors2) => { + function ThrowNoProject() { + throw new Error("No Project."); + } + Errors2.ThrowNoProject = ThrowNoProject; + function ThrowProjectLanguageServiceDisabled() { + throw new Error("The project's language service is disabled."); + } + Errors2.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled; + function ThrowProjectDoesNotContainDocument(fileName, project) { + throw new Error(`Project '${project.getProjectName()}' does not contain document '${fileName}'`); + } + Errors2.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; + })(Errors || (Errors = {})); + } + }); + + // src/server/utilities.ts + function getBaseConfigFileName(configFilePath) { + const base = getBaseFileName(configFilePath); + return base === "tsconfig.json" || base === "jsconfig.json" ? base : void 0; + } + function removeSorted(array, remove, compare) { + if (!array || array.length === 0) { + return; + } + if (array[0] === remove) { + array.splice(0, 1); + return; + } + const removeIndex = binarySearch(array, remove, identity, compare); + if (removeIndex >= 0) { + array.splice(removeIndex, 1); + } + } + var ThrottledOperations, GcTimer; + var init_utilities5 = __esm({ + "src/server/utilities.ts"() { + "use strict"; + init_ts7(); + init_ts_server3(); + ThrottledOperations = class _ThrottledOperations { + constructor(host, logger) { + this.host = host; + this.pendingTimeouts = /* @__PURE__ */ new Map(); + this.logger = logger.hasLevel(3 /* verbose */) ? logger : void 0; + } + /** + * Wait `number` milliseconds and then invoke `cb`. If, while waiting, schedule + * is called again with the same `operationId`, cancel this operation in favor + * of the new one. (Note that the amount of time the canceled operation had been + * waiting does not affect the amount of time that the new operation waits.) + */ + schedule(operationId, delay, cb) { + const pendingTimeout = this.pendingTimeouts.get(operationId); + if (pendingTimeout) { + this.host.clearTimeout(pendingTimeout); + } + this.pendingTimeouts.set(operationId, this.host.setTimeout(_ThrottledOperations.run, delay, operationId, this, cb)); + if (this.logger) { + this.logger.info(`Scheduled: ${operationId}${pendingTimeout ? ", Cancelled earlier one" : ""}`); + } + } + cancel(operationId) { + const pendingTimeout = this.pendingTimeouts.get(operationId); + if (!pendingTimeout) + return false; + this.host.clearTimeout(pendingTimeout); + return this.pendingTimeouts.delete(operationId); + } + static run(operationId, self, cb) { + var _a, _b; + (_a = perfLogger) == null ? void 0 : _a.logStartScheduledOperation(operationId); + self.pendingTimeouts.delete(operationId); + if (self.logger) { + self.logger.info(`Running: ${operationId}`); + } + cb(); + (_b = perfLogger) == null ? void 0 : _b.logStopScheduledOperation(); + } + }; + GcTimer = class _GcTimer { + constructor(host, delay, logger) { + this.host = host; + this.delay = delay; + this.logger = logger; + } + scheduleCollect() { + if (!this.host.gc || this.timerId !== void 0) { + return; + } + this.timerId = this.host.setTimeout(_GcTimer.run, this.delay, this); + } + static run(self) { + var _a, _b; + self.timerId = void 0; + (_a = perfLogger) == null ? void 0 : _a.logStartScheduledOperation("GC collect"); + const log = self.logger.hasLevel(2 /* requestTime */); + const before = log && self.host.getMemoryUsage(); + self.host.gc(); + if (log) { + const after = self.host.getMemoryUsage(); + self.logger.perftrc(`GC::before ${before}, after ${after}`); + } + (_b = perfLogger) == null ? void 0 : _b.logStopScheduledOperation(); + } + }; + } + }); + + // src/server/protocol.ts + var CommandTypes, OrganizeImportsMode2, WatchFileKind2, WatchDirectoryKind2, PollingWatchKind2, CompletionTriggerKind2, IndentStyle2, SemicolonPreference2, JsxEmit2, ModuleKind2, ModuleResolutionKind2, NewLineKind2, ScriptTarget10, ClassificationType2; + var init_protocol = __esm({ + "src/server/protocol.ts"() { + "use strict"; + CommandTypes = /* @__PURE__ */ ((CommandTypes2) => { + CommandTypes2["JsxClosingTag"] = "jsxClosingTag"; + CommandTypes2["LinkedEditingRange"] = "linkedEditingRange"; + CommandTypes2["Brace"] = "brace"; + CommandTypes2["BraceFull"] = "brace-full"; + CommandTypes2["BraceCompletion"] = "braceCompletion"; + CommandTypes2["GetSpanOfEnclosingComment"] = "getSpanOfEnclosingComment"; + CommandTypes2["Change"] = "change"; + CommandTypes2["Close"] = "close"; + CommandTypes2["Completions"] = "completions"; + CommandTypes2["CompletionInfo"] = "completionInfo"; + CommandTypes2["CompletionsFull"] = "completions-full"; + CommandTypes2["CompletionDetails"] = "completionEntryDetails"; + CommandTypes2["CompletionDetailsFull"] = "completionEntryDetails-full"; + CommandTypes2["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList"; + CommandTypes2["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile"; + CommandTypes2["Configure"] = "configure"; + CommandTypes2["Definition"] = "definition"; + CommandTypes2["DefinitionFull"] = "definition-full"; + CommandTypes2["DefinitionAndBoundSpan"] = "definitionAndBoundSpan"; + CommandTypes2["DefinitionAndBoundSpanFull"] = "definitionAndBoundSpan-full"; + CommandTypes2["Implementation"] = "implementation"; + CommandTypes2["ImplementationFull"] = "implementation-full"; + CommandTypes2["EmitOutput"] = "emit-output"; + CommandTypes2["Exit"] = "exit"; + CommandTypes2["FileReferences"] = "fileReferences"; + CommandTypes2["FileReferencesFull"] = "fileReferences-full"; + CommandTypes2["Format"] = "format"; + CommandTypes2["Formatonkey"] = "formatonkey"; + CommandTypes2["FormatFull"] = "format-full"; + CommandTypes2["FormatonkeyFull"] = "formatonkey-full"; + CommandTypes2["FormatRangeFull"] = "formatRange-full"; + CommandTypes2["Geterr"] = "geterr"; + CommandTypes2["GeterrForProject"] = "geterrForProject"; + CommandTypes2["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync"; + CommandTypes2["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync"; + CommandTypes2["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync"; + CommandTypes2["NavBar"] = "navbar"; + CommandTypes2["NavBarFull"] = "navbar-full"; + CommandTypes2["Navto"] = "navto"; + CommandTypes2["NavtoFull"] = "navto-full"; + CommandTypes2["NavTree"] = "navtree"; + CommandTypes2["NavTreeFull"] = "navtree-full"; + CommandTypes2["DocumentHighlights"] = "documentHighlights"; + CommandTypes2["DocumentHighlightsFull"] = "documentHighlights-full"; + CommandTypes2["Open"] = "open"; + CommandTypes2["Quickinfo"] = "quickinfo"; + CommandTypes2["QuickinfoFull"] = "quickinfo-full"; + CommandTypes2["References"] = "references"; + CommandTypes2["ReferencesFull"] = "references-full"; + CommandTypes2["Reload"] = "reload"; + CommandTypes2["Rename"] = "rename"; + CommandTypes2["RenameInfoFull"] = "rename-full"; + CommandTypes2["RenameLocationsFull"] = "renameLocations-full"; + CommandTypes2["Saveto"] = "saveto"; + CommandTypes2["SignatureHelp"] = "signatureHelp"; + CommandTypes2["SignatureHelpFull"] = "signatureHelp-full"; + CommandTypes2["FindSourceDefinition"] = "findSourceDefinition"; + CommandTypes2["Status"] = "status"; + CommandTypes2["TypeDefinition"] = "typeDefinition"; + CommandTypes2["ProjectInfo"] = "projectInfo"; + CommandTypes2["ReloadProjects"] = "reloadProjects"; + CommandTypes2["Unknown"] = "unknown"; + CommandTypes2["OpenExternalProject"] = "openExternalProject"; + CommandTypes2["OpenExternalProjects"] = "openExternalProjects"; + CommandTypes2["CloseExternalProject"] = "closeExternalProject"; + CommandTypes2["SynchronizeProjectList"] = "synchronizeProjectList"; + CommandTypes2["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles"; + CommandTypes2["UpdateOpen"] = "updateOpen"; + CommandTypes2["EncodedSyntacticClassificationsFull"] = "encodedSyntacticClassifications-full"; + CommandTypes2["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full"; + CommandTypes2["Cleanup"] = "cleanup"; + CommandTypes2["GetOutliningSpans"] = "getOutliningSpans"; + CommandTypes2["GetOutliningSpansFull"] = "outliningSpans"; + CommandTypes2["TodoComments"] = "todoComments"; + CommandTypes2["Indentation"] = "indentation"; + CommandTypes2["DocCommentTemplate"] = "docCommentTemplate"; + CommandTypes2["CompilerOptionsDiagnosticsFull"] = "compilerOptionsDiagnostics-full"; + CommandTypes2["NameOrDottedNameSpan"] = "nameOrDottedNameSpan"; + CommandTypes2["BreakpointStatement"] = "breakpointStatement"; + CommandTypes2["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects"; + CommandTypes2["GetCodeFixes"] = "getCodeFixes"; + CommandTypes2["GetCodeFixesFull"] = "getCodeFixes-full"; + CommandTypes2["GetCombinedCodeFix"] = "getCombinedCodeFix"; + CommandTypes2["GetCombinedCodeFixFull"] = "getCombinedCodeFix-full"; + CommandTypes2["ApplyCodeActionCommand"] = "applyCodeActionCommand"; + CommandTypes2["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; + CommandTypes2["GetApplicableRefactors"] = "getApplicableRefactors"; + CommandTypes2["GetEditsForRefactor"] = "getEditsForRefactor"; + CommandTypes2["GetMoveToRefactoringFileSuggestions"] = "getMoveToRefactoringFileSuggestions"; + CommandTypes2["GetEditsForRefactorFull"] = "getEditsForRefactor-full"; + CommandTypes2["OrganizeImports"] = "organizeImports"; + CommandTypes2["OrganizeImportsFull"] = "organizeImports-full"; + CommandTypes2["GetEditsForFileRename"] = "getEditsForFileRename"; + CommandTypes2["GetEditsForFileRenameFull"] = "getEditsForFileRename-full"; + CommandTypes2["ConfigurePlugin"] = "configurePlugin"; + CommandTypes2["SelectionRange"] = "selectionRange"; + CommandTypes2["SelectionRangeFull"] = "selectionRange-full"; + CommandTypes2["ToggleLineComment"] = "toggleLineComment"; + CommandTypes2["ToggleLineCommentFull"] = "toggleLineComment-full"; + CommandTypes2["ToggleMultilineComment"] = "toggleMultilineComment"; + CommandTypes2["ToggleMultilineCommentFull"] = "toggleMultilineComment-full"; + CommandTypes2["CommentSelection"] = "commentSelection"; + CommandTypes2["CommentSelectionFull"] = "commentSelection-full"; + CommandTypes2["UncommentSelection"] = "uncommentSelection"; + CommandTypes2["UncommentSelectionFull"] = "uncommentSelection-full"; + CommandTypes2["PrepareCallHierarchy"] = "prepareCallHierarchy"; + CommandTypes2["ProvideCallHierarchyIncomingCalls"] = "provideCallHierarchyIncomingCalls"; + CommandTypes2["ProvideCallHierarchyOutgoingCalls"] = "provideCallHierarchyOutgoingCalls"; + CommandTypes2["ProvideInlayHints"] = "provideInlayHints"; + CommandTypes2["WatchChange"] = "watchChange"; + return CommandTypes2; + })(CommandTypes || {}); + OrganizeImportsMode2 = /* @__PURE__ */ ((OrganizeImportsMode3) => { + OrganizeImportsMode3["All"] = "All"; + OrganizeImportsMode3["SortAndCombine"] = "SortAndCombine"; + OrganizeImportsMode3["RemoveUnused"] = "RemoveUnused"; + return OrganizeImportsMode3; + })(OrganizeImportsMode2 || {}); + WatchFileKind2 = /* @__PURE__ */ ((WatchFileKind3) => { + WatchFileKind3["FixedPollingInterval"] = "FixedPollingInterval"; + WatchFileKind3["PriorityPollingInterval"] = "PriorityPollingInterval"; + WatchFileKind3["DynamicPriorityPolling"] = "DynamicPriorityPolling"; + WatchFileKind3["FixedChunkSizePolling"] = "FixedChunkSizePolling"; + WatchFileKind3["UseFsEvents"] = "UseFsEvents"; + WatchFileKind3["UseFsEventsOnParentDirectory"] = "UseFsEventsOnParentDirectory"; + return WatchFileKind3; + })(WatchFileKind2 || {}); + WatchDirectoryKind2 = /* @__PURE__ */ ((WatchDirectoryKind3) => { + WatchDirectoryKind3["UseFsEvents"] = "UseFsEvents"; + WatchDirectoryKind3["FixedPollingInterval"] = "FixedPollingInterval"; + WatchDirectoryKind3["DynamicPriorityPolling"] = "DynamicPriorityPolling"; + WatchDirectoryKind3["FixedChunkSizePolling"] = "FixedChunkSizePolling"; + return WatchDirectoryKind3; + })(WatchDirectoryKind2 || {}); + PollingWatchKind2 = /* @__PURE__ */ ((PollingWatchKind3) => { + PollingWatchKind3["FixedInterval"] = "FixedInterval"; + PollingWatchKind3["PriorityInterval"] = "PriorityInterval"; + PollingWatchKind3["DynamicPriority"] = "DynamicPriority"; + PollingWatchKind3["FixedChunkSize"] = "FixedChunkSize"; + return PollingWatchKind3; + })(PollingWatchKind2 || {}); + CompletionTriggerKind2 = /* @__PURE__ */ ((CompletionTriggerKind4) => { + CompletionTriggerKind4[CompletionTriggerKind4["Invoked"] = 1] = "Invoked"; + CompletionTriggerKind4[CompletionTriggerKind4["TriggerCharacter"] = 2] = "TriggerCharacter"; + CompletionTriggerKind4[CompletionTriggerKind4["TriggerForIncompleteCompletions"] = 3] = "TriggerForIncompleteCompletions"; + return CompletionTriggerKind4; + })(CompletionTriggerKind2 || {}); + IndentStyle2 = /* @__PURE__ */ ((IndentStyle3) => { + IndentStyle3["None"] = "None"; + IndentStyle3["Block"] = "Block"; + IndentStyle3["Smart"] = "Smart"; + return IndentStyle3; + })(IndentStyle2 || {}); + SemicolonPreference2 = /* @__PURE__ */ ((SemicolonPreference3) => { + SemicolonPreference3["Ignore"] = "ignore"; + SemicolonPreference3["Insert"] = "insert"; + SemicolonPreference3["Remove"] = "remove"; + return SemicolonPreference3; + })(SemicolonPreference2 || {}); + JsxEmit2 = /* @__PURE__ */ ((JsxEmit3) => { + JsxEmit3["None"] = "None"; + JsxEmit3["Preserve"] = "Preserve"; + JsxEmit3["ReactNative"] = "ReactNative"; + JsxEmit3["React"] = "React"; + return JsxEmit3; + })(JsxEmit2 || {}); + ModuleKind2 = /* @__PURE__ */ ((ModuleKind3) => { + ModuleKind3["None"] = "None"; + ModuleKind3["CommonJS"] = "CommonJS"; + ModuleKind3["AMD"] = "AMD"; + ModuleKind3["UMD"] = "UMD"; + ModuleKind3["System"] = "System"; + ModuleKind3["ES6"] = "ES6"; + ModuleKind3["ES2015"] = "ES2015"; + ModuleKind3["ESNext"] = "ESNext"; + return ModuleKind3; + })(ModuleKind2 || {}); + ModuleResolutionKind2 = /* @__PURE__ */ ((ModuleResolutionKind3) => { + ModuleResolutionKind3["Classic"] = "Classic"; + ModuleResolutionKind3["Node"] = "Node"; + return ModuleResolutionKind3; + })(ModuleResolutionKind2 || {}); + NewLineKind2 = /* @__PURE__ */ ((NewLineKind3) => { + NewLineKind3["Crlf"] = "Crlf"; + NewLineKind3["Lf"] = "Lf"; + return NewLineKind3; + })(NewLineKind2 || {}); + ScriptTarget10 = /* @__PURE__ */ ((ScriptTarget11) => { + ScriptTarget11["ES3"] = "ES3"; + ScriptTarget11["ES5"] = "ES5"; + ScriptTarget11["ES6"] = "ES6"; + ScriptTarget11["ES2015"] = "ES2015"; + ScriptTarget11["ES2016"] = "ES2016"; + ScriptTarget11["ES2017"] = "ES2017"; + ScriptTarget11["ES2018"] = "ES2018"; + ScriptTarget11["ES2019"] = "ES2019"; + ScriptTarget11["ES2020"] = "ES2020"; + ScriptTarget11["ES2021"] = "ES2021"; + ScriptTarget11["ES2022"] = "ES2022"; + ScriptTarget11["ESNext"] = "ESNext"; + return ScriptTarget11; + })(ScriptTarget10 || {}); + ClassificationType2 = /* @__PURE__ */ ((ClassificationType3) => { + ClassificationType3[ClassificationType3["comment"] = 1] = "comment"; + ClassificationType3[ClassificationType3["identifier"] = 2] = "identifier"; + ClassificationType3[ClassificationType3["keyword"] = 3] = "keyword"; + ClassificationType3[ClassificationType3["numericLiteral"] = 4] = "numericLiteral"; + ClassificationType3[ClassificationType3["operator"] = 5] = "operator"; + ClassificationType3[ClassificationType3["stringLiteral"] = 6] = "stringLiteral"; + ClassificationType3[ClassificationType3["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; + ClassificationType3[ClassificationType3["whiteSpace"] = 8] = "whiteSpace"; + ClassificationType3[ClassificationType3["text"] = 9] = "text"; + ClassificationType3[ClassificationType3["punctuation"] = 10] = "punctuation"; + ClassificationType3[ClassificationType3["className"] = 11] = "className"; + ClassificationType3[ClassificationType3["enumName"] = 12] = "enumName"; + ClassificationType3[ClassificationType3["interfaceName"] = 13] = "interfaceName"; + ClassificationType3[ClassificationType3["moduleName"] = 14] = "moduleName"; + ClassificationType3[ClassificationType3["typeParameterName"] = 15] = "typeParameterName"; + ClassificationType3[ClassificationType3["typeAliasName"] = 16] = "typeAliasName"; + ClassificationType3[ClassificationType3["parameterName"] = 17] = "parameterName"; + ClassificationType3[ClassificationType3["docCommentTagName"] = 18] = "docCommentTagName"; + ClassificationType3[ClassificationType3["jsxOpenTagName"] = 19] = "jsxOpenTagName"; + ClassificationType3[ClassificationType3["jsxCloseTagName"] = 20] = "jsxCloseTagName"; + ClassificationType3[ClassificationType3["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; + ClassificationType3[ClassificationType3["jsxAttribute"] = 22] = "jsxAttribute"; + ClassificationType3[ClassificationType3["jsxText"] = 23] = "jsxText"; + ClassificationType3[ClassificationType3["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + ClassificationType3[ClassificationType3["bigintLiteral"] = 25] = "bigintLiteral"; + return ClassificationType3; + })(ClassificationType2 || {}); + } + }); + + // src/server/_namespaces/ts.server.protocol.ts + var ts_server_protocol_exports = {}; + __export(ts_server_protocol_exports, { + ClassificationType: () => ClassificationType2, + CommandTypes: () => CommandTypes, + CompletionTriggerKind: () => CompletionTriggerKind2, + IndentStyle: () => IndentStyle2, + JsxEmit: () => JsxEmit2, + ModuleKind: () => ModuleKind2, + ModuleResolutionKind: () => ModuleResolutionKind2, + NewLineKind: () => NewLineKind2, + OrganizeImportsMode: () => OrganizeImportsMode2, + PollingWatchKind: () => PollingWatchKind2, + ScriptTarget: () => ScriptTarget10, + SemicolonPreference: () => SemicolonPreference2, + WatchDirectoryKind: () => WatchDirectoryKind2, + WatchFileKind: () => WatchFileKind2 + }); + var init_ts_server_protocol = __esm({ + "src/server/_namespaces/ts.server.protocol.ts"() { + "use strict"; + init_protocol(); + } + }); + + // src/server/scriptInfo.ts + function isDynamicFileName(fileName) { + return fileName[0] === "^" || (fileName.includes("walkThroughSnippet:/") || fileName.includes("untitled:/")) && getBaseFileName(fileName)[0] === "^" || fileName.includes(":^") && !fileName.includes(directorySeparator); + } + function ensurePrimaryProjectKind(project) { + if (!project || isBackgroundProject(project)) { + return Errors.ThrowNoProject(); + } + return project; + } + function failIfInvalidPosition(position) { + Debug.assert(typeof position === "number", `Expected position ${position} to be a number.`); + Debug.assert(position >= 0, `Expected position to be non-negative.`); + } + function failIfInvalidLocation(location) { + Debug.assert(typeof location.line === "number", `Expected line ${location.line} to be a number.`); + Debug.assert(typeof location.offset === "number", `Expected offset ${location.offset} to be a number.`); + Debug.assert(location.line > 0, `Expected line to be non-${location.line === 0 ? "zero" : "negative"}`); + Debug.assert(location.offset > 0, `Expected offset to be non-${location.offset === 0 ? "zero" : "negative"}`); + } + var TextStorage, ScriptInfo; + var init_scriptInfo = __esm({ + "src/server/scriptInfo.ts"() { + "use strict"; + init_ts7(); + init_ts_server3(); + TextStorage = class { + constructor(host, info, initialVersion) { + this.host = host; + this.info = info; + /** + * True if the text is for the file thats open in the editor + */ + this.isOpen = false; + /** + * True if the text present is the text from the file on the disk + */ + this.ownFileText = false; + /** + * True when reloading contents of file from the disk is pending + */ + this.pendingReloadFromDisk = false; + this.version = initialVersion || 0; + } + getVersion() { + return this.svc ? `SVC-${this.version}-${this.svc.getSnapshotVersion()}` : `Text-${this.version}`; + } + hasScriptVersionCache_TestOnly() { + return this.svc !== void 0; + } + resetSourceMapInfo() { + this.info.sourceFileLike = void 0; + this.info.closeSourceMapFileWatcher(); + this.info.sourceMapFilePath = void 0; + this.info.declarationInfoPath = void 0; + this.info.sourceInfos = void 0; + this.info.documentPositionMapper = void 0; + } + /** Public for testing */ + useText(newText) { + this.svc = void 0; + this.text = newText; + this.textSnapshot = void 0; + this.lineMap = void 0; + this.fileSize = void 0; + this.resetSourceMapInfo(); + this.version++; + } + edit(start, end, newText) { + this.switchToScriptVersionCache().edit(start, end - start, newText); + this.ownFileText = false; + this.text = void 0; + this.textSnapshot = void 0; + this.lineMap = void 0; + this.fileSize = void 0; + this.resetSourceMapInfo(); + } + /** + * Set the contents as newText + * returns true if text changed + */ + reload(newText) { + Debug.assert(newText !== void 0); + this.pendingReloadFromDisk = false; + if (!this.text && this.svc) { + this.text = getSnapshotText(this.svc.getSnapshot()); + } + if (this.text !== newText) { + this.useText(newText); + this.ownFileText = false; + return true; + } + return false; + } + /** + * Reads the contents from tempFile(if supplied) or own file and sets it as contents + * returns true if text changed + */ + reloadWithFileText(tempFileName) { + const { text: newText, fileSize } = tempFileName || !this.info.isDynamicOrHasMixedContent() ? this.getFileTextAndSize(tempFileName) : { text: "", fileSize: void 0 }; + const reloaded = this.reload(newText); + this.fileSize = fileSize; + this.ownFileText = !tempFileName || tempFileName === this.info.fileName; + return reloaded; + } + /** + * Schedule reload from the disk if its not already scheduled and its not own text + * returns true when scheduling reload + */ + scheduleReloadIfNeeded() { + return !this.pendingReloadFromDisk && !this.ownFileText ? this.pendingReloadFromDisk = true : false; + } + delayReloadFromFileIntoText() { + this.pendingReloadFromDisk = true; + } + /** + * For telemetry purposes, we would like to be able to report the size of the file. + * However, we do not want telemetry to require extra file I/O so we report a size + * that may be stale (e.g. may not reflect change made on disk since the last reload). + * NB: Will read from disk if the file contents have never been loaded because + * telemetry falsely indicating size 0 would be counter-productive. + */ + getTelemetryFileSize() { + return !!this.fileSize ? this.fileSize : !!this.text ? this.text.length : !!this.svc ? this.svc.getSnapshot().getLength() : this.getSnapshot().getLength(); + } + getSnapshot() { + var _a; + return ((_a = this.tryUseScriptVersionCache()) == null ? void 0 : _a.getSnapshot()) || (this.textSnapshot ?? (this.textSnapshot = ScriptSnapshot.fromString(Debug.checkDefined(this.text)))); + } + getAbsolutePositionAndLineText(oneBasedLine) { + const svc = this.tryUseScriptVersionCache(); + if (svc) + return svc.getAbsolutePositionAndLineText(oneBasedLine); + const lineMap = this.getLineMap(); + return oneBasedLine <= lineMap.length ? { + absolutePosition: lineMap[oneBasedLine - 1], + lineText: this.text.substring(lineMap[oneBasedLine - 1], lineMap[oneBasedLine]) + } : { + absolutePosition: this.text.length, + lineText: void 0 + }; + } + /** + * @param line 0 based index + */ + lineToTextSpan(line) { + const svc = this.tryUseScriptVersionCache(); + if (svc) + return svc.lineToTextSpan(line); + const lineMap = this.getLineMap(); + const start = lineMap[line]; + const end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; + return createTextSpanFromBounds(start, end); + } + /** + * @param line 1 based index + * @param offset 1 based index + */ + lineOffsetToPosition(line, offset, allowEdits) { + const svc = this.tryUseScriptVersionCache(); + return svc ? svc.lineOffsetToPosition(line, offset) : computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text, allowEdits); + } + positionToLineOffset(position) { + const svc = this.tryUseScriptVersionCache(); + if (svc) + return svc.positionToLineOffset(position); + const { line, character } = computeLineAndCharacterOfPosition(this.getLineMap(), position); + return { line: line + 1, offset: character + 1 }; + } + getFileTextAndSize(tempFileName) { + let text; + const fileName = tempFileName || this.info.fileName; + const getText = () => text === void 0 ? text = this.host.readFile(fileName) || "" : text; + if (!hasTSFileExtension(this.info.fileName)) { + const fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; + if (fileSize > maxFileSize) { + Debug.assert(!!this.info.containingProjects.length); + const service = this.info.containingProjects[0].projectService; + service.logger.info(`Skipped loading contents of large file ${fileName} for info ${this.info.fileName}: fileSize: ${fileSize}`); + this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize); + return { text: "", fileSize }; + } + } + return { text: getText() }; + } + /** @internal */ + switchToScriptVersionCache() { + if (!this.svc || this.pendingReloadFromDisk) { + this.svc = ScriptVersionCache.fromString(this.getOrLoadText()); + this.textSnapshot = void 0; + this.version++; + } + return this.svc; + } + tryUseScriptVersionCache() { + if (!this.svc || this.pendingReloadFromDisk) { + this.getOrLoadText(); + } + if (this.isOpen) { + if (!this.svc && !this.textSnapshot) { + this.svc = ScriptVersionCache.fromString(Debug.checkDefined(this.text)); + this.textSnapshot = void 0; + } + return this.svc; + } + return this.svc; + } + getOrLoadText() { + if (this.text === void 0 || this.pendingReloadFromDisk) { + Debug.assert(!this.svc || this.pendingReloadFromDisk, "ScriptVersionCache should not be set when reloading from disk"); + this.reloadWithFileText(); + } + return this.text; + } + getLineMap() { + Debug.assert(!this.svc, "ScriptVersionCache should not be set"); + return this.lineMap || (this.lineMap = computeLineStarts(Debug.checkDefined(this.text))); + } + getLineInfo() { + const svc = this.tryUseScriptVersionCache(); + if (svc) { + return { + getLineCount: () => svc.getLineCount(), + getLineText: (line) => svc.getAbsolutePositionAndLineText(line + 1).lineText + }; + } + const lineMap = this.getLineMap(); + return getLineInfo(this.text, lineMap); + } + }; + ScriptInfo = class { + constructor(host, fileName, scriptKind, hasMixedContent, path, initialVersion) { + this.host = host; + this.fileName = fileName; + this.scriptKind = scriptKind; + this.hasMixedContent = hasMixedContent; + this.path = path; + /** + * All projects that include this file + */ + this.containingProjects = []; + this.isDynamic = isDynamicFileName(fileName); + this.textStorage = new TextStorage(host, this, initialVersion); + if (hasMixedContent || this.isDynamic) { + this.realpath = this.path; + } + this.scriptKind = scriptKind ? scriptKind : getScriptKindFromFileName(fileName); + } + /** @internal */ + isDynamicOrHasMixedContent() { + return this.hasMixedContent || this.isDynamic; + } + isScriptOpen() { + return this.textStorage.isOpen; + } + open(newText) { + this.textStorage.isOpen = true; + if (newText !== void 0 && this.textStorage.reload(newText)) { + this.markContainingProjectsAsDirty(); + } + } + close(fileExists = true) { + this.textStorage.isOpen = false; + if (fileExists && this.textStorage.scheduleReloadIfNeeded()) { + this.markContainingProjectsAsDirty(); + } + } + getSnapshot() { + return this.textStorage.getSnapshot(); + } + ensureRealPath() { + if (this.realpath === void 0) { + this.realpath = this.path; + if (this.host.realpath) { + Debug.assert(!!this.containingProjects.length); + const project = this.containingProjects[0]; + const realpath = this.host.realpath(this.path); + if (realpath) { + this.realpath = project.toPath(realpath); + if (this.realpath !== this.path) { + project.projectService.realpathToScriptInfos.add(this.realpath, this); + } + } + } + } + } + /** @internal */ + getRealpathIfDifferent() { + return this.realpath && this.realpath !== this.path ? this.realpath : void 0; + } + /** + * @internal + * Does not compute realpath; uses precomputed result. Use `ensureRealPath` + * first if a definite result is needed. + */ + isSymlink() { + return this.realpath && this.realpath !== this.path; + } + getFormatCodeSettings() { + return this.formatSettings; + } + getPreferences() { + return this.preferences; + } + attachToProject(project) { + const isNew = !this.isAttached(project); + if (isNew) { + this.containingProjects.push(project); + if (!project.getCompilerOptions().preserveSymlinks) { + this.ensureRealPath(); + } + project.onFileAddedOrRemoved(this.isSymlink()); + } + return isNew; + } + isAttached(project) { + switch (this.containingProjects.length) { + case 0: + return false; + case 1: + return this.containingProjects[0] === project; + case 2: + return this.containingProjects[0] === project || this.containingProjects[1] === project; + default: + return contains(this.containingProjects, project); + } + } + detachFromProject(project) { + switch (this.containingProjects.length) { + case 0: + return; + case 1: + if (this.containingProjects[0] === project) { + project.onFileAddedOrRemoved(this.isSymlink()); + this.containingProjects.pop(); + } + break; + case 2: + if (this.containingProjects[0] === project) { + project.onFileAddedOrRemoved(this.isSymlink()); + this.containingProjects[0] = this.containingProjects.pop(); + } else if (this.containingProjects[1] === project) { + project.onFileAddedOrRemoved(this.isSymlink()); + this.containingProjects.pop(); + } + break; + default: + if (unorderedRemoveItem(this.containingProjects, project)) { + project.onFileAddedOrRemoved(this.isSymlink()); + } + break; + } + } + detachAllProjects() { + for (const p of this.containingProjects) { + if (isConfiguredProject(p)) { + p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, 2 /* Deleted */); + } + const existingRoot = p.getRootFilesMap().get(this.path); + p.removeFile( + this, + /*fileExists*/ + false, + /*detachFromProject*/ + false + ); + p.onFileAddedOrRemoved(this.isSymlink()); + if (existingRoot && !isInferredProject(p)) { + p.addMissingFileRoot(existingRoot.fileName); + } + } + clear(this.containingProjects); + } + getDefaultProject() { + switch (this.containingProjects.length) { + case 0: + return Errors.ThrowNoProject(); + case 1: + return ensurePrimaryProjectKind(this.containingProjects[0]); + default: + let firstExternalProject; + let firstConfiguredProject; + let firstInferredProject; + let firstNonSourceOfProjectReferenceRedirect; + let defaultConfiguredProject; + for (let index = 0; index < this.containingProjects.length; index++) { + const project = this.containingProjects[index]; + if (isConfiguredProject(project)) { + if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) { + if (defaultConfiguredProject === void 0 && index !== this.containingProjects.length - 1) { + defaultConfiguredProject = project.projectService.findDefaultConfiguredProject(this) || false; + } + if (defaultConfiguredProject === project) + return project; + if (!firstNonSourceOfProjectReferenceRedirect) + firstNonSourceOfProjectReferenceRedirect = project; + } + if (!firstConfiguredProject) + firstConfiguredProject = project; + } else if (!firstExternalProject && isExternalProject(project)) { + firstExternalProject = project; + } else if (!firstInferredProject && isInferredProject(project)) { + firstInferredProject = project; + } + } + return ensurePrimaryProjectKind( + defaultConfiguredProject || firstNonSourceOfProjectReferenceRedirect || firstConfiguredProject || firstExternalProject || firstInferredProject + ); + } + } + registerFileUpdate() { + for (const p of this.containingProjects) { + p.registerFileUpdate(this.path); + } + } + setOptions(formatSettings, preferences) { + if (formatSettings) { + if (!this.formatSettings) { + this.formatSettings = getDefaultFormatCodeSettings(this.host.newLine); + assign(this.formatSettings, formatSettings); + } else { + this.formatSettings = { ...this.formatSettings, ...formatSettings }; + } + } + if (preferences) { + if (!this.preferences) { + this.preferences = emptyOptions; + } + this.preferences = { ...this.preferences, ...preferences }; + } + } + getLatestVersion() { + this.textStorage.getSnapshot(); + return this.textStorage.getVersion(); + } + saveTo(fileName) { + this.host.writeFile(fileName, getSnapshotText(this.textStorage.getSnapshot())); + } + /** @internal */ + delayReloadNonMixedContentFile() { + Debug.assert(!this.isDynamicOrHasMixedContent()); + this.textStorage.delayReloadFromFileIntoText(); + this.markContainingProjectsAsDirty(); + } + reloadFromFile(tempFileName) { + if (this.textStorage.reloadWithFileText(tempFileName)) { + this.markContainingProjectsAsDirty(); + return true; + } + return false; + } + editContent(start, end, newText) { + this.textStorage.edit(start, end, newText); + this.markContainingProjectsAsDirty(); + } + markContainingProjectsAsDirty() { + for (const p of this.containingProjects) { + p.markFileAsDirty(this.path); + } + } + isOrphan() { + return !forEach(this.containingProjects, (p) => !p.isOrphan()); + } + /** @internal */ + isContainedByBackgroundProject() { + return some( + this.containingProjects, + isBackgroundProject + ); + } + /** + * @param line 1 based index + */ + lineToTextSpan(line) { + return this.textStorage.lineToTextSpan(line); + } + // eslint-disable-line @typescript-eslint/unified-signatures + lineOffsetToPosition(line, offset, allowEdits) { + return this.textStorage.lineOffsetToPosition(line, offset, allowEdits); + } + positionToLineOffset(position) { + failIfInvalidPosition(position); + const location = this.textStorage.positionToLineOffset(position); + failIfInvalidLocation(location); + return location; + } + isJavaScript() { + return this.scriptKind === 1 /* JS */ || this.scriptKind === 2 /* JSX */; + } + /** @internal */ + closeSourceMapFileWatcher() { + if (this.sourceMapFilePath && !isString(this.sourceMapFilePath)) { + closeFileWatcherOf(this.sourceMapFilePath); + this.sourceMapFilePath = void 0; + } + } + }; + } + }); + + // src/server/typingsCache.ts + function setIsEqualTo(arr1, arr2) { + if (arr1 === arr2) { + return true; + } + if ((arr1 || emptyArray2).length === 0 && (arr2 || emptyArray2).length === 0) { + return true; + } + const set = /* @__PURE__ */ new Map(); + let unique = 0; + for (const v of arr1) { + if (set.get(v) !== true) { + set.set(v, true); + unique++; + } + } + for (const v of arr2) { + const isSet = set.get(v); + if (isSet === void 0) { + return false; + } + if (isSet === true) { + set.set(v, false); + unique--; + } + } + return unique === 0; + } + function typeAcquisitionChanged(opt1, opt2) { + return opt1.enable !== opt2.enable || !setIsEqualTo(opt1.include, opt2.include) || !setIsEqualTo(opt1.exclude, opt2.exclude); + } + function compilerOptionsChanged(opt1, opt2) { + return getAllowJSCompilerOption(opt1) !== getAllowJSCompilerOption(opt2); + } + function unresolvedImportsChanged(imports1, imports2) { + if (imports1 === imports2) { + return false; + } + return !arrayIsEqualTo(imports1, imports2); + } + var nullTypingsInstaller, TypingsCache; + var init_typingsCache = __esm({ + "src/server/typingsCache.ts"() { + "use strict"; + init_ts7(); + init_ts_server3(); + nullTypingsInstaller = { + isKnownTypesPackageName: returnFalse, + // Should never be called because we never provide a types registry. + installPackage: notImplemented, + enqueueInstallTypingsRequest: noop, + attach: noop, + onProjectClosed: noop, + globalTypingsCacheLocation: void 0 + // TODO: GH#18217 + }; + TypingsCache = class { + constructor(installer) { + this.installer = installer; + this.perProjectCache = /* @__PURE__ */ new Map(); + } + isKnownTypesPackageName(name) { + return this.installer.isKnownTypesPackageName(name); + } + installPackage(options) { + return this.installer.installPackage(options); + } + enqueueInstallTypingsForProject(project, unresolvedImports, forceRefresh) { + const typeAcquisition = project.getTypeAcquisition(); + if (!typeAcquisition || !typeAcquisition.enable) { + return; + } + const entry = this.perProjectCache.get(project.getProjectName()); + if (forceRefresh || !entry || typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || compilerOptionsChanged(project.getCompilationSettings(), entry.compilerOptions) || unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) { + this.perProjectCache.set(project.getProjectName(), { + compilerOptions: project.getCompilationSettings(), + typeAcquisition, + typings: entry ? entry.typings : emptyArray2, + unresolvedImports, + poisoned: true + }); + this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); + } + } + updateTypingsForProject(projectName, compilerOptions, typeAcquisition, unresolvedImports, newTypings) { + const typings = sort(newTypings); + this.perProjectCache.set(projectName, { + compilerOptions, + typeAcquisition, + typings, + unresolvedImports, + poisoned: false + }); + return !typeAcquisition || !typeAcquisition.enable ? emptyArray2 : typings; + } + onProjectClosed(project) { + this.perProjectCache.delete(project.getProjectName()); + this.installer.onProjectClosed(project); + } + }; + } + }); + + // src/server/project.ts + function countEachFileTypes(infos, includeSizes = false) { + const result = { + js: 0, + jsSize: 0, + jsx: 0, + jsxSize: 0, + ts: 0, + tsSize: 0, + tsx: 0, + tsxSize: 0, + dts: 0, + dtsSize: 0, + deferred: 0, + deferredSize: 0 + }; + for (const info of infos) { + const fileSize = includeSizes ? info.textStorage.getTelemetryFileSize() : 0; + switch (info.scriptKind) { + case 1 /* JS */: + result.js += 1; + result.jsSize += fileSize; + break; + case 2 /* JSX */: + result.jsx += 1; + result.jsxSize += fileSize; + break; + case 3 /* TS */: + if (isDeclarationFileName(info.fileName)) { + result.dts += 1; + result.dtsSize += fileSize; + } else { + result.ts += 1; + result.tsSize += fileSize; + } + break; + case 4 /* TSX */: + result.tsx += 1; + result.tsxSize += fileSize; + break; + case 7 /* Deferred */: + result.deferred += 1; + result.deferredSize += fileSize; + break; + } + } + return result; + } + function hasOneOrMoreJsAndNoTsFiles(project) { + const counts2 = countEachFileTypes(project.getScriptInfos()); + return counts2.js > 0 && counts2.ts === 0 && counts2.tsx === 0; + } + function allRootFilesAreJsOrDts(project) { + const counts2 = countEachFileTypes(project.getRootScriptInfos()); + return counts2.ts === 0 && counts2.tsx === 0; + } + function allFilesAreJsOrDts(project) { + const counts2 = countEachFileTypes(project.getScriptInfos()); + return counts2.ts === 0 && counts2.tsx === 0; + } + function hasNoTypeScriptSource(fileNames) { + return !fileNames.some((fileName) => fileExtensionIs(fileName, ".ts" /* Ts */) && !isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".tsx" /* Tsx */)); + } + function isGeneratedFileWatcher(watch) { + return watch.generatedFilePath !== void 0; + } + function getUnresolvedImports(program, cachedUnresolvedImportsPerFile) { + var _a, _b; + const sourceFiles = program.getSourceFiles(); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "getUnresolvedImports", { count: sourceFiles.length }); + const ambientModules = program.getTypeChecker().getAmbientModules().map((mod) => stripQuotes(mod.getName())); + const result = sortAndDeduplicate(flatMap(sourceFiles, (sourceFile) => extractUnresolvedImportsFromSourceFile( + program, + sourceFile, + ambientModules, + cachedUnresolvedImportsPerFile + ))); + (_b = tracing) == null ? void 0 : _b.pop(); + return result; + } + function extractUnresolvedImportsFromSourceFile(program, file, ambientModules, cachedUnresolvedImportsPerFile) { + return getOrUpdate(cachedUnresolvedImportsPerFile, file.path, () => { + let unresolvedImports; + program.forEachResolvedModule(({ resolvedModule }, name) => { + if ((!resolvedModule || !resolutionExtensionIsTSOrJson(resolvedModule.extension)) && !isExternalModuleNameRelative(name) && !ambientModules.some((m) => m === name)) { + unresolvedImports = append(unresolvedImports, parsePackageName(name).packageName); + } + }, file); + return unresolvedImports || emptyArray2; + }); + } + function isInferredProject(project) { + return project.projectKind === 0 /* Inferred */; + } + function isConfiguredProject(project) { + return project.projectKind === 1 /* Configured */; + } + function isExternalProject(project) { + return project.projectKind === 2 /* External */; + } + function isBackgroundProject(project) { + return project.projectKind === 3 /* AutoImportProvider */ || project.projectKind === 4 /* Auxiliary */; + } + var ProjectKind, Project3, InferredProject2, AuxiliaryProject, _AutoImportProviderProject, AutoImportProviderProject, ConfiguredProject2, ExternalProject2; + var init_project = __esm({ + "src/server/project.ts"() { + "use strict"; + init_ts7(); + init_ts7(); + init_ts_server3(); + ProjectKind = /* @__PURE__ */ ((ProjectKind2) => { + ProjectKind2[ProjectKind2["Inferred"] = 0] = "Inferred"; + ProjectKind2[ProjectKind2["Configured"] = 1] = "Configured"; + ProjectKind2[ProjectKind2["External"] = 2] = "External"; + ProjectKind2[ProjectKind2["AutoImportProvider"] = 3] = "AutoImportProvider"; + ProjectKind2[ProjectKind2["Auxiliary"] = 4] = "Auxiliary"; + return ProjectKind2; + })(ProjectKind || {}); + Project3 = class _Project { + /** @internal */ + constructor(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, watchOptions, directoryStructureHost, currentDirectory) { + this.projectKind = projectKind; + this.projectService = projectService; + this.documentRegistry = documentRegistry; + this.compilerOptions = compilerOptions; + this.compileOnSaveEnabled = compileOnSaveEnabled; + this.watchOptions = watchOptions; + this.rootFiles = []; + this.rootFilesMap = /* @__PURE__ */ new Map(); + /** @internal */ + this.plugins = []; + /** + * This is map from files to unresolved imports in it + * Maop does not contain entries for files that do not have unresolved imports + * This helps in containing the set of files to invalidate + * + * @internal + */ + this.cachedUnresolvedImportsPerFile = /* @__PURE__ */ new Map(); + /** @internal */ + this.hasAddedorRemovedFiles = false; + /** @internal */ + this.hasAddedOrRemovedSymlinks = false; + /** + * Last version that was reported. + */ + this.lastReportedVersion = 0; + /** + * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one) + * This property is changed in 'updateGraph' based on the set of files in program + */ + this.projectProgramVersion = 0; + /** + * Current version of the project state. It is changed when: + * - new root file was added/removed + * - edit happen in some file that is currently included in the project. + * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project + */ + this.projectStateVersion = 0; + this.isInitialLoadPending = returnFalse; + /** @internal */ + this.dirty = false; + /** @internal */ + this.typingFiles = emptyArray2; + /** @internal */ + this.moduleSpecifierCache = createModuleSpecifierCache(this); + /** @internal */ + this.createHash = maybeBind(this.projectService.host, this.projectService.host.createHash); + /** @internal */ + this.globalCacheResolutionModuleName = ts_JsTyping_exports.nonRelativeModuleNameForTypingCache; + this.projectName = projectName; + this.directoryStructureHost = directoryStructureHost; + this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory); + this.getCanonicalFileName = this.projectService.toCanonicalFileName; + this.jsDocParsingMode = this.projectService.jsDocParsingMode; + this.cancellationToken = new ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); + if (!this.compilerOptions) { + this.compilerOptions = getDefaultCompilerOptions2(); + this.compilerOptions.allowNonTsExtensions = true; + this.compilerOptions.allowJs = true; + } else if (hasExplicitListOfFiles || getAllowJSCompilerOption(this.compilerOptions) || this.projectService.hasDeferredExtension()) { + this.compilerOptions.allowNonTsExtensions = true; + } + switch (projectService.serverMode) { + case 0 /* Semantic */: + this.languageServiceEnabled = true; + break; + case 1 /* PartialSemantic */: + this.languageServiceEnabled = true; + this.compilerOptions.noResolve = true; + this.compilerOptions.types = []; + break; + case 2 /* Syntactic */: + this.languageServiceEnabled = false; + this.compilerOptions.noResolve = true; + this.compilerOptions.types = []; + break; + default: + Debug.assertNever(projectService.serverMode); + } + this.setInternalCompilerOptionsForEmittingJsFiles(); + const host = this.projectService.host; + if (this.projectService.logger.loggingEnabled()) { + this.trace = (s) => this.writeLog(s); + } else if (host.trace) { + this.trace = (s) => host.trace(s); + } + this.realpath = maybeBind(host, host.realpath); + this.resolutionCache = createResolutionCache( + this, + this.currentDirectory, + /*logChangesWhenResolvingModule*/ + true + ); + this.languageService = createLanguageService(this, this.documentRegistry, this.projectService.serverMode); + if (lastFileExceededProgramSize) { + this.disableLanguageService(lastFileExceededProgramSize); + } + this.markAsDirty(); + if (!isBackgroundProject(this)) { + this.projectService.pendingEnsureProjectForOpenFiles = true; + } + this.projectService.onProjectCreation(this); + } + /** @internal */ + getResolvedProjectReferenceToRedirect(_fileName) { + return void 0; + } + isNonTsProject() { + updateProjectIfDirty(this); + return allFilesAreJsOrDts(this); + } + isJsOnlyProject() { + updateProjectIfDirty(this); + return hasOneOrMoreJsAndNoTsFiles(this); + } + static resolveModule(moduleName, initialDir, host, log) { + return _Project.importServicePluginSync({ name: moduleName }, [initialDir], host, log).resolvedModule; + } + /** @internal */ + static importServicePluginSync(pluginConfigEntry, searchPaths, host, log) { + Debug.assertIsDefined(host.require); + let errorLogs; + let resolvedModule; + for (const initialDir of searchPaths) { + const resolvedPath = normalizeSlashes(host.resolvePath(combinePaths(initialDir, "node_modules"))); + log(`Loading ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`); + const result = host.require(resolvedPath, pluginConfigEntry.name); + if (!result.error) { + resolvedModule = result.module; + break; + } + const err = result.error.stack || result.error.message || JSON.stringify(result.error); + (errorLogs ?? (errorLogs = [])).push(`Failed to load module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`); + } + return { pluginConfigEntry, resolvedModule, errorLogs }; + } + /** @internal */ + static async importServicePluginAsync(pluginConfigEntry, searchPaths, host, log) { + Debug.assertIsDefined(host.importPlugin); + let errorLogs; + let resolvedModule; + for (const initialDir of searchPaths) { + const resolvedPath = combinePaths(initialDir, "node_modules"); + log(`Dynamically importing ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`); + let result; + try { + result = await host.importPlugin(resolvedPath, pluginConfigEntry.name); + } catch (e) { + result = { module: void 0, error: e }; + } + if (!result.error) { + resolvedModule = result.module; + break; + } + const err = result.error.stack || result.error.message || JSON.stringify(result.error); + (errorLogs ?? (errorLogs = [])).push(`Failed to dynamically import module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`); + } + return { pluginConfigEntry, resolvedModule, errorLogs }; + } + isKnownTypesPackageName(name) { + return this.typingsCache.isKnownTypesPackageName(name); + } + installPackage(options) { + return this.typingsCache.installPackage({ ...options, projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) }); + } + /** @internal */ + getGlobalTypingsCacheLocation() { + return this.getGlobalCache(); + } + get typingsCache() { + return this.projectService.typingsCache; + } + /** @internal */ + getSymlinkCache() { + if (!this.symlinks) { + this.symlinks = createSymlinkCache(this.getCurrentDirectory(), this.getCanonicalFileName); + } + if (this.program && !this.symlinks.hasProcessedResolutions()) { + this.symlinks.setSymlinksFromResolutions( + this.program.forEachResolvedModule, + this.program.forEachResolvedTypeReferenceDirective, + this.program.getAutomaticTypeDirectiveResolutions() + ); + } + return this.symlinks; + } + // Method of LanguageServiceHost + getCompilationSettings() { + return this.compilerOptions; + } + // Method to support public API + getCompilerOptions() { + return this.getCompilationSettings(); + } + getNewLine() { + return this.projectService.host.newLine; + } + getProjectVersion() { + return this.projectStateVersion.toString(); + } + getProjectReferences() { + return void 0; + } + getScriptFileNames() { + if (!this.rootFiles) { + return emptyArray; + } + let result; + this.rootFilesMap.forEach((value) => { + if (this.languageServiceEnabled || value.info && value.info.isScriptOpen()) { + (result || (result = [])).push(value.fileName); + } + }); + return addRange(result, this.typingFiles) || emptyArray; + } + getOrCreateScriptInfoAndAttachToProject(fileName) { + const scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(fileName, this.currentDirectory, this.directoryStructureHost); + if (scriptInfo) { + const existingValue = this.rootFilesMap.get(scriptInfo.path); + if (existingValue && existingValue.info !== scriptInfo) { + this.rootFiles.push(scriptInfo); + existingValue.info = scriptInfo; + } + scriptInfo.attachToProject(this); + } + return scriptInfo; + } + getScriptKind(fileName) { + const info = this.projectService.getScriptInfoForPath(this.toPath(fileName)); + return info && info.scriptKind; + } + getScriptVersion(filename) { + const info = this.projectService.getOrCreateScriptInfoNotOpenedByClient(filename, this.currentDirectory, this.directoryStructureHost); + return info && info.getLatestVersion(); + } + getScriptSnapshot(filename) { + const scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename); + if (scriptInfo) { + return scriptInfo.getSnapshot(); + } + } + getCancellationToken() { + return this.cancellationToken; + } + getCurrentDirectory() { + return this.currentDirectory; + } + getDefaultLibFileName() { + const nodeModuleBinDir = getDirectoryPath(normalizePath(this.projectService.getExecutingFilePath())); + return combinePaths(nodeModuleBinDir, getDefaultLibFileName(this.compilerOptions)); + } + useCaseSensitiveFileNames() { + return this.projectService.host.useCaseSensitiveFileNames; + } + readDirectory(path, extensions, exclude, include, depth) { + return this.directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); + } + readFile(fileName) { + return this.projectService.host.readFile(fileName); + } + writeFile(fileName, content) { + return this.projectService.host.writeFile(fileName, content); + } + fileExists(file) { + const path = this.toPath(file); + return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); + } + /** @internal */ + resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { + return this.resolutionCache.resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames); + } + /** @internal */ + getModuleResolutionCache() { + return this.resolutionCache.getModuleResolutionCache(); + } + /** @internal */ + resolveTypeReferenceDirectiveReferences(typeDirectiveReferences, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { + return this.resolutionCache.resolveTypeReferenceDirectiveReferences( + typeDirectiveReferences, + containingFile, + redirectedReference, + options, + containingSourceFile, + reusedNames + ); + } + /** @internal */ + resolveLibrary(libraryName, resolveFrom, options, libFileName) { + return this.resolutionCache.resolveLibrary(libraryName, resolveFrom, options, libFileName); + } + directoryExists(path) { + return this.directoryStructureHost.directoryExists(path); + } + getDirectories(path) { + return this.directoryStructureHost.getDirectories(path); + } + /** @internal */ + getCachedDirectoryStructureHost() { + return void 0; + } + /** @internal */ + toPath(fileName) { + return toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName); + } + /** @internal */ + watchDirectoryOfFailedLookupLocation(directory, cb, flags) { + return this.projectService.watchFactory.watchDirectory( + directory, + cb, + flags, + this.projectService.getWatchOptions(this), + WatchType.FailedLookupLocations, + this + ); + } + /** @internal */ + watchAffectingFileLocation(file, cb) { + return this.projectService.watchFactory.watchFile( + file, + cb, + 2e3 /* High */, + this.projectService.getWatchOptions(this), + WatchType.AffectingFileLocation, + this + ); + } + /** @internal */ + clearInvalidateResolutionOfFailedLookupTimer() { + return this.projectService.throttledOperations.cancel(`${this.getProjectName()}FailedLookupInvalidation`); + } + /** @internal */ + scheduleInvalidateResolutionsOfFailedLookupLocations() { + this.projectService.throttledOperations.schedule( + `${this.getProjectName()}FailedLookupInvalidation`, + /*delay*/ + 1e3, + () => { + if (this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) { + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + } + } + ); + } + /** @internal */ + invalidateResolutionsOfFailedLookupLocations() { + if (this.clearInvalidateResolutionOfFailedLookupTimer() && this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) { + this.markAsDirty(); + this.projectService.delayEnsureProjectForOpenFiles(); + } + } + /** @internal */ + onInvalidatedResolution() { + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + } + /** @internal */ + watchTypeRootsDirectory(directory, cb, flags) { + return this.projectService.watchFactory.watchDirectory( + directory, + cb, + flags, + this.projectService.getWatchOptions(this), + WatchType.TypeRoots, + this + ); + } + /** @internal */ + hasChangedAutomaticTypeDirectiveNames() { + return this.resolutionCache.hasChangedAutomaticTypeDirectiveNames(); + } + /** @internal */ + onChangedAutomaticTypeDirectiveNames() { + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + } + /** @internal */ + getGlobalCache() { + return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : void 0; + } + /** @internal */ + fileIsOpen(filePath) { + return this.projectService.openFiles.has(filePath); + } + /** @internal */ + writeLog(s) { + this.projectService.logger.info(s); + } + log(s) { + this.writeLog(s); + } + error(s) { + this.projectService.logger.msg(s, "Err" /* Err */); + } + setInternalCompilerOptionsForEmittingJsFiles() { + if (this.projectKind === 0 /* Inferred */ || this.projectKind === 2 /* External */) { + this.compilerOptions.noEmitForJsFiles = true; + } + } + /** + * Get the errors that dont have any file name associated + */ + getGlobalProjectErrors() { + return filter(this.projectErrors, (diagnostic) => !diagnostic.file) || emptyArray2; + } + /** + * Get all the project errors + */ + getAllProjectErrors() { + return this.projectErrors || emptyArray2; + } + setProjectErrors(projectErrors) { + this.projectErrors = projectErrors; + } + getLanguageService(ensureSynchronized = true) { + if (ensureSynchronized) { + updateProjectIfDirty(this); + } + return this.languageService; + } + /** @internal */ + getSourceMapper() { + return this.getLanguageService().getSourceMapper(); + } + /** @internal */ + clearSourceMapperCache() { + this.languageService.clearSourceMapperCache(); + } + /** @internal */ + getDocumentPositionMapper(generatedFileName, sourceFileName) { + return this.projectService.getDocumentPositionMapper(this, generatedFileName, sourceFileName); + } + /** @internal */ + getSourceFileLike(fileName) { + return this.projectService.getSourceFileLike(fileName, this); + } + /** @internal */ + shouldEmitFile(scriptInfo) { + return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent() && !this.program.isSourceOfProjectReferenceRedirect(scriptInfo.path); + } + getCompileOnSaveAffectedFileList(scriptInfo) { + if (!this.languageServiceEnabled) { + return []; + } + updateProjectIfDirty(this); + this.builderState = BuilderState.create( + this.program, + this.builderState, + /*disableUseFileVersionAsSignature*/ + true + ); + return mapDefined( + BuilderState.getFilesAffectedBy( + this.builderState, + this.program, + scriptInfo.path, + this.cancellationToken, + this.projectService.host + ), + (sourceFile) => this.shouldEmitFile(this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : void 0 + ); + } + /** + * Returns true if emit was conducted + */ + emitFile(scriptInfo, writeFile2) { + if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) { + return { emitSkipped: true, diagnostics: emptyArray2 }; + } + const { emitSkipped, diagnostics, outputFiles } = this.getLanguageService().getEmitOutput(scriptInfo.fileName); + if (!emitSkipped) { + for (const outputFile of outputFiles) { + const outputFileAbsoluteFileName = getNormalizedAbsolutePath(outputFile.name, this.currentDirectory); + writeFile2(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); + } + if (this.builderState && getEmitDeclarations(this.compilerOptions)) { + const dtsFiles = outputFiles.filter((f) => isDeclarationFileName(f.name)); + if (dtsFiles.length === 1) { + const sourceFile = this.program.getSourceFile(scriptInfo.fileName); + const signature = this.projectService.host.createHash ? this.projectService.host.createHash(dtsFiles[0].text) : generateDjb2Hash(dtsFiles[0].text); + BuilderState.updateSignatureOfFile(this.builderState, signature, sourceFile.resolvedPath); + } + } + } + return { emitSkipped, diagnostics }; + } + enableLanguageService() { + if (this.languageServiceEnabled || this.projectService.serverMode === 2 /* Syntactic */) { + return; + } + this.languageServiceEnabled = true; + this.lastFileExceededProgramSize = void 0; + this.projectService.onUpdateLanguageServiceStateForProject( + this, + /*languageServiceEnabled*/ + true + ); + } + /** @internal */ + cleanupProgram() { + if (this.program) { + for (const f of this.program.getSourceFiles()) { + this.detachScriptInfoIfNotRoot(f.fileName); + } + this.program.forEachResolvedProjectReference((ref) => this.detachScriptInfoFromProject(ref.sourceFile.fileName)); + this.program = void 0; + } + } + disableLanguageService(lastFileExceededProgramSize) { + if (!this.languageServiceEnabled) { + return; + } + Debug.assert(this.projectService.serverMode !== 2 /* Syntactic */); + this.languageService.cleanupSemanticCache(); + this.languageServiceEnabled = false; + this.cleanupProgram(); + this.lastFileExceededProgramSize = lastFileExceededProgramSize; + this.builderState = void 0; + if (this.autoImportProviderHost) { + this.autoImportProviderHost.close(); + } + this.autoImportProviderHost = void 0; + this.resolutionCache.closeTypeRootsWatch(); + this.clearGeneratedFileWatch(); + this.projectService.verifyDocumentRegistry(); + this.projectService.onUpdateLanguageServiceStateForProject( + this, + /*languageServiceEnabled*/ + false + ); + } + getProjectName() { + return this.projectName; + } + removeLocalTypingsFromTypeAcquisition(newTypeAcquisition) { + if (!newTypeAcquisition || !newTypeAcquisition.include) { + return newTypeAcquisition; + } + return { ...newTypeAcquisition, include: this.removeExistingTypings(newTypeAcquisition.include) }; + } + getExternalFiles(updateLevel) { + return sort(flatMap(this.plugins, (plugin) => { + if (typeof plugin.module.getExternalFiles !== "function") + return; + try { + return plugin.module.getExternalFiles(this, updateLevel || 0 /* Update */); + } catch (e) { + this.projectService.logger.info(`A plugin threw an exception in getExternalFiles: ${e}`); + if (e.stack) { + this.projectService.logger.info(e.stack); + } + } + })); + } + getSourceFile(path) { + if (!this.program) { + return void 0; + } + return this.program.getSourceFileByPath(path); + } + /** @internal */ + getSourceFileOrConfigFile(path) { + const options = this.program.getCompilerOptions(); + return path === options.configFilePath ? options.configFile : this.getSourceFile(path); + } + close() { + this.projectService.typingsCache.onProjectClosed(this); + this.closeWatchingTypingLocations(); + this.cleanupProgram(); + forEach(this.externalFiles, (externalFile) => this.detachScriptInfoIfNotRoot(externalFile)); + for (const root of this.rootFiles) { + root.detachFromProject(this); + } + this.projectService.pendingEnsureProjectForOpenFiles = true; + this.rootFiles = void 0; + this.rootFilesMap = void 0; + this.externalFiles = void 0; + this.program = void 0; + this.builderState = void 0; + this.resolutionCache.clear(); + this.resolutionCache = void 0; + this.cachedUnresolvedImportsPerFile = void 0; + this.moduleSpecifierCache = void 0; + this.directoryStructureHost = void 0; + this.exportMapCache = void 0; + this.projectErrors = void 0; + this.plugins.length = 0; + if (this.missingFilesMap) { + clearMap(this.missingFilesMap, closeFileWatcher); + this.missingFilesMap = void 0; + } + this.clearGeneratedFileWatch(); + this.clearInvalidateResolutionOfFailedLookupTimer(); + if (this.autoImportProviderHost) { + this.autoImportProviderHost.close(); + } + this.autoImportProviderHost = void 0; + if (this.noDtsResolutionProject) { + this.noDtsResolutionProject.close(); + } + this.noDtsResolutionProject = void 0; + this.languageService.dispose(); + this.languageService = void 0; + } + detachScriptInfoIfNotRoot(uncheckedFilename) { + const info = this.projectService.getScriptInfo(uncheckedFilename); + if (info && !this.isRoot(info)) { + info.detachFromProject(this); + } + } + isClosed() { + return this.rootFiles === void 0; + } + hasRoots() { + return this.rootFiles && this.rootFiles.length > 0; + } + /** @internal */ + isOrphan() { + return false; + } + getRootFiles() { + return this.rootFiles && this.rootFiles.map((info) => info.fileName); + } + /** @internal */ + getRootFilesMap() { + return this.rootFilesMap; + } + getRootScriptInfos() { + return this.rootFiles; + } + getScriptInfos() { + if (!this.languageServiceEnabled) { + return this.rootFiles; + } + return map(this.program.getSourceFiles(), (sourceFile) => { + const scriptInfo = this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); + Debug.assert(!!scriptInfo, "getScriptInfo", () => `scriptInfo for a file '${sourceFile.fileName}' Path: '${sourceFile.path}' / '${sourceFile.resolvedPath}' is missing.`); + return scriptInfo; + }); + } + getExcludedFiles() { + return emptyArray2; + } + getFileNames(excludeFilesFromExternalLibraries, excludeConfigFiles) { + if (!this.program) { + return []; + } + if (!this.languageServiceEnabled) { + let rootFiles = this.getRootFiles(); + if (this.compilerOptions) { + const defaultLibrary = getDefaultLibFilePath(this.compilerOptions); + if (defaultLibrary) { + (rootFiles || (rootFiles = [])).push(asNormalizedPath(defaultLibrary)); + } + } + return rootFiles; + } + const result = []; + for (const f of this.program.getSourceFiles()) { + if (excludeFilesFromExternalLibraries && this.program.isSourceFileFromExternalLibrary(f)) { + continue; + } + result.push(asNormalizedPath(f.fileName)); + } + if (!excludeConfigFiles) { + const configFile = this.program.getCompilerOptions().configFile; + if (configFile) { + result.push(asNormalizedPath(configFile.fileName)); + if (configFile.extendedSourceFiles) { + for (const f of configFile.extendedSourceFiles) { + result.push(asNormalizedPath(f)); + } + } + } + } + return result; + } + /** @internal */ + getFileNamesWithRedirectInfo(includeProjectReferenceRedirectInfo) { + return this.getFileNames().map((fileName) => ({ + fileName, + isSourceOfProjectReferenceRedirect: includeProjectReferenceRedirectInfo && this.isSourceOfProjectReferenceRedirect(fileName) + })); + } + hasConfigFile(configFilePath) { + if (this.program && this.languageServiceEnabled) { + const configFile = this.program.getCompilerOptions().configFile; + if (configFile) { + if (configFilePath === asNormalizedPath(configFile.fileName)) { + return true; + } + if (configFile.extendedSourceFiles) { + for (const f of configFile.extendedSourceFiles) { + if (configFilePath === asNormalizedPath(f)) { + return true; + } + } + } + } + } + return false; + } + containsScriptInfo(info) { + if (this.isRoot(info)) + return true; + if (!this.program) + return false; + const file = this.program.getSourceFileByPath(info.path); + return !!file && file.resolvedPath === info.path; + } + containsFile(filename, requireOpen) { + const info = this.projectService.getScriptInfoForNormalizedPath(filename); + if (info && (info.isScriptOpen() || !requireOpen)) { + return this.containsScriptInfo(info); + } + return false; + } + isRoot(info) { + var _a; + return this.rootFilesMap && ((_a = this.rootFilesMap.get(info.path)) == null ? void 0 : _a.info) === info; + } + // add a root file to project + addRoot(info, fileName) { + Debug.assert(!this.isRoot(info)); + this.rootFiles.push(info); + this.rootFilesMap.set(info.path, { fileName: fileName || info.fileName, info }); + info.attachToProject(this); + this.markAsDirty(); + } + // add a root file that doesnt exist on host + addMissingFileRoot(fileName) { + const path = this.projectService.toPath(fileName); + this.rootFilesMap.set(path, { fileName }); + this.markAsDirty(); + } + removeFile(info, fileExists, detachFromProject) { + if (this.isRoot(info)) { + this.removeRoot(info); + } + if (fileExists) { + this.resolutionCache.removeResolutionsOfFile(info.path); + } else { + this.resolutionCache.invalidateResolutionOfFile(info.path); + } + this.cachedUnresolvedImportsPerFile.delete(info.path); + if (detachFromProject) { + info.detachFromProject(this); + } + this.markAsDirty(); + } + registerFileUpdate(fileName) { + (this.updatedFileNames || (this.updatedFileNames = /* @__PURE__ */ new Set())).add(fileName); + } + /** @internal */ + markFileAsDirty(changedFile) { + this.markAsDirty(); + if (this.exportMapCache && !this.exportMapCache.isEmpty()) { + (this.changedFilesForExportMapCache || (this.changedFilesForExportMapCache = /* @__PURE__ */ new Set())).add(changedFile); + } + } + markAsDirty() { + if (!this.dirty) { + this.projectStateVersion++; + this.dirty = true; + } + } + /** @internal */ + onAutoImportProviderSettingsChanged() { + var _a; + if (this.autoImportProviderHost === false) { + this.autoImportProviderHost = void 0; + } else { + (_a = this.autoImportProviderHost) == null ? void 0 : _a.markAsDirty(); + } + } + /** @internal */ + onPackageJsonChange(packageJsonPath) { + var _a; + if ((_a = this.packageJsonsForAutoImport) == null ? void 0 : _a.has(packageJsonPath)) { + this.moduleSpecifierCache.clear(); + if (this.autoImportProviderHost) { + this.autoImportProviderHost.markAsDirty(); + } + } + } + /** @internal */ + onFileAddedOrRemoved(isSymlink) { + this.hasAddedorRemovedFiles = true; + if (isSymlink) { + this.hasAddedOrRemovedSymlinks = true; + } + } + /** @internal */ + onDiscoveredSymlink() { + this.hasAddedOrRemovedSymlinks = true; + } + /** + * Updates set of files that contribute to this project + * @returns: true if set of files in the project stays the same and false - otherwise. + */ + updateGraph() { + var _a, _b, _c, _d, _e; + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "updateGraph", { name: this.projectName, kind: ProjectKind[this.projectKind] }); + (_b = perfLogger) == null ? void 0 : _b.logStartUpdateGraph(); + this.resolutionCache.startRecordingFilesWithChangedResolutions(); + const hasNewProgram = this.updateGraphWorker(); + const hasAddedorRemovedFiles = this.hasAddedorRemovedFiles; + this.hasAddedorRemovedFiles = false; + this.hasAddedOrRemovedSymlinks = false; + const changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || emptyArray2; + for (const file of changedFiles) { + this.cachedUnresolvedImportsPerFile.delete(file); + } + if (this.languageServiceEnabled && this.projectService.serverMode === 0 /* Semantic */) { + if (hasNewProgram || changedFiles.length) { + this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile); + } + this.projectService.typingsCache.enqueueInstallTypingsForProject(this, this.lastCachedUnresolvedImportsList, hasAddedorRemovedFiles); + } else { + this.lastCachedUnresolvedImportsList = void 0; + } + const isFirstProgramLoad = this.projectProgramVersion === 0 && hasNewProgram; + if (hasNewProgram) { + this.projectProgramVersion++; + } + if (hasAddedorRemovedFiles) { + if (!this.autoImportProviderHost) + this.autoImportProviderHost = void 0; + (_c = this.autoImportProviderHost) == null ? void 0 : _c.markAsDirty(); + } + if (isFirstProgramLoad) { + this.getPackageJsonAutoImportProvider(); + } + (_d = perfLogger) == null ? void 0 : _d.logStopUpdateGraph(); + (_e = tracing) == null ? void 0 : _e.pop(); + return !hasNewProgram; + } + /** @internal */ + updateTypingFiles(typingFiles) { + if (enumerateInsertsAndDeletes( + typingFiles, + this.typingFiles, + getStringComparer(!this.useCaseSensitiveFileNames()), + /*inserted*/ + noop, + (removed) => this.detachScriptInfoFromProject(removed) + )) { + this.typingFiles = typingFiles; + this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + } + } + /** @internal */ + closeWatchingTypingLocations() { + if (this.typingWatchers) + clearMap(this.typingWatchers, closeFileWatcher); + this.typingWatchers = void 0; + } + /** @internal */ + onTypingInstallerWatchInvoke() { + this.typingWatchers.isInvoked = true; + this.projectService.updateTypingsForProject({ projectName: this.getProjectName(), kind: ActionInvalidate }); + } + /** @internal */ + watchTypingLocations(files) { + if (!files) { + this.typingWatchers.isInvoked = false; + return; + } + if (!files.length) { + this.closeWatchingTypingLocations(); + return; + } + const toRemove = new Map(this.typingWatchers); + if (!this.typingWatchers) + this.typingWatchers = /* @__PURE__ */ new Map(); + this.typingWatchers.isInvoked = false; + const createProjectWatcher = (path, typingsWatcherType) => { + const canonicalPath = this.toPath(path); + toRemove.delete(canonicalPath); + if (!this.typingWatchers.has(canonicalPath)) { + this.typingWatchers.set( + canonicalPath, + typingsWatcherType === "FileWatcher" /* FileWatcher */ ? this.projectService.watchFactory.watchFile( + path, + () => !this.typingWatchers.isInvoked ? this.onTypingInstallerWatchInvoke() : this.writeLog(`TypingWatchers already invoked`), + 2e3 /* High */, + this.projectService.getWatchOptions(this), + WatchType.TypingInstallerLocationFile, + this + ) : this.projectService.watchFactory.watchDirectory( + path, + (f) => { + if (this.typingWatchers.isInvoked) + return this.writeLog(`TypingWatchers already invoked`); + if (!fileExtensionIs(f, ".json" /* Json */)) + return this.writeLog(`Ignoring files that are not *.json`); + if (comparePaths(f, combinePaths(this.projectService.typingsInstaller.globalTypingsCacheLocation, "package.json"), !this.useCaseSensitiveFileNames())) + return this.writeLog(`Ignoring package.json change at global typings location`); + this.onTypingInstallerWatchInvoke(); + }, + 1 /* Recursive */, + this.projectService.getWatchOptions(this), + WatchType.TypingInstallerLocationDirectory, + this + ) + ); + } + }; + for (const file of files) { + const basename = getBaseFileName(file); + if (basename === "package.json" || basename === "bower.json") { + createProjectWatcher(file, "FileWatcher" /* FileWatcher */); + continue; + } + if (containsPath(this.currentDirectory, file, this.currentDirectory, !this.useCaseSensitiveFileNames())) { + const subDirectory = file.indexOf(directorySeparator, this.currentDirectory.length + 1); + if (subDirectory !== -1) { + createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */); + } else { + createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); + } + continue; + } + if (containsPath(this.projectService.typingsInstaller.globalTypingsCacheLocation, file, this.currentDirectory, !this.useCaseSensitiveFileNames())) { + createProjectWatcher(this.projectService.typingsInstaller.globalTypingsCacheLocation, "DirectoryWatcher" /* DirectoryWatcher */); + continue; + } + createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); + } + toRemove.forEach((watch, path) => { + watch.close(); + this.typingWatchers.delete(path); + }); + } + /** @internal */ + getCurrentProgram() { + return this.program; + } + removeExistingTypings(include) { + const existing = getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); + return include.filter((i) => !existing.includes(i)); + } + updateGraphWorker() { + var _a, _b; + const oldProgram = this.languageService.getCurrentProgram(); + Debug.assert(oldProgram === this.program); + Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); + this.writeLog(`Starting updateGraphWorker: Project: ${this.getProjectName()}`); + const start = timestamp(); + const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = this.resolutionCache.createHasInvalidatedResolutions(returnFalse, returnFalse); + this.hasInvalidatedResolutions = hasInvalidatedResolutions; + this.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions; + this.resolutionCache.startCachingPerDirectoryResolution(); + this.program = this.languageService.getProgram(); + this.dirty = false; + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "finishCachingPerDirectoryResolution"); + this.resolutionCache.finishCachingPerDirectoryResolution(this.program, oldProgram); + (_b = tracing) == null ? void 0 : _b.pop(); + Debug.assert(oldProgram === void 0 || this.program !== void 0); + let hasNewProgram = false; + if (this.program && (!oldProgram || this.program !== oldProgram && this.program.structureIsReused !== 2 /* Completely */)) { + hasNewProgram = true; + if (oldProgram) { + for (const f of oldProgram.getSourceFiles()) { + const newFile = this.program.getSourceFileByPath(f.resolvedPath); + if (!newFile || f.resolvedPath === f.path && newFile.resolvedPath !== f.path) { + this.detachScriptInfoFromProject( + f.fileName, + !!this.program.getSourceFileByPath(f.path), + /*syncDirWatcherRemove*/ + true + ); + } + } + oldProgram.forEachResolvedProjectReference((resolvedProjectReference) => { + if (!this.program.getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { + this.detachScriptInfoFromProject( + resolvedProjectReference.sourceFile.fileName, + /*noRemoveResolution*/ + void 0, + /*syncDirWatcherRemove*/ + true + ); + } + }); + } + updateMissingFilePathsWatch( + this.program, + this.missingFilesMap || (this.missingFilesMap = /* @__PURE__ */ new Map()), + // Watch the missing files + (missingFilePath) => this.addMissingFileWatcher(missingFilePath) + ); + if (this.generatedFilesMap) { + const outPath = outFile(this.compilerOptions); + if (isGeneratedFileWatcher(this.generatedFilesMap)) { + if (!outPath || !this.isValidGeneratedFileWatcher( + removeFileExtension(outPath) + ".d.ts" /* Dts */, + this.generatedFilesMap + )) { + this.clearGeneratedFileWatch(); + } + } else { + if (outPath) { + this.clearGeneratedFileWatch(); + } else { + this.generatedFilesMap.forEach((watcher, source) => { + const sourceFile = this.program.getSourceFileByPath(source); + if (!sourceFile || sourceFile.resolvedPath !== source || !this.isValidGeneratedFileWatcher( + getDeclarationEmitOutputFilePathWorker(sourceFile.fileName, this.compilerOptions, this.currentDirectory, this.program.getCommonSourceDirectory(), this.getCanonicalFileName), + watcher + )) { + closeFileWatcherOf(watcher); + this.generatedFilesMap.delete(source); + } + }); + } + } + } + if (this.languageServiceEnabled && this.projectService.serverMode === 0 /* Semantic */) { + this.resolutionCache.updateTypeRootsWatch(); + } + } + this.projectService.verifyProgram(this); + if (this.exportMapCache && !this.exportMapCache.isEmpty()) { + this.exportMapCache.releaseSymbols(); + if (this.hasAddedorRemovedFiles || oldProgram && !this.program.structureIsReused) { + this.exportMapCache.clear(); + } else if (this.changedFilesForExportMapCache && oldProgram && this.program) { + forEachKey(this.changedFilesForExportMapCache, (fileName) => { + const oldSourceFile = oldProgram.getSourceFileByPath(fileName); + const sourceFile = this.program.getSourceFileByPath(fileName); + if (!oldSourceFile || !sourceFile) { + this.exportMapCache.clear(); + return true; + } + return this.exportMapCache.onFileChanged(oldSourceFile, sourceFile, !!this.getTypeAcquisition().enable); + }); + } + } + if (this.changedFilesForExportMapCache) { + this.changedFilesForExportMapCache.clear(); + } + if (this.hasAddedOrRemovedSymlinks || this.program && !this.program.structureIsReused && this.getCompilerOptions().preserveSymlinks) { + this.symlinks = void 0; + this.moduleSpecifierCache.clear(); + } + const oldExternalFiles = this.externalFiles || emptyArray2; + this.externalFiles = this.getExternalFiles(); + enumerateInsertsAndDeletes( + this.externalFiles, + oldExternalFiles, + getStringComparer(!this.useCaseSensitiveFileNames()), + // Ensure a ScriptInfo is created for new external files. This is performed indirectly + // by the host for files in the program when the program is retrieved above but + // the program doesn't contain external files so this must be done explicitly. + (inserted) => { + const scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, this.currentDirectory, this.directoryStructureHost); + scriptInfo == null ? void 0 : scriptInfo.attachToProject(this); + }, + (removed) => this.detachScriptInfoFromProject(removed) + ); + const elapsed = timestamp() - start; + this.sendPerformanceEvent("UpdateGraph", elapsed); + this.writeLog(`Finishing updateGraphWorker: Project: ${this.getProjectName()} Version: ${this.getProjectVersion()} structureChanged: ${hasNewProgram}${this.program ? ` structureIsReused:: ${StructureIsReused[this.program.structureIsReused]}` : ""} Elapsed: ${elapsed}ms`); + if (this.projectService.logger.isTestLogger) { + if (this.program !== oldProgram) { + this.print( + /*writeProjectFileNames*/ + true, + this.hasAddedorRemovedFiles, + /*writeFileVersionAndText*/ + true + ); + } else { + this.writeLog(`Same program as before`); + } + } else if (this.hasAddedorRemovedFiles) { + this.print( + /*writeProjectFileNames*/ + true, + /*writeFileExplaination*/ + true, + /*writeFileVersionAndText*/ + false + ); + } else if (this.program !== oldProgram) { + this.writeLog(`Different program with same set of files`); + } + this.projectService.verifyDocumentRegistry(); + return hasNewProgram; + } + /** @internal */ + sendPerformanceEvent(kind, durationMs) { + this.projectService.sendPerformanceEvent(kind, durationMs); + } + detachScriptInfoFromProject(uncheckedFileName, noRemoveResolution, syncDirWatcherRemove) { + const scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); + if (scriptInfoToDetach) { + scriptInfoToDetach.detachFromProject(this); + if (!noRemoveResolution) { + this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path, syncDirWatcherRemove); + } + } + } + addMissingFileWatcher(missingFilePath) { + var _a; + if (isConfiguredProject(this)) { + const configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(missingFilePath); + if ((_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config) == null ? void 0 : _a.projects.has(this.canonicalConfigFilePath)) + return noopFileWatcher; + } + const fileWatcher = this.projectService.watchFactory.watchFile( + missingFilePath, + (fileName, eventKind) => { + if (isConfiguredProject(this)) { + this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); + } + if (eventKind === 0 /* Created */ && this.missingFilesMap.has(missingFilePath)) { + this.missingFilesMap.delete(missingFilePath); + fileWatcher.close(); + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + } + }, + 500 /* Medium */, + this.projectService.getWatchOptions(this), + WatchType.MissingFile, + this + ); + return fileWatcher; + } + isWatchedMissingFile(path) { + return !!this.missingFilesMap && this.missingFilesMap.has(path); + } + /** @internal */ + addGeneratedFileWatch(generatedFile, sourceFile) { + if (outFile(this.compilerOptions)) { + if (!this.generatedFilesMap) { + this.generatedFilesMap = this.createGeneratedFileWatcher(generatedFile); + } + } else { + const path = this.toPath(sourceFile); + if (this.generatedFilesMap) { + if (isGeneratedFileWatcher(this.generatedFilesMap)) { + Debug.fail(`${this.projectName} Expected to not have --out watcher for generated file with options: ${JSON.stringify(this.compilerOptions)}`); + return; + } + if (this.generatedFilesMap.has(path)) + return; + } else { + this.generatedFilesMap = /* @__PURE__ */ new Map(); + } + this.generatedFilesMap.set(path, this.createGeneratedFileWatcher(generatedFile)); + } + } + createGeneratedFileWatcher(generatedFile) { + return { + generatedFilePath: this.toPath(generatedFile), + watcher: this.projectService.watchFactory.watchFile( + generatedFile, + () => { + this.clearSourceMapperCache(); + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + }, + 2e3 /* High */, + this.projectService.getWatchOptions(this), + WatchType.MissingGeneratedFile, + this + ) + }; + } + isValidGeneratedFileWatcher(generateFile, watcher) { + return this.toPath(generateFile) === watcher.generatedFilePath; + } + clearGeneratedFileWatch() { + if (this.generatedFilesMap) { + if (isGeneratedFileWatcher(this.generatedFilesMap)) { + closeFileWatcherOf(this.generatedFilesMap); + } else { + clearMap(this.generatedFilesMap, closeFileWatcherOf); + } + this.generatedFilesMap = void 0; + } + } + getScriptInfoForNormalizedPath(fileName) { + const scriptInfo = this.projectService.getScriptInfoForPath(this.toPath(fileName)); + if (scriptInfo && !scriptInfo.isAttached(this)) { + return Errors.ThrowProjectDoesNotContainDocument(fileName, this); + } + return scriptInfo; + } + getScriptInfo(uncheckedFileName) { + return this.projectService.getScriptInfo(uncheckedFileName); + } + filesToString(writeProjectFileNames) { + return this.filesToStringWorker( + writeProjectFileNames, + /*writeFileExplaination*/ + true, + /*writeFileVersionAndText*/ + false + ); + } + /** @internal */ + filesToStringWorker(writeProjectFileNames, writeFileExplaination, writeFileVersionAndText) { + if (this.isInitialLoadPending()) + return " Files (0) InitialLoadPending\n"; + if (!this.program) + return " Files (0) NoProgram\n"; + const sourceFiles = this.program.getSourceFiles(); + let strBuilder = ` Files (${sourceFiles.length}) +`; + if (writeProjectFileNames) { + for (const file of sourceFiles) { + strBuilder += ` ${file.fileName}${writeFileVersionAndText ? ` ${file.version} ${JSON.stringify(file.text)}` : ""} +`; + } + if (writeFileExplaination) { + strBuilder += "\n\n"; + explainFiles(this.program, (s) => strBuilder += ` ${s} +`); + } + } + return strBuilder; + } + /** @internal */ + print(writeProjectFileNames, writeFileExplaination, writeFileVersionAndText) { + this.writeLog(`Project '${this.projectName}' (${ProjectKind[this.projectKind]})`); + this.writeLog(this.filesToStringWorker( + writeProjectFileNames && this.projectService.logger.hasLevel(3 /* verbose */), + writeFileExplaination && this.projectService.logger.hasLevel(3 /* verbose */), + writeFileVersionAndText && this.projectService.logger.hasLevel(3 /* verbose */) + )); + this.writeLog("-----------------------------------------------"); + if (this.autoImportProviderHost) { + this.autoImportProviderHost.print( + /*writeProjectFileNames*/ + false, + /*writeFileExplaination*/ + false, + /*writeFileVersionAndText*/ + false + ); + } + } + setCompilerOptions(compilerOptions) { + var _a; + if (compilerOptions) { + compilerOptions.allowNonTsExtensions = true; + const oldOptions = this.compilerOptions; + this.compilerOptions = compilerOptions; + this.setInternalCompilerOptionsForEmittingJsFiles(); + (_a = this.noDtsResolutionProject) == null ? void 0 : _a.setCompilerOptions(this.getCompilerOptionsForNoDtsResolutionProject()); + if (changesAffectModuleResolution(oldOptions, compilerOptions)) { + this.cachedUnresolvedImportsPerFile.clear(); + this.lastCachedUnresolvedImportsList = void 0; + this.resolutionCache.onChangesAffectModuleResolution(); + this.moduleSpecifierCache.clear(); + } + this.markAsDirty(); + } + } + /** @internal */ + setWatchOptions(watchOptions) { + this.watchOptions = watchOptions; + } + /** @internal */ + getWatchOptions() { + return this.watchOptions; + } + setTypeAcquisition(newTypeAcquisition) { + if (newTypeAcquisition) { + this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition); + } + } + getTypeAcquisition() { + return this.typeAcquisition || {}; + } + /** @internal */ + getChangesSinceVersion(lastKnownVersion, includeProjectReferenceRedirectInfo) { + var _a, _b; + const includeProjectReferenceRedirectInfoIfRequested = includeProjectReferenceRedirectInfo ? (files) => arrayFrom(files.entries(), ([fileName, isSourceOfProjectReferenceRedirect]) => ({ + fileName, + isSourceOfProjectReferenceRedirect + })) : (files) => arrayFrom(files.keys()); + if (!this.isInitialLoadPending()) { + updateProjectIfDirty(this); + } + const info = { + projectName: this.getProjectName(), + version: this.projectProgramVersion, + isInferred: isInferredProject(this), + options: this.getCompilationSettings(), + languageServiceDisabled: !this.languageServiceEnabled, + lastFileExceededProgramSize: this.lastFileExceededProgramSize + }; + const updatedFileNames = this.updatedFileNames; + this.updatedFileNames = void 0; + if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { + if (this.projectProgramVersion === this.lastReportedVersion && !updatedFileNames) { + return { info, projectErrors: this.getGlobalProjectErrors() }; + } + const lastReportedFileNames = this.lastReportedFileNames; + const externalFiles = ((_a = this.externalFiles) == null ? void 0 : _a.map((f) => ({ + fileName: toNormalizedPath(f), + isSourceOfProjectReferenceRedirect: false + }))) || emptyArray2; + const currentFiles = arrayToMap( + this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo).concat(externalFiles), + (info2) => info2.fileName, + (info2) => info2.isSourceOfProjectReferenceRedirect + ); + const added = /* @__PURE__ */ new Map(); + const removed = /* @__PURE__ */ new Map(); + const updated = updatedFileNames ? arrayFrom(updatedFileNames.keys()) : []; + const updatedRedirects = []; + forEachEntry(currentFiles, (isSourceOfProjectReferenceRedirect, fileName) => { + if (!lastReportedFileNames.has(fileName)) { + added.set(fileName, isSourceOfProjectReferenceRedirect); + } else if (includeProjectReferenceRedirectInfo && isSourceOfProjectReferenceRedirect !== lastReportedFileNames.get(fileName)) { + updatedRedirects.push({ + fileName, + isSourceOfProjectReferenceRedirect + }); + } + }); + forEachEntry(lastReportedFileNames, (isSourceOfProjectReferenceRedirect, fileName) => { + if (!currentFiles.has(fileName)) { + removed.set(fileName, isSourceOfProjectReferenceRedirect); + } + }); + this.lastReportedFileNames = currentFiles; + this.lastReportedVersion = this.projectProgramVersion; + return { + info, + changes: { + added: includeProjectReferenceRedirectInfoIfRequested(added), + removed: includeProjectReferenceRedirectInfoIfRequested(removed), + updated: includeProjectReferenceRedirectInfo ? updated.map((fileName) => ({ + fileName, + isSourceOfProjectReferenceRedirect: this.isSourceOfProjectReferenceRedirect(fileName) + })) : updated, + updatedRedirects: includeProjectReferenceRedirectInfo ? updatedRedirects : void 0 + }, + projectErrors: this.getGlobalProjectErrors() + }; + } else { + const projectFileNames = this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo); + const externalFiles = ((_b = this.externalFiles) == null ? void 0 : _b.map((f) => ({ + fileName: toNormalizedPath(f), + isSourceOfProjectReferenceRedirect: false + }))) || emptyArray2; + const allFiles = projectFileNames.concat(externalFiles); + this.lastReportedFileNames = arrayToMap( + allFiles, + (info2) => info2.fileName, + (info2) => info2.isSourceOfProjectReferenceRedirect + ); + this.lastReportedVersion = this.projectProgramVersion; + return { + info, + files: includeProjectReferenceRedirectInfo ? allFiles : allFiles.map((f) => f.fileName), + projectErrors: this.getGlobalProjectErrors() + }; + } + } + // remove a root file from project + removeRoot(info) { + orderedRemoveItem(this.rootFiles, info); + this.rootFilesMap.delete(info.path); + } + /** @internal */ + isSourceOfProjectReferenceRedirect(fileName) { + return !!this.program && this.program.isSourceOfProjectReferenceRedirect(fileName); + } + /** @internal */ + getGlobalPluginSearchPaths() { + return [ + ...this.projectService.pluginProbeLocations, + // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ + combinePaths(this.projectService.getExecutingFilePath(), "../../..") + ]; + } + enableGlobalPlugins(options) { + if (!this.projectService.globalPlugins.length) + return; + const host = this.projectService.host; + if (!host.require && !host.importPlugin) { + this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); + return; + } + const searchPaths = this.getGlobalPluginSearchPaths(); + for (const globalPluginName of this.projectService.globalPlugins) { + if (!globalPluginName) + continue; + if (options.plugins && options.plugins.some((p) => p.name === globalPluginName)) + continue; + this.projectService.logger.info(`Loading global plugin ${globalPluginName}`); + this.enablePlugin({ name: globalPluginName, global: true }, searchPaths); + } + } + enablePlugin(pluginConfigEntry, searchPaths) { + this.projectService.requestEnablePlugin(this, pluginConfigEntry, searchPaths); + } + /** @internal */ + enableProxy(pluginModuleFactory, configEntry) { + try { + if (typeof pluginModuleFactory !== "function") { + this.projectService.logger.info(`Skipped loading plugin ${configEntry.name} because it did not expose a proper factory function`); + return; + } + const info = { + config: configEntry, + project: this, + languageService: this.languageService, + languageServiceHost: this, + serverHost: this.projectService.host, + session: this.projectService.session + }; + const pluginModule = pluginModuleFactory({ typescript: ts_exports2 }); + const newLS = pluginModule.create(info); + for (const k of Object.keys(this.languageService)) { + if (!(k in newLS)) { + this.projectService.logger.info(`Plugin activation warning: Missing proxied method ${k} in created LS. Patching.`); + newLS[k] = this.languageService[k]; + } + } + this.projectService.logger.info(`Plugin validation succeeded`); + this.languageService = newLS; + this.plugins.push({ name: configEntry.name, module: pluginModule }); + } catch (e) { + this.projectService.logger.info(`Plugin activation failed: ${e}`); + } + } + /** @internal */ + onPluginConfigurationChanged(pluginName, configuration) { + this.plugins.filter((plugin) => plugin.name === pluginName).forEach((plugin) => { + if (plugin.module.onConfigurationChanged) { + plugin.module.onConfigurationChanged(configuration); + } + }); + } + /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ + refreshDiagnostics() { + this.projectService.sendProjectsUpdatedInBackgroundEvent(); + } + /** @internal */ + getPackageJsonsVisibleToFile(fileName, rootDir) { + if (this.projectService.serverMode !== 0 /* Semantic */) + return emptyArray2; + return this.projectService.getPackageJsonsVisibleToFile(fileName, rootDir); + } + /** @internal */ + getNearestAncestorDirectoryWithPackageJson(fileName) { + return this.projectService.getNearestAncestorDirectoryWithPackageJson(fileName); + } + /** @internal */ + getPackageJsonsForAutoImport(rootDir) { + const packageJsons = this.getPackageJsonsVisibleToFile(combinePaths(this.currentDirectory, inferredTypesContainingFile), rootDir); + this.packageJsonsForAutoImport = new Set(packageJsons.map((p) => p.fileName)); + return packageJsons; + } + /** @internal */ + getPackageJsonCache() { + return this.projectService.packageJsonCache; + } + /** @internal */ + getCachedExportInfoMap() { + return this.exportMapCache || (this.exportMapCache = createCacheableExportInfoMap(this)); + } + /** @internal */ + clearCachedExportInfoMap() { + var _a; + (_a = this.exportMapCache) == null ? void 0 : _a.clear(); + } + /** @internal */ + getModuleSpecifierCache() { + return this.moduleSpecifierCache; + } + /** @internal */ + includePackageJsonAutoImports() { + if (this.projectService.includePackageJsonAutoImports() === 0 /* Off */ || !this.languageServiceEnabled || isInsideNodeModules(this.currentDirectory) || !this.isDefaultProjectForOpenFiles()) { + return 0 /* Off */; + } + return this.projectService.includePackageJsonAutoImports(); + } + /** @internal */ + getHostForAutoImportProvider() { + var _a, _b; + if (this.program) { + return { + fileExists: this.program.fileExists, + directoryExists: this.program.directoryExists, + realpath: this.program.realpath || ((_a = this.projectService.host.realpath) == null ? void 0 : _a.bind(this.projectService.host)), + getCurrentDirectory: this.getCurrentDirectory.bind(this), + 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(), + readDirectory: this.projectService.host.readDirectory.bind(this.projectService.host) + }; + } + return this.projectService.host; + } + /** @internal */ + getPackageJsonAutoImportProvider() { + var _a, _b, _c; + if (this.autoImportProviderHost === false) { + return void 0; + } + if (this.projectService.serverMode !== 0 /* Semantic */) { + this.autoImportProviderHost = false; + return void 0; + } + if (this.autoImportProviderHost) { + updateProjectIfDirty(this.autoImportProviderHost); + if (this.autoImportProviderHost.isEmpty()) { + this.autoImportProviderHost.close(); + this.autoImportProviderHost = void 0; + return void 0; + } + return this.autoImportProviderHost.getCurrentProgram(); + } + const dependencySelection = this.includePackageJsonAutoImports(); + if (dependencySelection) { + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "getPackageJsonAutoImportProvider"); + const start = timestamp(); + this.autoImportProviderHost = AutoImportProviderProject.create(dependencySelection, this, this.getHostForAutoImportProvider(), this.documentRegistry); + if (this.autoImportProviderHost) { + updateProjectIfDirty(this.autoImportProviderHost); + this.sendPerformanceEvent("CreatePackageJsonAutoImportProvider", timestamp() - start); + (_b = tracing) == null ? void 0 : _b.pop(); + return this.autoImportProviderHost.getCurrentProgram(); + } + (_c = tracing) == null ? void 0 : _c.pop(); + } + } + /** @internal */ + isDefaultProjectForOpenFiles() { + return !!forEachEntry( + this.projectService.openFiles, + (_, fileName) => this.projectService.tryGetDefaultProjectForFile(toNormalizedPath(fileName)) === this + ); + } + /** @internal */ + watchNodeModulesForPackageJsonChanges(directoryPath) { + return this.projectService.watchPackageJsonsInNodeModules(this.toPath(directoryPath), this); + } + /** @internal */ + getIncompleteCompletionsCache() { + return this.projectService.getIncompleteCompletionsCache(); + } + /** @internal */ + getNoDtsResolutionProject(rootFile) { + Debug.assert(this.projectService.serverMode === 0 /* Semantic */); + if (!this.noDtsResolutionProject) { + this.noDtsResolutionProject = new AuxiliaryProject(this.projectService, this.documentRegistry, this.getCompilerOptionsForNoDtsResolutionProject(), this.currentDirectory); + } + if (this.noDtsResolutionProject.rootFile !== rootFile) { + this.projectService.setFileNamesOfAutpImportProviderOrAuxillaryProject(this.noDtsResolutionProject, [rootFile]); + this.noDtsResolutionProject.rootFile = rootFile; + } + return this.noDtsResolutionProject; + } + /** @internal */ + getCompilerOptionsForNoDtsResolutionProject() { + return { + ...this.getCompilerOptions(), + noDtsResolution: true, + allowJs: true, + maxNodeModuleJsDepth: 3, + diagnostics: false, + skipLibCheck: true, + sourceMap: false, + types: emptyArray, + lib: emptyArray, + noLib: true + }; + } + }; + InferredProject2 = class extends Project3 { + /** @internal */ + constructor(projectService, documentRegistry, compilerOptions, watchOptions, projectRootPath, currentDirectory, typeAcquisition) { + super( + projectService.newInferredProjectName(), + 0 /* Inferred */, + projectService, + documentRegistry, + // TODO: GH#18217 + /*files*/ + void 0, + /*lastFileExceededProgramSize*/ + void 0, + compilerOptions, + /*compileOnSaveEnabled*/ + false, + watchOptions, + projectService.host, + currentDirectory + ); + this._isJsInferredProject = false; + this.typeAcquisition = typeAcquisition; + this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); + if (!projectRootPath && !projectService.useSingleInferredProject) { + this.canonicalCurrentDirectory = projectService.toCanonicalFileName(this.currentDirectory); + } + this.enableGlobalPlugins(this.getCompilerOptions()); + } + toggleJsInferredProject(isJsInferredProject) { + if (isJsInferredProject !== this._isJsInferredProject) { + this._isJsInferredProject = isJsInferredProject; + this.setCompilerOptions(); + } + } + setCompilerOptions(options) { + if (!options && !this.getCompilationSettings()) { + return; + } + const newOptions = cloneCompilerOptions(options || this.getCompilationSettings()); + if (this._isJsInferredProject && typeof newOptions.maxNodeModuleJsDepth !== "number") { + newOptions.maxNodeModuleJsDepth = 2; + } else if (!this._isJsInferredProject) { + newOptions.maxNodeModuleJsDepth = void 0; + } + newOptions.allowJs = true; + super.setCompilerOptions(newOptions); + } + addRoot(info) { + Debug.assert(info.isScriptOpen()); + this.projectService.startWatchingConfigFilesForInferredProjectRoot(info); + if (!this._isJsInferredProject && info.isJavaScript()) { + this.toggleJsInferredProject( + /*isJsInferredProject*/ + true + ); + } else if (this.isOrphan() && this._isJsInferredProject && !info.isJavaScript()) { + this.toggleJsInferredProject( + /*isJsInferredProject*/ + false + ); + } + super.addRoot(info); + } + removeRoot(info) { + this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); + super.removeRoot(info); + if (!this.isOrphan() && this._isJsInferredProject && info.isJavaScript()) { + if (every(this.getRootScriptInfos(), (rootInfo) => !rootInfo.isJavaScript())) { + this.toggleJsInferredProject( + /*isJsInferredProject*/ + false + ); + } + } + } + /** @internal */ + isOrphan() { + return !this.hasRoots(); + } + isProjectWithSingleRoot() { + return !this.projectRootPath && !this.projectService.useSingleInferredProject || this.getRootScriptInfos().length === 1; + } + close() { + forEach(this.getRootScriptInfos(), (info) => this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info)); + super.close(); + } + getTypeAcquisition() { + return this.typeAcquisition || { + enable: allRootFilesAreJsOrDts(this), + include: emptyArray, + exclude: emptyArray + }; + } + }; + AuxiliaryProject = class extends Project3 { + constructor(projectService, documentRegistry, compilerOptions, currentDirectory) { + super( + projectService.newAuxiliaryProjectName(), + 4 /* Auxiliary */, + projectService, + documentRegistry, + /*hasExplicitListOfFiles*/ + false, + /*lastFileExceededProgramSize*/ + void 0, + compilerOptions, + /*compileOnSaveEnabled*/ + false, + /*watchOptions*/ + void 0, + projectService.host, + currentDirectory + ); + } + isOrphan() { + return true; + } + scheduleInvalidateResolutionsOfFailedLookupLocations() { + return; + } + }; + _AutoImportProviderProject = class _AutoImportProviderProject extends Project3 { + /** @internal */ + constructor(hostProject, initialRootNames, documentRegistry, compilerOptions) { + super( + hostProject.projectService.newAutoImportProviderProjectName(), + 3 /* AutoImportProvider */, + hostProject.projectService, + documentRegistry, + /*hasExplicitListOfFiles*/ + false, + /*lastFileExceededProgramSize*/ + void 0, + compilerOptions, + /*compileOnSaveEnabled*/ + false, + hostProject.getWatchOptions(), + hostProject.projectService.host, + hostProject.currentDirectory + ); + this.hostProject = hostProject; + this.rootFileNames = initialRootNames; + this.useSourceOfProjectReferenceRedirect = maybeBind(this.hostProject, this.hostProject.useSourceOfProjectReferenceRedirect); + this.getParsedCommandLine = maybeBind(this.hostProject, this.hostProject.getParsedCommandLine); + } + /** @internal */ + static getRootFileNames(dependencySelection, hostProject, host, compilerOptions) { + var _a, _b; + if (!dependencySelection) { + return emptyArray; + } + const program = hostProject.getCurrentProgram(); + if (!program) { + return emptyArray; + } + const start = timestamp(); + let dependencyNames; + let rootNames; + const rootFileName = combinePaths(hostProject.currentDirectory, inferredTypesContainingFile); + const packageJsons = hostProject.getPackageJsonsForAutoImport(combinePaths(hostProject.currentDirectory, rootFileName)); + for (const packageJson of packageJsons) { + (_a = packageJson.dependencies) == null ? void 0 : _a.forEach((_, dependenyName) => addDependency(dependenyName)); + (_b = packageJson.peerDependencies) == null ? void 0 : _b.forEach((_, dependencyName) => addDependency(dependencyName)); + } + let dependenciesAdded = 0; + if (dependencyNames) { + const symlinkCache = hostProject.getSymlinkCache(); + for (const name of arrayFrom(dependencyNames.keys())) { + if (dependencySelection === 2 /* Auto */ && dependenciesAdded > this.maxDependencies) { + hostProject.log(`AutoImportProviderProject: attempted to add more than ${this.maxDependencies} dependencies. Aborting.`); + return emptyArray; + } + const packageJson = resolvePackageNameToPackageJson( + name, + hostProject.currentDirectory, + compilerOptions, + host, + program.getModuleResolutionCache() + ); + if (packageJson) { + const entrypoints = getRootNamesFromPackageJson(packageJson, program, symlinkCache); + if (entrypoints) { + rootNames = concatenate(rootNames, entrypoints); + dependenciesAdded += entrypoints.length ? 1 : 0; + continue; + } + } + const done = forEach([hostProject.currentDirectory, hostProject.getGlobalTypingsCacheLocation()], (directory) => { + if (directory) { + const typesPackageJson = resolvePackageNameToPackageJson( + `@types/${name}`, + directory, + compilerOptions, + host, + program.getModuleResolutionCache() + ); + if (typesPackageJson) { + const entrypoints = getRootNamesFromPackageJson(typesPackageJson, program, symlinkCache); + rootNames = concatenate(rootNames, entrypoints); + dependenciesAdded += (entrypoints == null ? void 0 : entrypoints.length) ? 1 : 0; + return true; + } + } + }); + if (done) + continue; + if (packageJson && compilerOptions.allowJs && compilerOptions.maxNodeModuleJsDepth) { + const entrypoints = getRootNamesFromPackageJson( + packageJson, + program, + symlinkCache, + /*resolveJs*/ + true + ); + rootNames = concatenate(rootNames, entrypoints); + dependenciesAdded += (entrypoints == null ? void 0 : entrypoints.length) ? 1 : 0; + } + } + } + if (rootNames == null ? void 0 : rootNames.length) { + hostProject.log(`AutoImportProviderProject: found ${rootNames.length} root files in ${dependenciesAdded} dependencies in ${timestamp() - start} ms`); + } + return rootNames || emptyArray; + function addDependency(dependency) { + if (!startsWith(dependency, "@types/")) { + (dependencyNames || (dependencyNames = /* @__PURE__ */ new Set())).add(dependency); + } + } + function getRootNamesFromPackageJson(packageJson, program2, symlinkCache, resolveJs) { + var _a2; + const entrypoints = getEntrypointsFromPackageJsonInfo( + packageJson, + compilerOptions, + host, + program2.getModuleResolutionCache(), + resolveJs + ); + if (entrypoints) { + const real = (_a2 = host.realpath) == null ? void 0 : _a2.call(host, packageJson.packageDirectory); + const realPath2 = real ? hostProject.toPath(real) : void 0; + const isSymlink = realPath2 && realPath2 !== hostProject.toPath(packageJson.packageDirectory); + if (isSymlink) { + symlinkCache.setSymlinkedDirectory(packageJson.packageDirectory, { + real: ensureTrailingDirectorySeparator(real), + realPath: ensureTrailingDirectorySeparator(realPath2) + }); + } + return mapDefined(entrypoints, (entrypoint) => { + const resolvedFileName = isSymlink ? entrypoint.replace(packageJson.packageDirectory, real) : entrypoint; + if (!program2.getSourceFile(resolvedFileName) && !(isSymlink && program2.getSourceFile(entrypoint))) { + return resolvedFileName; + } + }); + } + } + } + /** @internal */ + static create(dependencySelection, hostProject, host, documentRegistry) { + if (dependencySelection === 0 /* Off */) { + return void 0; + } + const compilerOptions = { + ...hostProject.getCompilerOptions(), + ...this.compilerOptionsOverrides + }; + const rootNames = this.getRootFileNames(dependencySelection, hostProject, host, compilerOptions); + if (!rootNames.length) { + return void 0; + } + return new _AutoImportProviderProject(hostProject, rootNames, documentRegistry, compilerOptions); + } + /** @internal */ + isEmpty() { + return !some(this.rootFileNames); + } + isOrphan() { + return true; + } + updateGraph() { + let rootFileNames = this.rootFileNames; + if (!rootFileNames) { + rootFileNames = _AutoImportProviderProject.getRootFileNames( + this.hostProject.includePackageJsonAutoImports(), + this.hostProject, + this.hostProject.getHostForAutoImportProvider(), + this.getCompilationSettings() + ); + } + this.projectService.setFileNamesOfAutpImportProviderOrAuxillaryProject(this, rootFileNames); + this.rootFileNames = rootFileNames; + const oldProgram = this.getCurrentProgram(); + const hasSameSetOfFiles = super.updateGraph(); + if (oldProgram && oldProgram !== this.getCurrentProgram()) { + this.hostProject.clearCachedExportInfoMap(); + } + return hasSameSetOfFiles; + } + /** @internal */ + scheduleInvalidateResolutionsOfFailedLookupLocations() { + return; + } + hasRoots() { + var _a; + return !!((_a = this.rootFileNames) == null ? void 0 : _a.length); + } + markAsDirty() { + this.rootFileNames = void 0; + super.markAsDirty(); + } + getScriptFileNames() { + return this.rootFileNames || emptyArray; + } + getLanguageService() { + throw new Error("AutoImportProviderProject language service should never be used. To get the program, use `project.getCurrentProgram()`."); + } + /** @internal */ + onAutoImportProviderSettingsChanged() { + throw new Error("AutoImportProviderProject is an auto import provider; use `markAsDirty()` instead."); + } + /** @internal */ + onPackageJsonChange() { + throw new Error("package.json changes should be notified on an AutoImportProvider's host project"); + } + getHostForAutoImportProvider() { + throw new Error("AutoImportProviderProject cannot provide its own host; use `hostProject.getModuleResolutionHostForAutomImportProvider()` instead."); + } + getProjectReferences() { + return this.hostProject.getProjectReferences(); + } + /** @internal */ + includePackageJsonAutoImports() { + return 0 /* Off */; + } + /** @internal */ + getSymlinkCache() { + return this.hostProject.getSymlinkCache(); + } + /** @internal */ + getModuleResolutionCache() { + var _a; + return (_a = this.hostProject.getCurrentProgram()) == null ? void 0 : _a.getModuleResolutionCache(); + } + }; + /** @internal */ + _AutoImportProviderProject.maxDependencies = 10; + /** @internal */ + _AutoImportProviderProject.compilerOptionsOverrides = { + diagnostics: false, + skipLibCheck: true, + sourceMap: false, + types: emptyArray, + lib: emptyArray, + noLib: true + }; + AutoImportProviderProject = _AutoImportProviderProject; + ConfiguredProject2 = class extends Project3 { + /** @internal */ + constructor(configFileName, canonicalConfigFilePath, projectService, documentRegistry, cachedDirectoryStructureHost) { + super( + configFileName, + 1 /* Configured */, + projectService, + documentRegistry, + /*hasExplicitListOfFiles*/ + false, + /*lastFileExceededProgramSize*/ + void 0, + /*compilerOptions*/ + {}, + /*compileOnSaveEnabled*/ + false, + /*watchOptions*/ + void 0, + cachedDirectoryStructureHost, + getDirectoryPath(configFileName) + ); + this.canonicalConfigFilePath = canonicalConfigFilePath; + /** @internal */ + this.openFileWatchTriggered = /* @__PURE__ */ new Map(); + /** @internal */ + this.canConfigFileJsonReportNoInputFiles = false; + /** Ref count to the project when opened from external project */ + this.externalProjectRefCount = 0; + /** @internal */ + this.isInitialLoadPending = returnTrue; + /** @internal */ + this.sendLoadingProjectFinish = false; + } + /** @internal */ + setCompilerHost(host) { + this.compilerHost = host; + } + /** @internal */ + getCompilerHost() { + return this.compilerHost; + } + /** @internal */ + useSourceOfProjectReferenceRedirect() { + return this.languageServiceEnabled; + } + /** @internal */ + getParsedCommandLine(fileName) { + const configFileName = asNormalizedPath(normalizePath(fileName)); + const canonicalConfigFilePath = asNormalizedPath(this.projectService.toCanonicalFileName(configFileName)); + let configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo) { + this.projectService.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: this.projectService.host.fileExists(configFileName) }); + } + this.projectService.ensureParsedConfigUptoDate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, this); + if (this.languageServiceEnabled && this.projectService.serverMode === 0 /* Semantic */) { + this.projectService.watchWildcards(configFileName, configFileExistenceInfo, this); + } + return configFileExistenceInfo.exists ? configFileExistenceInfo.config.parsedCommandLine : void 0; + } + /** @internal */ + onReleaseParsedCommandLine(fileName) { + this.releaseParsedConfig(asNormalizedPath(this.projectService.toCanonicalFileName(asNormalizedPath(normalizePath(fileName))))); + } + /** @internal */ + releaseParsedConfig(canonicalConfigFilePath) { + this.projectService.stopWatchingWildCards(canonicalConfigFilePath, this); + this.projectService.releaseParsedConfig(canonicalConfigFilePath, this); + } + /** + * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph + * @returns: true if set of files in the project stays the same and false - otherwise. + */ + updateGraph() { + const isInitialLoad = this.isInitialLoadPending(); + this.isInitialLoadPending = returnFalse; + const updateLevel = this.pendingUpdateLevel; + this.pendingUpdateLevel = 0 /* Update */; + let result; + switch (updateLevel) { + case 1 /* RootNamesAndUpdate */: + this.openFileWatchTriggered.clear(); + result = this.projectService.reloadFileNamesOfConfiguredProject(this); + break; + case 2 /* Full */: + this.openFileWatchTriggered.clear(); + const reason = Debug.checkDefined(this.pendingUpdateReason); + this.pendingUpdateReason = void 0; + this.projectService.reloadConfiguredProject( + this, + reason, + isInitialLoad, + /*clearSemanticCache*/ + false + ); + result = true; + break; + default: + result = super.updateGraph(); + } + this.compilerHost = void 0; + this.projectService.sendProjectLoadingFinishEvent(this); + this.projectService.sendProjectTelemetry(this); + return result; + } + /** @internal */ + getCachedDirectoryStructureHost() { + return this.directoryStructureHost; + } + getConfigFilePath() { + return asNormalizedPath(this.getProjectName()); + } + getProjectReferences() { + return this.projectReferences; + } + updateReferences(refs) { + this.projectReferences = refs; + this.potentialProjectReferences = void 0; + } + /** @internal */ + setPotentialProjectReference(canonicalConfigPath) { + Debug.assert(this.isInitialLoadPending()); + (this.potentialProjectReferences || (this.potentialProjectReferences = /* @__PURE__ */ new Set())).add(canonicalConfigPath); + } + /** @internal */ + getResolvedProjectReferenceToRedirect(fileName) { + const program = this.getCurrentProgram(); + return program && program.getResolvedProjectReferenceToRedirect(fileName); + } + /** @internal */ + forEachResolvedProjectReference(cb) { + var _a; + return (_a = this.getCurrentProgram()) == null ? void 0 : _a.forEachResolvedProjectReference(cb); + } + /** @internal */ + enablePluginsWithOptions(options) { + var _a; + this.plugins.length = 0; + if (!((_a = options.plugins) == null ? void 0 : _a.length) && !this.projectService.globalPlugins.length) + return; + const host = this.projectService.host; + if (!host.require && !host.importPlugin) { + this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); + return; + } + const searchPaths = this.getGlobalPluginSearchPaths(); + if (this.projectService.allowLocalPluginLoads) { + const local = getDirectoryPath(this.canonicalConfigFilePath); + this.projectService.logger.info(`Local plugin loading enabled; adding ${local} to search paths`); + searchPaths.unshift(local); + } + if (options.plugins) { + for (const pluginConfigEntry of options.plugins) { + this.enablePlugin(pluginConfigEntry, searchPaths); + } + } + return this.enableGlobalPlugins(options); + } + /** + * Get the errors that dont have any file name associated + */ + getGlobalProjectErrors() { + return filter(this.projectErrors, (diagnostic) => !diagnostic.file) || emptyArray2; + } + /** + * Get all the project errors + */ + getAllProjectErrors() { + return this.projectErrors || emptyArray2; + } + setProjectErrors(projectErrors) { + this.projectErrors = projectErrors; + } + close() { + this.projectService.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => this.releaseParsedConfig(canonicalConfigFilePath)); + this.projectErrors = void 0; + this.openFileWatchTriggered.clear(); + this.compilerHost = void 0; + super.close(); + } + /** @internal */ + addExternalProjectReference() { + this.externalProjectRefCount++; + } + /** @internal */ + deleteExternalProjectReference() { + this.externalProjectRefCount--; + } + /** @internal */ + isSolution() { + return this.getRootFilesMap().size === 0 && !this.canConfigFileJsonReportNoInputFiles; + } + /** + * Find the configured project from the project references in project which contains the info directly + * + * @internal + */ + getDefaultChildProjectFromProjectWithReferences(info) { + return forEachResolvedProjectReferenceProject( + this, + info.path, + (child) => projectContainsInfoDirectly(child, info) ? child : void 0, + 0 /* Find */ + ); + } + /** + * Returns true if the project is needed by any of the open script info/external project + * + * @internal + */ + hasOpenRef() { + var _a; + if (!!this.externalProjectRefCount) { + return true; + } + if (this.isClosed()) { + return false; + } + const configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(this.canonicalConfigFilePath); + if (this.projectService.hasPendingProjectUpdate(this)) { + return !!((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.size); + } + return !!configFileExistenceInfo.openFilesImpactedByConfigFile && forEachEntry( + configFileExistenceInfo.openFilesImpactedByConfigFile, + (_value, infoPath) => { + const info = this.projectService.getScriptInfoForPath(infoPath); + return this.containsScriptInfo(info) || !!forEachResolvedProjectReferenceProject( + this, + info.path, + (child) => child.containsScriptInfo(info), + 0 /* Find */ + ); + } + ) || false; + } + /** @internal */ + hasExternalProjectRef() { + return !!this.externalProjectRefCount; + } + getEffectiveTypeRoots() { + return getEffectiveTypeRoots(this.getCompilationSettings(), this) || []; + } + /** @internal */ + updateErrorOnNoInputFiles(fileNames) { + updateErrorForNoInputFiles(fileNames, this.getConfigFilePath(), this.getCompilerOptions().configFile.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles); + } + }; + ExternalProject2 = class extends Project3 { + /** @internal */ + constructor(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, watchOptions) { + super( + externalProjectName, + 2 /* External */, + projectService, + documentRegistry, + /*hasExplicitListOfFiles*/ + true, + lastFileExceededProgramSize, + compilerOptions, + compileOnSaveEnabled, + watchOptions, + projectService.host, + getDirectoryPath(projectFilePath || normalizeSlashes(externalProjectName)) + ); + this.externalProjectName = externalProjectName; + this.compileOnSaveEnabled = compileOnSaveEnabled; + this.excludedFiles = []; + this.enableGlobalPlugins(this.getCompilerOptions()); + } + updateGraph() { + const result = super.updateGraph(); + this.projectService.sendProjectTelemetry(this); + return result; + } + getExcludedFiles() { + return this.excludedFiles; + } + }; + } + }); + + // src/server/editorServices.ts + function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) { + const map2 = /* @__PURE__ */ new Map(); + for (const option of commandLineOptions) { + if (typeof option.type === "object") { + const optionMap = option.type; + optionMap.forEach((value) => { + Debug.assert(typeof value === "number"); + }); + map2.set(option.name, optionMap); + } + } + return map2; + } + function convertFormatOptions(protocolOptions) { + if (isString(protocolOptions.indentStyle)) { + protocolOptions.indentStyle = indentStyle.get(protocolOptions.indentStyle.toLowerCase()); + Debug.assert(protocolOptions.indentStyle !== void 0); + } + return protocolOptions; + } + function convertCompilerOptions(protocolOptions) { + compilerOptionConverters.forEach((mappedValues, id) => { + const propertyValue = protocolOptions[id]; + if (isString(propertyValue)) { + protocolOptions[id] = mappedValues.get(propertyValue.toLowerCase()); + } + }); + return protocolOptions; + } + function convertWatchOptions(protocolOptions, currentDirectory) { + let watchOptions; + let errors; + optionsForWatch.forEach((option) => { + const propertyValue = protocolOptions[option.name]; + if (propertyValue === void 0) + return; + const mappedValues = watchOptionsConverters.get(option.name); + (watchOptions || (watchOptions = {}))[option.name] = mappedValues ? isString(propertyValue) ? mappedValues.get(propertyValue.toLowerCase()) : propertyValue : convertJsonOption(option, propertyValue, currentDirectory || "", errors || (errors = [])); + }); + return watchOptions && { watchOptions, errors }; + } + function convertTypeAcquisition(protocolOptions) { + let result; + typeAcquisitionDeclarations.forEach((option) => { + const propertyValue = protocolOptions[option.name]; + if (propertyValue === void 0) + return; + (result || (result = {}))[option.name] = propertyValue; + }); + return result; + } + function tryConvertScriptKindName(scriptKindName) { + return isString(scriptKindName) ? convertScriptKindName(scriptKindName) : scriptKindName; + } + function convertScriptKindName(scriptKindName) { + switch (scriptKindName) { + case "JS": + return 1 /* JS */; + case "JSX": + return 2 /* JSX */; + case "TS": + return 3 /* TS */; + case "TSX": + return 4 /* TSX */; + default: + return 0 /* Unknown */; + } + } + function convertUserPreferences(preferences) { + const { lazyConfiguredProjectsFromExternalProject, ...userPreferences } = preferences; + return userPreferences; + } + function findProjectByName(projectName, projects) { + for (const proj of projects) { + if (proj.getProjectName() === projectName) { + return proj; + } + } + } + function isOpenScriptInfo(infoOrFileNameOrConfig) { + return !!infoOrFileNameOrConfig.containingProjects; + } + function isAncestorConfigFileInfo(infoOrFileNameOrConfig) { + return !!infoOrFileNameOrConfig.configFileInfo; + } + function forEachResolvedProjectReferenceProject(project, fileName, cb, projectReferenceProjectLoadKind, reason) { + var _a; + const resolvedRefs = (_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences(); + if (!resolvedRefs) + return void 0; + let seenResolvedRefs; + const possibleDefaultRef = fileName ? project.getResolvedProjectReferenceToRedirect(fileName) : void 0; + if (possibleDefaultRef) { + const configFileName = toNormalizedPath(possibleDefaultRef.sourceFile.fileName); + const child = project.projectService.findConfiguredProjectByProjectName(configFileName); + if (child) { + const result = cb(child); + if (result) + return result; + } else if (projectReferenceProjectLoadKind !== 0 /* Find */) { + seenResolvedRefs = /* @__PURE__ */ new Map(); + const result = forEachResolvedProjectReferenceProjectWorker( + resolvedRefs, + project.getCompilerOptions(), + (ref, loadKind) => possibleDefaultRef === ref ? callback(ref, loadKind) : void 0, + projectReferenceProjectLoadKind, + project.projectService, + seenResolvedRefs + ); + if (result) + return result; + seenResolvedRefs.clear(); + } + } + return forEachResolvedProjectReferenceProjectWorker( + resolvedRefs, + project.getCompilerOptions(), + (ref, loadKind) => possibleDefaultRef !== ref ? callback(ref, loadKind) : void 0, + projectReferenceProjectLoadKind, + project.projectService, + seenResolvedRefs + ); + function callback(ref, loadKind) { + const configFileName = toNormalizedPath(ref.sourceFile.fileName); + const child = project.projectService.findConfiguredProjectByProjectName(configFileName) || (loadKind === 0 /* Find */ ? void 0 : loadKind === 1 /* FindCreate */ ? project.projectService.createConfiguredProject(configFileName) : loadKind === 2 /* FindCreateLoad */ ? project.projectService.createAndLoadConfiguredProject(configFileName, reason) : Debug.assertNever(loadKind)); + return child && cb(child); + } + } + function forEachResolvedProjectReferenceProjectWorker(resolvedProjectReferences, parentOptions, cb, projectReferenceProjectLoadKind, projectService, seenResolvedRefs) { + const loadKind = parentOptions.disableReferencedProjectLoad ? 0 /* Find */ : projectReferenceProjectLoadKind; + return forEach(resolvedProjectReferences, (ref) => { + if (!ref) + return void 0; + const configFileName = toNormalizedPath(ref.sourceFile.fileName); + const canonicalPath = projectService.toCanonicalFileName(configFileName); + const seenValue = seenResolvedRefs == null ? void 0 : seenResolvedRefs.get(canonicalPath); + if (seenValue !== void 0 && seenValue >= loadKind) { + return void 0; + } + const result = cb(ref, loadKind); + if (result) { + return result; + } + (seenResolvedRefs || (seenResolvedRefs = /* @__PURE__ */ new Map())).set(canonicalPath, loadKind); + return ref.references && forEachResolvedProjectReferenceProjectWorker(ref.references, ref.commandLine.options, cb, loadKind, projectService, seenResolvedRefs); + }); + } + function forEachPotentialProjectReference(project, cb) { + return project.potentialProjectReferences && forEachKey(project.potentialProjectReferences, cb); + } + function forEachAnyProjectReferenceKind(project, cb, cbProjectRef, cbPotentialProjectRef) { + return project.getCurrentProgram() ? project.forEachResolvedProjectReference(cb) : project.isInitialLoadPending() ? forEachPotentialProjectReference(project, cbPotentialProjectRef) : forEach(project.getProjectReferences(), cbProjectRef); + } + function callbackRefProject(project, cb, refPath) { + const refProject = refPath && project.projectService.configuredProjects.get(refPath); + return refProject && cb(refProject); + } + function forEachReferencedProject(project, cb) { + return forEachAnyProjectReferenceKind( + project, + (resolvedRef) => callbackRefProject(project, cb, resolvedRef.sourceFile.path), + (projectRef) => callbackRefProject(project, cb, project.toPath(resolveProjectReferencePath(projectRef))), + (potentialProjectRef) => callbackRefProject(project, cb, potentialProjectRef) + ); + } + function getDetailWatchInfo(watchType, project) { + return `${isString(project) ? `Config: ${project} ` : project ? `Project: ${project.getProjectName()} ` : ""}WatchType: ${watchType}`; + } + function isScriptInfoWatchedFromNodeModules(info) { + return !info.isScriptOpen() && info.mTime !== void 0; + } + function projectContainsInfoDirectly(project, info) { + return project.containsScriptInfo(info) && !project.isSourceOfProjectReferenceRedirect(info.path); + } + function updateProjectIfDirty(project) { + project.invalidateResolutionsOfFailedLookupLocations(); + return project.dirty && project.updateGraph(); + } + function setProjectOptionsUsed(project) { + if (isConfiguredProject(project)) { + project.projectOptions = true; + } + } + function createProjectNameFactoryWithCounter(nameFactory) { + let nextId = 1; + return () => nameFactory(nextId++); + } + function getHostWatcherMap() { + return { idToCallbacks: /* @__PURE__ */ new Map(), pathToId: /* @__PURE__ */ new Map() }; + } + function createWatchFactoryHostUsingWatchEvents(service, canUseWatchEvents) { + if (!canUseWatchEvents || !service.eventHandler || !service.session) + return void 0; + const watchedFiles = getHostWatcherMap(); + const watchedDirectories = getHostWatcherMap(); + const watchedDirectoriesRecursive = getHostWatcherMap(); + let ids = 1; + service.session.addProtocolHandler("watchChange" /* WatchChange */, (req) => { + onWatchChange(req.arguments); + return { responseRequired: false }; + }); + return { + watchFile: watchFile2, + watchDirectory, + getCurrentDirectory: () => service.host.getCurrentDirectory(), + useCaseSensitiveFileNames: service.host.useCaseSensitiveFileNames + }; + function watchFile2(path, callback) { + return getOrCreateFileWatcher( + watchedFiles, + path, + callback, + (id) => ({ eventName: CreateFileWatcherEvent, data: { id, path } }) + ); + } + function watchDirectory(path, callback, recursive) { + return getOrCreateFileWatcher( + recursive ? watchedDirectoriesRecursive : watchedDirectories, + path, + callback, + (id) => ({ eventName: CreateDirectoryWatcherEvent, data: { id, path, recursive: !!recursive } }) + ); + } + function getOrCreateFileWatcher({ pathToId, idToCallbacks }, path, callback, event) { + const key = service.toPath(path); + let id = pathToId.get(key); + if (!id) + pathToId.set(key, id = ids++); + let callbacks = idToCallbacks.get(id); + if (!callbacks) { + idToCallbacks.set(id, callbacks = /* @__PURE__ */ new Set()); + service.eventHandler(event(id)); + } + callbacks.add(callback); + return { + close() { + const callbacks2 = idToCallbacks.get(id); + if (!(callbacks2 == null ? void 0 : callbacks2.delete(callback))) + return; + if (callbacks2.size) + return; + idToCallbacks.delete(id); + pathToId.delete(key); + service.eventHandler({ eventName: CloseFileWatcherEvent, data: { id } }); + } + }; + } + function onWatchChange({ id, path, eventType }) { + onFileWatcherCallback(id, path, eventType); + onDirectoryWatcherCallback(watchedDirectories, id, path, eventType); + onDirectoryWatcherCallback(watchedDirectoriesRecursive, id, path, eventType); + } + function onFileWatcherCallback(id, eventPath, eventType) { + var _a; + (_a = watchedFiles.idToCallbacks.get(id)) == null ? void 0 : _a.forEach((callback) => { + const eventKind = eventType === "create" ? 0 /* Created */ : eventType === "delete" ? 2 /* Deleted */ : 1 /* Changed */; + callback(eventPath, eventKind); + }); + } + function onDirectoryWatcherCallback({ idToCallbacks }, id, eventPath, eventType) { + var _a; + if (eventType === "update") + return; + (_a = idToCallbacks.get(id)) == null ? void 0 : _a.forEach((callback) => { + callback(eventPath); + }); + } + } + function createIncompleteCompletionsCache() { + let info; + return { + get() { + return info; + }, + set(newInfo) { + info = newInfo; + }, + clear() { + info = void 0; + } + }; + } + function isConfigFile(config) { + return config.kind !== void 0; + } + function printProjectWithoutFileNames(project) { + project.print( + /*writeProjectFileNames*/ + false, + /*writeFileExplaination*/ + false, + /*writeFileVersionAndText*/ + false + ); + } + var maxProgramSizeForNonTsFiles, maxFileSize, ProjectsUpdatedInBackgroundEvent, ProjectLoadingStartEvent, ProjectLoadingFinishEvent, LargeFileReferencedEvent, ConfigFileDiagEvent, ProjectLanguageServiceStateEvent, ProjectInfoTelemetryEvent, OpenFileInfoTelemetryEvent, CreateFileWatcherEvent, CreateDirectoryWatcherEvent, CloseFileWatcherEvent, ensureProjectForOpenFileSchedule, compilerOptionConverters, watchOptionsConverters, indentStyle, defaultTypeSafeList, fileNamePropertyReader, externalFilePropertyReader, noopConfigFileWatcher, ProjectReferenceProjectLoadKind, _ProjectService, ProjectService3; + var init_editorServices = __esm({ + "src/server/editorServices.ts"() { + "use strict"; + init_ts7(); + init_ts_server3(); + init_protocol(); + maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + maxFileSize = 4 * 1024 * 1024; + ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + ProjectLoadingStartEvent = "projectLoadingStart"; + ProjectLoadingFinishEvent = "projectLoadingFinish"; + LargeFileReferencedEvent = "largeFileReferenced"; + ConfigFileDiagEvent = "configFileDiag"; + ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; + ProjectInfoTelemetryEvent = "projectInfo"; + OpenFileInfoTelemetryEvent = "openFileInfo"; + CreateFileWatcherEvent = "createFileWatcher"; + CreateDirectoryWatcherEvent = "createDirectoryWatcher"; + CloseFileWatcherEvent = "closeFileWatcher"; + ensureProjectForOpenFileSchedule = "*ensureProjectForOpenFiles*"; + compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(optionDeclarations); + watchOptionsConverters = prepareConvertersForEnumLikeCompilerOptions(optionsForWatch); + indentStyle = new Map(Object.entries({ + none: 0 /* None */, + block: 1 /* Block */, + smart: 2 /* Smart */ + })); + 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, + types: ["jquery"] + }, + "WinJS": { + // e.g. c:/temp/UWApp1/lib/winjs-4.0.1/js/base.js + match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i, + // If the winjs/base.js file is found.. + exclude: [["^", 1, "/.*"]], + // ..then exclude all files under the winjs folder + types: ["winjs"] + // And fetch the @types package for WinJS + }, + "Kendo": { + // e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js + match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i, + exclude: [["^", 1, "/.*"]], + types: ["kendo-ui"] + }, + "Office Nuget": { + // e.g. /scripts/Office/1/excel-15.debug.js + match: /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i, + // Office NuGet package is installed under a "1/office" folder + exclude: [["^", 1, "/.*"]], + // Exclude that whole folder if the file indicated above is found in it + types: ["office"] + // @types package to fetch instead + }, + "References": { + match: /^(.*\/_references\.js)$/i, + exclude: [["^", 1, "$"]] + } + }; + fileNamePropertyReader = { + getFileName: (x) => x, + getScriptKind: (fileName, extraFileExtensions) => { + let result; + if (extraFileExtensions) { + const fileExtension = getAnyExtensionFromPath(fileName); + if (fileExtension) { + some(extraFileExtensions, (info) => { + if (info.extension === fileExtension) { + result = info.scriptKind; + return true; + } + return false; + }); + } + } + return result; + }, + hasMixedContent: (fileName, extraFileExtensions) => some(extraFileExtensions, (ext) => ext.isMixedContent && fileExtensionIs(fileName, ext.extension)) + }; + externalFilePropertyReader = { + getFileName: (x) => x.fileName, + getScriptKind: (x) => tryConvertScriptKindName(x.scriptKind), + // TODO: GH#18217 + hasMixedContent: (x) => !!x.hasMixedContent + }; + noopConfigFileWatcher = { close: noop }; + ProjectReferenceProjectLoadKind = /* @__PURE__ */ ((ProjectReferenceProjectLoadKind2) => { + ProjectReferenceProjectLoadKind2[ProjectReferenceProjectLoadKind2["Find"] = 0] = "Find"; + ProjectReferenceProjectLoadKind2[ProjectReferenceProjectLoadKind2["FindCreate"] = 1] = "FindCreate"; + ProjectReferenceProjectLoadKind2[ProjectReferenceProjectLoadKind2["FindCreateLoad"] = 2] = "FindCreateLoad"; + return ProjectReferenceProjectLoadKind2; + })(ProjectReferenceProjectLoadKind || {}); + _ProjectService = class _ProjectService { + constructor(opts) { + /** + * Container of all known scripts + * + * @internal + */ + this.filenameToScriptInfo = /* @__PURE__ */ new Map(); + this.nodeModulesWatchers = /* @__PURE__ */ new Map(); + /** + * Contains all the deleted script info's version information so that + * it does not reset when creating script info again + * (and could have potentially collided with version where contents mismatch) + */ + this.filenameToScriptInfoVersion = /* @__PURE__ */ new Map(); + // Set of all '.js' files ever opened. + this.allJsFilesForOpenFileTelemetry = /* @__PURE__ */ new Map(); + /** + * maps external project file name to list of config files that were the part of this project + */ + this.externalProjectToConfiguredProjectMap = /* @__PURE__ */ new Map(); + /** + * external projects (configuration and list of root files is not controlled by tsserver) + */ + this.externalProjects = []; + /** + * projects built from openFileRoots + */ + this.inferredProjects = []; + /** + * projects specified by a tsconfig.json file + */ + this.configuredProjects = /* @__PURE__ */ new Map(); + /** @internal */ + this.newInferredProjectName = createProjectNameFactoryWithCounter(makeInferredProjectName); + /** @internal */ + this.newAutoImportProviderProjectName = createProjectNameFactoryWithCounter(makeAutoImportProviderProjectName); + /** @internal */ + this.newAuxiliaryProjectName = createProjectNameFactoryWithCounter(makeAuxiliaryProjectName); + /** + * Open files: with value being project root path, and key being Path of the file that is open + */ + this.openFiles = /* @__PURE__ */ new Map(); + /** @internal */ + this.configFileForOpenFiles = /* @__PURE__ */ new Map(); + /** + * Map of open files that are opened without complete path but have projectRoot as current directory + */ + this.openFilesWithNonRootedDiskPath = /* @__PURE__ */ new Map(); + this.compilerOptionsForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map(); + this.watchOptionsForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map(); + this.typeAcquisitionForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map(); + /** + * Project size for configured or external projects + */ + this.projectToSizeMap = /* @__PURE__ */ new Map(); + /** + * This is a map of config file paths existence that doesnt need query to disk + * - The entry can be present because there is inferred project that needs to watch addition of config file to directory + * In this case the exists could be true/false based on config file is present or not + * - Or it is present if we have configured project open with config file at that location + * In this case the exists property is always true + * + * @internal + */ + this.configFileExistenceInfoCache = /* @__PURE__ */ new Map(); + this.safelist = defaultTypeSafeList; + this.legacySafelist = /* @__PURE__ */ new Map(); + this.pendingProjectUpdates = /* @__PURE__ */ new Map(); + /** @internal */ + this.pendingEnsureProjectForOpenFiles = false; + /** Tracks projects that we have already sent telemetry for. */ + this.seenProjects = /* @__PURE__ */ new Map(); + /** @internal */ + this.sharedExtendedConfigFileWatchers = /* @__PURE__ */ new Map(); + /** @internal */ + this.extendedConfigCache = /* @__PURE__ */ new Map(); + /** @internal */ + this.verifyDocumentRegistry = noop; + /** @internal */ + this.verifyProgram = noop; + /** @internal */ + this.onProjectCreation = noop; + var _a; + this.host = opts.host; + this.logger = opts.logger; + this.cancellationToken = opts.cancellationToken; + this.useSingleInferredProject = opts.useSingleInferredProject; + this.useInferredProjectPerProjectRoot = opts.useInferredProjectPerProjectRoot; + this.typingsInstaller = opts.typingsInstaller || nullTypingsInstaller; + this.throttleWaitMilliseconds = opts.throttleWaitMilliseconds; + this.eventHandler = opts.eventHandler; + this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; + this.globalPlugins = opts.globalPlugins || emptyArray2; + this.pluginProbeLocations = opts.pluginProbeLocations || emptyArray2; + this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; + this.typesMapLocation = opts.typesMapLocation === void 0 ? combinePaths(getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation; + this.session = opts.session; + this.jsDocParsingMode = opts.jsDocParsingMode; + if (opts.serverMode !== void 0) { + this.serverMode = opts.serverMode; + } else { + this.serverMode = 0 /* Semantic */; + } + if (this.host.realpath) { + this.realpathToScriptInfos = createMultiMap(); + } + this.currentDirectory = toNormalizedPath(this.host.getCurrentDirectory()); + this.toCanonicalFileName = createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); + this.globalCacheLocationDirectoryPath = this.typingsInstaller.globalTypingsCacheLocation ? ensureTrailingDirectorySeparator(this.toPath(this.typingsInstaller.globalTypingsCacheLocation)) : void 0; + this.throttledOperations = new ThrottledOperations(this.host, this.logger); + if (this.typesMapLocation) { + this.loadTypesMap(); + } else { + this.logger.info("No types map provided; using the default"); + } + this.typingsInstaller.attach(this); + this.typingsCache = new TypingsCache(this.typingsInstaller); + this.hostConfiguration = { + formatCodeOptions: getDefaultFormatCodeSettings(this.host.newLine), + preferences: emptyOptions, + hostInfo: "Unknown host", + extraFileExtensions: [] + }; + this.documentRegistry = createDocumentRegistryInternal(this.host.useCaseSensitiveFileNames, this.currentDirectory, this.jsDocParsingMode, this); + const watchLogLevel = this.logger.hasLevel(3 /* verbose */) ? 2 /* Verbose */ : this.logger.loggingEnabled() ? 1 /* TriggerOnly */ : 0 /* None */; + const log = watchLogLevel !== 0 /* None */ ? (s) => this.logger.info(s) : noop; + this.packageJsonCache = createPackageJsonCache(this); + this.watchFactory = this.serverMode !== 0 /* Semantic */ ? { + watchFile: returnNoopFileWatcher, + watchDirectory: returnNoopFileWatcher + } : getWatchFactory( + createWatchFactoryHostUsingWatchEvents(this, opts.canUseWatchEvents) || this.host, + watchLogLevel, + log, + getDetailWatchInfo + ); + (_a = opts.incrementalVerifier) == null ? void 0 : _a.call(opts, this); + } + toPath(fileName) { + return toPath(fileName, this.currentDirectory, this.toCanonicalFileName); + } + /** @internal */ + getExecutingFilePath() { + return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath()); + } + /** @internal */ + getNormalizedAbsolutePath(fileName) { + return getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); + } + /** @internal */ + setDocument(key, path, sourceFile) { + const info = Debug.checkDefined(this.getScriptInfoForPath(path)); + info.cacheSourceFile = { key, sourceFile }; + } + /** @internal */ + getDocument(key, path) { + const info = this.getScriptInfoForPath(path); + return info && info.cacheSourceFile && info.cacheSourceFile.key === key ? info.cacheSourceFile.sourceFile : void 0; + } + /** @internal */ + ensureInferredProjectsUpToDate_TestOnly() { + this.ensureProjectStructuresUptoDate(); + } + /** @internal */ + getCompilerOptionsForInferredProjects() { + return this.compilerOptionsForInferredProjects; + } + /** @internal */ + onUpdateLanguageServiceStateForProject(project, languageServiceEnabled) { + if (!this.eventHandler) { + return; + } + const event = { + eventName: ProjectLanguageServiceStateEvent, + data: { project, languageServiceEnabled } + }; + this.eventHandler(event); + } + loadTypesMap() { + try { + const fileContent = this.host.readFile(this.typesMapLocation); + if (fileContent === void 0) { + this.logger.info(`Provided types map file "${this.typesMapLocation}" doesn't exist`); + return; + } + const raw = JSON.parse(fileContent); + for (const k of Object.keys(raw.typesMap)) { + raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i"); + } + this.safelist = raw.typesMap; + for (const key in raw.simpleMap) { + if (hasProperty(raw.simpleMap, key)) { + this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase()); + } + } + } catch (e) { + this.logger.info(`Error loading types map: ${e}`); + this.safelist = defaultTypeSafeList; + this.legacySafelist.clear(); + } + } + // eslint-disable-line @typescript-eslint/unified-signatures + updateTypingsForProject(response) { + const project = this.findProject(response.projectName); + if (!project) { + return; + } + switch (response.kind) { + case ActionSet: + project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings)); + return; + case ActionInvalidate: + this.typingsCache.enqueueInstallTypingsForProject( + project, + project.lastCachedUnresolvedImportsList, + /*forceRefresh*/ + true + ); + return; + } + } + /** @internal */ + watchTypingLocations(response) { + var _a; + (_a = this.findProject(response.projectName)) == null ? void 0 : _a.watchTypingLocations(response.files); + } + /** @internal */ + delayEnsureProjectForOpenFiles() { + if (!this.openFiles.size) + return; + this.pendingEnsureProjectForOpenFiles = true; + this.throttledOperations.schedule( + ensureProjectForOpenFileSchedule, + /*delay*/ + 2500, + () => { + if (this.pendingProjectUpdates.size !== 0) { + this.delayEnsureProjectForOpenFiles(); + } else { + if (this.pendingEnsureProjectForOpenFiles) { + this.ensureProjectForOpenFiles(); + this.sendProjectsUpdatedInBackgroundEvent(); + } + } + } + ); + } + delayUpdateProjectGraph(project) { + project.markAsDirty(); + if (isBackgroundProject(project)) + return; + const projectName = project.getProjectName(); + this.pendingProjectUpdates.set(projectName, project); + this.throttledOperations.schedule( + projectName, + /*delay*/ + 250, + () => { + if (this.pendingProjectUpdates.delete(projectName)) { + updateProjectIfDirty(project); + } + } + ); + } + /** @internal */ + hasPendingProjectUpdate(project) { + return this.pendingProjectUpdates.has(project.getProjectName()); + } + /** @internal */ + sendProjectsUpdatedInBackgroundEvent() { + if (!this.eventHandler) { + return; + } + const event = { + eventName: ProjectsUpdatedInBackgroundEvent, + data: { + openFiles: arrayFrom(this.openFiles.keys(), (path) => this.getScriptInfoForPath(path).fileName) + } + }; + this.eventHandler(event); + } + /** @internal */ + sendLargeFileReferencedEvent(file, fileSize) { + if (!this.eventHandler) { + return; + } + const event = { + eventName: LargeFileReferencedEvent, + data: { file, fileSize, maxFileSize } + }; + this.eventHandler(event); + } + /** @internal */ + sendProjectLoadingStartEvent(project, reason) { + if (!this.eventHandler) { + return; + } + project.sendLoadingProjectFinish = true; + const event = { + eventName: ProjectLoadingStartEvent, + data: { project, reason } + }; + this.eventHandler(event); + } + /** @internal */ + sendProjectLoadingFinishEvent(project) { + if (!this.eventHandler || !project.sendLoadingProjectFinish) { + return; + } + project.sendLoadingProjectFinish = false; + const event = { + eventName: ProjectLoadingFinishEvent, + data: { project } + }; + this.eventHandler(event); + } + /** @internal */ + sendPerformanceEvent(kind, durationMs) { + if (this.performanceEventHandler) { + this.performanceEventHandler({ kind, durationMs }); + } + } + /** @internal */ + delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project) { + this.delayUpdateProjectGraph(project); + this.delayEnsureProjectForOpenFiles(); + } + delayUpdateProjectGraphs(projects, clearSourceMapperCache) { + if (projects.length) { + for (const project of projects) { + if (clearSourceMapperCache) + project.clearSourceMapperCache(); + this.delayUpdateProjectGraph(project); + } + this.delayEnsureProjectForOpenFiles(); + } + } + setCompilerOptionsForInferredProjects(projectCompilerOptions, projectRootPath) { + Debug.assert(projectRootPath === void 0 || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled"); + const compilerOptions = convertCompilerOptions(projectCompilerOptions); + const watchOptions = convertWatchOptions(projectCompilerOptions, projectRootPath); + const typeAcquisition = convertTypeAcquisition(projectCompilerOptions); + compilerOptions.allowNonTsExtensions = true; + const canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath); + if (canonicalProjectRootPath) { + this.compilerOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, compilerOptions); + this.watchOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, watchOptions || false); + this.typeAcquisitionForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, typeAcquisition); + } else { + this.compilerOptionsForInferredProjects = compilerOptions; + this.watchOptionsForInferredProjects = watchOptions; + this.typeAcquisitionForInferredProjects = typeAcquisition; + } + for (const project of this.inferredProjects) { + if (canonicalProjectRootPath ? project.projectRootPath === canonicalProjectRootPath : !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) { + project.setCompilerOptions(compilerOptions); + project.setTypeAcquisition(typeAcquisition); + project.setWatchOptions(watchOptions == null ? void 0 : watchOptions.watchOptions); + project.setProjectErrors(watchOptions == null ? void 0 : watchOptions.errors); + project.compileOnSaveEnabled = compilerOptions.compileOnSave; + project.markAsDirty(); + this.delayUpdateProjectGraph(project); + } + } + this.delayEnsureProjectForOpenFiles(); + } + findProject(projectName) { + if (projectName === void 0) { + return void 0; + } + if (isInferredProjectName(projectName)) { + return findProjectByName(projectName, this.inferredProjects); + } + return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(toNormalizedPath(projectName)); + } + /** @internal */ + forEachProject(cb) { + this.externalProjects.forEach(cb); + this.configuredProjects.forEach(cb); + this.inferredProjects.forEach(cb); + } + /** @internal */ + forEachEnabledProject(cb) { + this.forEachProject((project) => { + if (!project.isOrphan() && project.languageServiceEnabled) { + cb(project); + } + }); + } + getDefaultProjectForFile(fileName, ensureProject) { + return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName); + } + /** @internal */ + tryGetDefaultProjectForFile(fileNameOrScriptInfo) { + const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo; + return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : void 0; + } + /** @internal */ + ensureDefaultProjectForFile(fileNameOrScriptInfo) { + return this.tryGetDefaultProjectForFile(fileNameOrScriptInfo) || this.doEnsureDefaultProjectForFile(fileNameOrScriptInfo); + } + doEnsureDefaultProjectForFile(fileNameOrScriptInfo) { + this.ensureProjectStructuresUptoDate(); + const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo; + return scriptInfo ? scriptInfo.getDefaultProject() : (this.logErrorForScriptInfoNotFound(isString(fileNameOrScriptInfo) ? fileNameOrScriptInfo : fileNameOrScriptInfo.fileName), Errors.ThrowNoProject()); + } + getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName) { + this.ensureProjectStructuresUptoDate(); + return this.getScriptInfo(uncheckedFileName); + } + /** + * Ensures the project structures are upto date + * This means, + * - we go through all the projects and update them if they are dirty + * - if updates reflect some change in structure or there was pending request to ensure projects for open files + * ensure that each open script info has project + */ + ensureProjectStructuresUptoDate() { + let hasChanges = this.pendingEnsureProjectForOpenFiles; + this.pendingProjectUpdates.clear(); + const updateGraph = (project) => { + hasChanges = updateProjectIfDirty(project) || hasChanges; + }; + this.externalProjects.forEach(updateGraph); + this.configuredProjects.forEach(updateGraph); + this.inferredProjects.forEach(updateGraph); + if (hasChanges) { + this.ensureProjectForOpenFiles(); + } + } + getFormatCodeOptions(file) { + const info = this.getScriptInfoForNormalizedPath(file); + return info && info.getFormatCodeSettings() || this.hostConfiguration.formatCodeOptions; + } + getPreferences(file) { + const info = this.getScriptInfoForNormalizedPath(file); + return { ...this.hostConfiguration.preferences, ...info && info.getPreferences() }; + } + getHostFormatCodeOptions() { + return this.hostConfiguration.formatCodeOptions; + } + getHostPreferences() { + return this.hostConfiguration.preferences; + } + onSourceFileChanged(info, eventKind) { + if (eventKind === 2 /* Deleted */) { + this.handleDeletedFile(info); + } else if (!info.isScriptOpen()) { + info.delayReloadNonMixedContentFile(); + this.delayUpdateProjectGraphs( + info.containingProjects, + /*clearSourceMapperCache*/ + false + ); + this.handleSourceMapProjects(info); + } + } + handleSourceMapProjects(info) { + if (info.sourceMapFilePath) { + if (isString(info.sourceMapFilePath)) { + const sourceMapFileInfo = this.getScriptInfoForPath(info.sourceMapFilePath); + this.delayUpdateSourceInfoProjects(sourceMapFileInfo && sourceMapFileInfo.sourceInfos); + } else { + this.delayUpdateSourceInfoProjects(info.sourceMapFilePath.sourceInfos); + } + } + this.delayUpdateSourceInfoProjects(info.sourceInfos); + if (info.declarationInfoPath) { + this.delayUpdateProjectsOfScriptInfoPath(info.declarationInfoPath); + } + } + delayUpdateSourceInfoProjects(sourceInfos) { + if (sourceInfos) { + sourceInfos.forEach((_value, path) => this.delayUpdateProjectsOfScriptInfoPath(path)); + } + } + delayUpdateProjectsOfScriptInfoPath(path) { + const info = this.getScriptInfoForPath(path); + if (info) { + this.delayUpdateProjectGraphs( + info.containingProjects, + /*clearSourceMapperCache*/ + true + ); + } + } + handleDeletedFile(info) { + this.stopWatchingScriptInfo(info); + if (!info.isScriptOpen()) { + this.deleteScriptInfo(info); + const containingProjects = info.containingProjects.slice(); + info.detachAllProjects(); + this.delayUpdateProjectGraphs( + containingProjects, + /*clearSourceMapperCache*/ + false + ); + this.handleSourceMapProjects(info); + info.closeSourceMapFileWatcher(); + if (info.declarationInfoPath) { + const declarationInfo = this.getScriptInfoForPath(info.declarationInfoPath); + if (declarationInfo) { + declarationInfo.sourceMapFilePath = void 0; + } + } + } + } + /** + * This is to watch whenever files are added or removed to the wildcard directories + * + * @internal + */ + watchWildcardDirectory(directory, flags, configFileName, config) { + return this.watchFactory.watchDirectory( + directory, + (fileOrDirectory) => { + const fileOrDirectoryPath = this.toPath(fileOrDirectory); + const fsResult = config.cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (getBaseFileName(fileOrDirectoryPath) === "package.json" && !isInsideNodeModules(fileOrDirectoryPath) && (fsResult && fsResult.fileExists || !fsResult && this.host.fileExists(fileOrDirectoryPath))) { + this.logger.info(`Config: ${configFileName} Detected new package.json: ${fileOrDirectory}`); + this.onAddPackageJson(fileOrDirectoryPath); + } + const configuredProjectForConfig = this.findConfiguredProjectByProjectName(configFileName); + if (isIgnoredFileFromWildCardWatching({ + watchedDirPath: directory, + fileOrDirectory, + fileOrDirectoryPath, + configFileName, + extraFileExtensions: this.hostConfiguration.extraFileExtensions, + currentDirectory: this.currentDirectory, + options: config.parsedCommandLine.options, + program: (configuredProjectForConfig == null ? void 0 : configuredProjectForConfig.getCurrentProgram()) || config.parsedCommandLine.fileNames, + useCaseSensitiveFileNames: this.host.useCaseSensitiveFileNames, + writeLog: (s) => this.logger.info(s), + toPath: (s) => this.toPath(s), + getScriptKind: configuredProjectForConfig ? (fileName) => configuredProjectForConfig.getScriptKind(fileName) : void 0 + })) + return; + if (config.updateLevel !== 2 /* Full */) + config.updateLevel = 1 /* RootNamesAndUpdate */; + config.projects.forEach((watchWildcardDirectories, projectCanonicalPath) => { + if (!watchWildcardDirectories) + return; + const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); + if (!project) + return; + const updateLevel = configuredProjectForConfig === project ? 1 /* RootNamesAndUpdate */ : 0 /* Update */; + if (project.pendingUpdateLevel !== void 0 && project.pendingUpdateLevel > updateLevel) + return; + if (this.openFiles.has(fileOrDirectoryPath)) { + const info = Debug.checkDefined(this.getScriptInfoForPath(fileOrDirectoryPath)); + if (info.isAttached(project)) { + const loadLevelToSet = Math.max(updateLevel, project.openFileWatchTriggered.get(fileOrDirectoryPath) || 0 /* Update */); + project.openFileWatchTriggered.set(fileOrDirectoryPath, loadLevelToSet); + } else { + project.pendingUpdateLevel = updateLevel; + this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + } + } else { + project.pendingUpdateLevel = updateLevel; + this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + } + }); + }, + flags, + this.getWatchOptionsFromProjectWatchOptions(config.parsedCommandLine.watchOptions), + WatchType.WildcardDirectory, + configFileName + ); + } + /** @internal */ + delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath, loadReason) { + const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!(configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config)) + return false; + let scheduledAnyProjectUpdate = false; + configFileExistenceInfo.config.updateLevel = 2 /* Full */; + configFileExistenceInfo.config.projects.forEach((_watchWildcardDirectories, projectCanonicalPath) => { + const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); + if (!project) + return; + scheduledAnyProjectUpdate = true; + if (projectCanonicalPath === canonicalConfigFilePath) { + if (project.isInitialLoadPending()) + return; + project.pendingUpdateLevel = 2 /* Full */; + project.pendingUpdateReason = loadReason; + this.delayUpdateProjectGraph(project); + } else { + project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(this.toPath(canonicalConfigFilePath)); + this.delayUpdateProjectGraph(project); + } + }); + return scheduledAnyProjectUpdate; + } + /** @internal */ + onConfigFileChanged(canonicalConfigFilePath, eventKind) { + var _a; + const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (eventKind === 2 /* Deleted */) { + configFileExistenceInfo.exists = false; + const project = ((_a = configFileExistenceInfo.config) == null ? void 0 : _a.projects.has(canonicalConfigFilePath)) ? this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath) : void 0; + if (project) + this.removeProject(project); + } else { + configFileExistenceInfo.exists = true; + } + this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath, "Change in config file detected"); + this.reloadConfiguredProjectForFiles( + configFileExistenceInfo.openFilesImpactedByConfigFile, + /*clearSemanticCache*/ + false, + /*delayReload*/ + true, + eventKind !== 2 /* Deleted */ ? identity : ( + // Reload open files if they are root of inferred project + returnTrue + ), + // Reload all the open files impacted by config file + "Change in config file detected" + ); + this.delayEnsureProjectForOpenFiles(); + } + removeProject(project) { + this.logger.info("`remove Project::"); + project.print( + /*writeProjectFileNames*/ + true, + /*writeFileExplaination*/ + true, + /*writeFileVersionAndText*/ + false + ); + project.close(); + if (Debug.shouldAssert(1 /* Normal */)) { + this.filenameToScriptInfo.forEach( + (info) => Debug.assert( + !info.isAttached(project), + "Found script Info still attached to project", + () => `${project.projectName}: ScriptInfos still attached: ${JSON.stringify( + arrayFrom( + mapDefinedIterator( + this.filenameToScriptInfo.values(), + (info2) => info2.isAttached(project) ? { + fileName: info2.fileName, + projects: info2.containingProjects.map((p) => p.projectName), + hasMixedContent: info2.hasMixedContent + } : void 0 + ) + ), + /*replacer*/ + void 0, + " " + )}` + ) + ); + } + this.pendingProjectUpdates.delete(project.getProjectName()); + switch (project.projectKind) { + case 2 /* External */: + unorderedRemoveItem(this.externalProjects, project); + this.projectToSizeMap.delete(project.getProjectName()); + break; + case 1 /* Configured */: + this.configuredProjects.delete(project.canonicalConfigFilePath); + this.projectToSizeMap.delete(project.canonicalConfigFilePath); + break; + case 0 /* Inferred */: + unorderedRemoveItem(this.inferredProjects, project); + break; + } + } + /** @internal */ + assignOrphanScriptInfoToInferredProject(info, projectRootPath) { + Debug.assert(info.isOrphan()); + const project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || this.getOrCreateSingleInferredProjectIfEnabled() || this.getOrCreateSingleInferredWithoutProjectRoot( + info.isDynamic ? projectRootPath || this.currentDirectory : getDirectoryPath( + isRootedDiskPath(info.fileName) ? info.fileName : getNormalizedAbsolutePath( + info.fileName, + projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory + ) + ) + ); + project.addRoot(info); + if (info.containingProjects[0] !== project) { + info.detachFromProject(project); + info.containingProjects.unshift(project); + } + project.updateGraph(); + if (!this.useSingleInferredProject && !project.projectRootPath) { + for (const inferredProject of this.inferredProjects) { + if (inferredProject === project || inferredProject.isOrphan()) { + continue; + } + const roots = inferredProject.getRootScriptInfos(); + Debug.assert(roots.length === 1 || !!inferredProject.projectRootPath); + if (roots.length === 1 && forEach(roots[0].containingProjects, (p) => p !== roots[0].containingProjects[0] && !p.isOrphan())) { + inferredProject.removeFile( + roots[0], + /*fileExists*/ + true, + /*detachFromProject*/ + true + ); + } + } + } + return project; + } + assignOrphanScriptInfosToInferredProject() { + this.openFiles.forEach((projectRootPath, path) => { + const info = this.getScriptInfoForPath(path); + if (info.isOrphan()) { + this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + } + }); + } + /** + * Remove this file from the set of open, non-configured files. + * @param info The file that has been closed or newly configured + */ + closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) { + const fileExists = info.isDynamic ? false : this.host.fileExists(info.fileName); + info.close(fileExists); + this.stopWatchingConfigFilesForClosedScriptInfo(info); + const canonicalFileName = this.toCanonicalFileName(info.fileName); + if (this.openFilesWithNonRootedDiskPath.get(canonicalFileName) === info) { + this.openFilesWithNonRootedDiskPath.delete(canonicalFileName); + } + let ensureProjectsForOpenFiles = false; + for (const p of info.containingProjects) { + if (isConfiguredProject(p)) { + if (info.hasMixedContent) { + info.registerFileUpdate(); + } + const updateLevel = p.openFileWatchTriggered.get(info.path); + if (updateLevel !== void 0) { + p.openFileWatchTriggered.delete(info.path); + if (p.pendingUpdateLevel !== void 0 && p.pendingUpdateLevel < updateLevel) { + p.pendingUpdateLevel = updateLevel; + p.markFileAsDirty(info.path); + } + } + } else if (isInferredProject(p) && p.isRoot(info)) { + if (p.isProjectWithSingleRoot()) { + ensureProjectsForOpenFiles = true; + } + p.removeFile( + info, + fileExists, + /*detachFromProject*/ + true + ); + } + if (!p.languageServiceEnabled) { + p.markAsDirty(); + } + } + this.openFiles.delete(info.path); + this.configFileForOpenFiles.delete(info.path); + if (!skipAssignOrphanScriptInfosToInferredProject && ensureProjectsForOpenFiles) { + this.assignOrphanScriptInfosToInferredProject(); + } + if (fileExists) { + this.watchClosedScriptInfo(info); + } else { + this.handleDeletedFile(info); + } + return ensureProjectsForOpenFiles; + } + deleteScriptInfo(info) { + this.filenameToScriptInfo.delete(info.path); + this.filenameToScriptInfoVersion.set(info.path, info.textStorage.version); + const realpath = info.getRealpathIfDifferent(); + if (realpath) { + this.realpathToScriptInfos.remove(realpath, info); + } + } + configFileExists(configFileName, canonicalConfigFilePath, info) { + var _a; + let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo) { + if (isOpenScriptInfo(info) && !((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.has(info.path))) { + (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Map())).set(info.path, false); + } + return configFileExistenceInfo.exists; + } + const exists = this.host.fileExists(configFileName); + let openFilesImpactedByConfigFile; + if (isOpenScriptInfo(info)) { + (openFilesImpactedByConfigFile || (openFilesImpactedByConfigFile = /* @__PURE__ */ new Map())).set(info.path, false); + } + configFileExistenceInfo = { exists, openFilesImpactedByConfigFile }; + this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); + return exists; + } + /** @internal */ + createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, forProject) { + var _a, _b; + const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo.watcher || configFileExistenceInfo.watcher === noopConfigFileWatcher) { + configFileExistenceInfo.watcher = this.watchFactory.watchFile( + configFileName, + (_fileName, eventKind) => this.onConfigFileChanged(canonicalConfigFilePath, eventKind), + 2e3 /* High */, + this.getWatchOptionsFromProjectWatchOptions((_b = (_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config) == null ? void 0 : _a.parsedCommandLine) == null ? void 0 : _b.watchOptions), + WatchType.ConfigFile, + forProject + ); + } + const projects = configFileExistenceInfo.config.projects; + projects.set(forProject.canonicalConfigFilePath, projects.get(forProject.canonicalConfigFilePath) || false); + } + /** + * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project + */ + configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo) { + return configFileExistenceInfo.openFilesImpactedByConfigFile && forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, identity); + } + /** @internal */ + releaseParsedConfig(canonicalConfigFilePath, forProject) { + var _a, _b, _c; + const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!((_a = configFileExistenceInfo.config) == null ? void 0 : _a.projects.delete(forProject.canonicalConfigFilePath))) + return; + if ((_b = configFileExistenceInfo.config) == null ? void 0 : _b.projects.size) + return; + configFileExistenceInfo.config = void 0; + clearSharedExtendedConfigFileWatcher(canonicalConfigFilePath, this.sharedExtendedConfigFileWatchers); + Debug.checkDefined(configFileExistenceInfo.watcher); + if ((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _c.size) { + if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { + if (!canWatchDirectoryOrFile(getPathComponents(getDirectoryPath(canonicalConfigFilePath)))) { + configFileExistenceInfo.watcher.close(); + configFileExistenceInfo.watcher = noopConfigFileWatcher; + } + } else { + configFileExistenceInfo.watcher.close(); + configFileExistenceInfo.watcher = void 0; + } + } else { + configFileExistenceInfo.watcher.close(); + this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); + } + } + /** + * Close the config file watcher in the cached ConfigFileExistenceInfo + * if there arent any open files that are root of inferred project and there is no parsed config held by any project + * + * @internal + */ + closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo) { + if (configFileExistenceInfo.watcher && !configFileExistenceInfo.config && !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { + configFileExistenceInfo.watcher.close(); + configFileExistenceInfo.watcher = void 0; + } + } + /** + * This is called on file close, so that we stop watching the config file for this script info + */ + stopWatchingConfigFilesForClosedScriptInfo(info) { + Debug.assert(!info.isScriptOpen()); + this.forEachConfigFileLocation(info, (canonicalConfigFilePath) => { + var _a, _b, _c; + const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo) { + const infoIsRootOfInferredProject = (_a = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.get(info.path); + (_b = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _b.delete(info.path); + if (infoIsRootOfInferredProject) { + this.closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo); + } + if (!((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _c.size) && !configFileExistenceInfo.config) { + Debug.assert(!configFileExistenceInfo.watcher); + this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); + } + } + }); + } + /** + * This is called by inferred project whenever script info is added as a root + * + * @internal + */ + startWatchingConfigFilesForInferredProjectRoot(info) { + Debug.assert(info.isScriptOpen()); + this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName) => { + let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo) { + configFileExistenceInfo = { exists: this.host.fileExists(configFileName) }; + this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); + } + (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Map())).set(info.path, true); + configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = canWatchDirectoryOrFile(getPathComponents(getDirectoryPath(canonicalConfigFilePath))) ? this.watchFactory.watchFile( + configFileName, + (_filename, eventKind) => this.onConfigFileChanged(canonicalConfigFilePath, eventKind), + 2e3 /* High */, + this.hostConfiguration.watchOptions, + WatchType.ConfigFileForInferredRoot + ) : noopConfigFileWatcher); + }); + } + /** + * This is called by inferred project whenever root script info is removed from it + * + * @internal + */ + stopWatchingConfigFilesForInferredProjectRoot(info) { + this.forEachConfigFileLocation(info, (canonicalConfigFilePath) => { + var _a; + const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if ((_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.has(info.path)) { + Debug.assert(info.isScriptOpen()); + configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); + this.closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo); + } + }); + } + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + */ + forEachConfigFileLocation(info, action) { + if (this.serverMode !== 0 /* Semantic */) { + return void 0; + } + Debug.assert(!isOpenScriptInfo(info) || this.openFiles.has(info.path)); + const projectRootPath = this.openFiles.get(info.path); + const scriptInfo = Debug.checkDefined(this.getScriptInfo(info.path)); + if (scriptInfo.isDynamic) + return void 0; + let searchPath = asNormalizedPath(getDirectoryPath(info.fileName)); + const isSearchPathInProjectRoot = () => containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames); + const anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot(); + let searchInDirectory = !isAncestorConfigFileInfo(info); + do { + if (searchInDirectory) { + const canonicalSearchPath = normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); + const tsconfigFileName = asNormalizedPath(combinePaths(searchPath, "tsconfig.json")); + let result = action(combinePaths(canonicalSearchPath, "tsconfig.json"), tsconfigFileName); + if (result) + return tsconfigFileName; + const jsconfigFileName = asNormalizedPath(combinePaths(searchPath, "jsconfig.json")); + result = action(combinePaths(canonicalSearchPath, "jsconfig.json"), jsconfigFileName); + if (result) + return jsconfigFileName; + if (isNodeModulesDirectory(canonicalSearchPath)) { + break; + } + } + const parentPath = asNormalizedPath(getDirectoryPath(searchPath)); + if (parentPath === searchPath) + break; + searchPath = parentPath; + searchInDirectory = true; + } while (anySearchPathOk || isSearchPathInProjectRoot()); + return void 0; + } + /** @internal */ + findDefaultConfiguredProject(info) { + if (!info.isScriptOpen()) + return void 0; + const configFileName = this.getConfigFileNameForFile(info); + const project = configFileName && this.findConfiguredProjectByProjectName(configFileName); + return project && projectContainsInfoDirectly(project, info) ? project : project == null ? void 0 : project.getDefaultChildProjectFromProjectWithReferences(info); + } + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + * If script info is passed in, it is asserted to be open script info + * otherwise just file name + */ + getConfigFileNameForFile(info) { + if (isOpenScriptInfo(info)) { + Debug.assert(info.isScriptOpen()); + const result = this.configFileForOpenFiles.get(info.path); + if (result !== void 0) + return result || void 0; + } + this.logger.info(`Search path: ${getDirectoryPath(info.fileName)}`); + const configFileName = this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName2) => this.configFileExists(configFileName2, canonicalConfigFilePath, info)); + if (configFileName) { + this.logger.info(`For info: ${info.fileName} :: Config file name: ${configFileName}`); + } else { + this.logger.info(`For info: ${info.fileName} :: No config files found.`); + } + if (isOpenScriptInfo(info)) { + this.configFileForOpenFiles.set(info.path, configFileName || false); + } + return configFileName; + } + printProjects() { + if (!this.logger.hasLevel(1 /* normal */)) { + return; + } + this.logger.startGroup(); + this.externalProjects.forEach(printProjectWithoutFileNames); + this.configuredProjects.forEach(printProjectWithoutFileNames); + this.inferredProjects.forEach(printProjectWithoutFileNames); + this.logger.info("Open files: "); + this.openFiles.forEach((projectRootPath, path) => { + const info = this.getScriptInfoForPath(path); + this.logger.info(` FileName: ${info.fileName} ProjectRootPath: ${projectRootPath}`); + this.logger.info(` Projects: ${info.containingProjects.map((p) => p.getProjectName())}`); + }); + this.logger.endGroup(); + } + /** @internal */ + findConfiguredProjectByProjectName(configFileName) { + const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName)); + return this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath); + } + getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath) { + return this.configuredProjects.get(canonicalConfigFilePath); + } + findExternalProjectByProjectName(projectFileName) { + return findProjectByName(projectFileName, this.externalProjects); + } + /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ + getFilenameForExceededTotalSizeLimitForNonTsFiles(name, options, fileNames, propertyReader) { + if (options && options.disableSizeLimit || !this.host.getFileSize) { + return; + } + let availableSpace = maxProgramSizeForNonTsFiles; + this.projectToSizeMap.set(name, 0); + this.projectToSizeMap.forEach((val) => availableSpace -= val || 0); + let totalNonTsFileSize = 0; + for (const f of fileNames) { + const fileName = propertyReader.getFileName(f); + if (hasTSFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { + const top5LargestFiles = fileNames.map((f2) => propertyReader.getFileName(f2)).filter((name2) => !hasTSFileExtension(name2)).map((name2) => ({ name: name2, size: this.host.getFileSize(name2) })).sort((a, b) => b.size - a.size).slice(0, 5); + this.logger.info(`Non TS file size exceeded limit (${totalNonTsFileSize}). Largest files: ${top5LargestFiles.map((file) => `${file.name}:${file.size}`).join(", ")}`); + return fileName; + } + } + this.projectToSizeMap.set(name, totalNonTsFileSize); + } + createExternalProject(projectFileName, files, options, typeAcquisition, excludedFiles) { + const compilerOptions = convertCompilerOptions(options); + const watchOptionsAndErrors = convertWatchOptions(options, getDirectoryPath(normalizeSlashes(projectFileName))); + const project = new ExternalProject2( + projectFileName, + this, + this.documentRegistry, + compilerOptions, + /*lastFileExceededProgramSize*/ + this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), + options.compileOnSave === void 0 ? true : options.compileOnSave, + /*projectFilePath*/ + void 0, + watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions + ); + project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors); + project.excludedFiles = excludedFiles; + this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition); + this.externalProjects.push(project); + return project; + } + /** @internal */ + sendProjectTelemetry(project) { + if (this.seenProjects.has(project.projectName)) { + setProjectOptionsUsed(project); + return; + } + this.seenProjects.set(project.projectName, true); + if (!this.eventHandler || !this.host.createSHA256Hash) { + setProjectOptionsUsed(project); + return; + } + const projectOptions = isConfiguredProject(project) ? project.projectOptions : void 0; + setProjectOptionsUsed(project); + const data = { + projectId: this.host.createSHA256Hash(project.projectName), + fileStats: countEachFileTypes( + project.getScriptInfos(), + /*includeSizes*/ + true + ), + compilerOptions: convertCompilerOptionsForTelemetry(project.getCompilationSettings()), + typeAcquisition: convertTypeAcquisition2(project.getTypeAcquisition()), + extends: projectOptions && projectOptions.configHasExtendsProperty, + files: projectOptions && projectOptions.configHasFilesProperty, + include: projectOptions && projectOptions.configHasIncludeProperty, + exclude: projectOptions && projectOptions.configHasExcludeProperty, + compileOnSave: project.compileOnSaveEnabled, + configFileName: configFileName(), + projectType: project instanceof ExternalProject2 ? "external" : "configured", + languageServiceEnabled: project.languageServiceEnabled, + version + }; + this.eventHandler({ eventName: ProjectInfoTelemetryEvent, data }); + function configFileName() { + if (!isConfiguredProject(project)) { + return "other"; + } + return getBaseConfigFileName(project.getConfigFilePath()) || "other"; + } + function convertTypeAcquisition2({ enable: enable2, include, exclude }) { + return { + enable: enable2, + include: include !== void 0 && include.length !== 0, + exclude: exclude !== void 0 && exclude.length !== 0 + }; + } + } + addFilesToNonInferredProject(project, files, propertyReader, typeAcquisition) { + this.updateNonInferredProjectFiles(project, files, propertyReader); + project.setTypeAcquisition(typeAcquisition); + project.markAsDirty(); + } + /** @internal */ + createConfiguredProject(configFileName) { + var _a; + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "createConfiguredProject", { configFilePath: configFileName }); + this.logger.info(`Creating configuration project ${configFileName}`); + const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName)); + let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo) { + this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: true }); + } else { + configFileExistenceInfo.exists = true; + } + if (!configFileExistenceInfo.config) { + configFileExistenceInfo.config = { + cachedDirectoryStructureHost: createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames), + projects: /* @__PURE__ */ new Map(), + updateLevel: 2 /* Full */ + }; + } + const project = new ConfiguredProject2( + configFileName, + canonicalConfigFilePath, + this, + this.documentRegistry, + configFileExistenceInfo.config.cachedDirectoryStructureHost + ); + this.configuredProjects.set(canonicalConfigFilePath, project); + this.createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, project); + return project; + } + /** @internal */ + createConfiguredProjectWithDelayLoad(configFileName, reason) { + const project = this.createConfiguredProject(configFileName); + project.pendingUpdateLevel = 2 /* Full */; + project.pendingUpdateReason = reason; + return project; + } + /** @internal */ + createAndLoadConfiguredProject(configFileName, reason) { + const project = this.createConfiguredProject(configFileName); + this.loadConfiguredProject(project, reason); + return project; + } + /** @internal */ + createLoadAndUpdateConfiguredProject(configFileName, reason) { + const project = this.createAndLoadConfiguredProject(configFileName, reason); + project.updateGraph(); + return project; + } + /** + * Read the config file of the project, and update the project root file names. + * + * @internal + */ + loadConfiguredProject(project, reason) { + var _a, _b; + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "loadConfiguredProject", { configFilePath: project.canonicalConfigFilePath }); + this.sendProjectLoadingStartEvent(project, reason); + const configFilename = asNormalizedPath(normalizePath(project.getConfigFilePath())); + const configFileExistenceInfo = this.ensureParsedConfigUptoDate( + configFilename, + project.canonicalConfigFilePath, + this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath), + project + ); + const parsedCommandLine = configFileExistenceInfo.config.parsedCommandLine; + Debug.assert(!!parsedCommandLine.fileNames); + const compilerOptions = parsedCommandLine.options; + if (!project.projectOptions) { + project.projectOptions = { + configHasExtendsProperty: parsedCommandLine.raw.extends !== void 0, + configHasFilesProperty: parsedCommandLine.raw.files !== void 0, + configHasIncludeProperty: parsedCommandLine.raw.include !== void 0, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== void 0 + }; + } + project.canConfigFileJsonReportNoInputFiles = canJsonReportNoInputFiles(parsedCommandLine.raw); + project.setProjectErrors(parsedCommandLine.options.configFile.parseDiagnostics); + project.updateReferences(parsedCommandLine.projectReferences); + const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); + if (lastFileExceededProgramSize) { + project.disableLanguageService(lastFileExceededProgramSize); + this.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => this.stopWatchingWildCards(canonicalConfigFilePath, project)); + } else { + project.setCompilerOptions(compilerOptions); + project.setWatchOptions(parsedCommandLine.watchOptions); + project.enableLanguageService(); + this.watchWildcards(configFilename, configFileExistenceInfo, project); + } + project.enablePluginsWithOptions(compilerOptions); + const filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles(2 /* Full */)); + this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave, parsedCommandLine.watchOptions); + (_b = tracing) == null ? void 0 : _b.pop(); + } + /** @internal */ + ensureParsedConfigUptoDate(configFilename, canonicalConfigFilePath, configFileExistenceInfo, forProject) { + var _a, _b, _c; + if (configFileExistenceInfo.config) { + if (!configFileExistenceInfo.config.updateLevel) + return configFileExistenceInfo; + if (configFileExistenceInfo.config.updateLevel === 1 /* RootNamesAndUpdate */) { + this.reloadFileNamesOfParsedConfig(configFilename, configFileExistenceInfo.config); + return configFileExistenceInfo; + } + } + const cachedDirectoryStructureHost = ((_a = configFileExistenceInfo.config) == null ? void 0 : _a.cachedDirectoryStructureHost) || createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); + const configFileContent = tryReadFile(configFilename, (fileName) => this.host.readFile(fileName)); + const configFile = parseJsonText(configFilename, isString(configFileContent) ? configFileContent : ""); + const configFileErrors = configFile.parseDiagnostics; + if (!isString(configFileContent)) + configFileErrors.push(configFileContent); + const parsedCommandLine = parseJsonSourceFileConfigFileContent( + configFile, + cachedDirectoryStructureHost, + getDirectoryPath(configFilename), + /*existingOptions*/ + {}, + configFilename, + /*resolutionStack*/ + [], + this.hostConfiguration.extraFileExtensions, + this.extendedConfigCache + ); + if (parsedCommandLine.errors.length) { + configFileErrors.push(...parsedCommandLine.errors); + } + this.logger.info(`Config: ${configFilename} : ${JSON.stringify( + { + rootNames: parsedCommandLine.fileNames, + options: parsedCommandLine.options, + watchOptions: parsedCommandLine.watchOptions, + projectReferences: parsedCommandLine.projectReferences + }, + /*replacer*/ + void 0, + " " + )}`); + const oldCommandLine = (_b = configFileExistenceInfo.config) == null ? void 0 : _b.parsedCommandLine; + if (!configFileExistenceInfo.config) { + configFileExistenceInfo.config = { parsedCommandLine, cachedDirectoryStructureHost, projects: /* @__PURE__ */ new Map() }; + } else { + configFileExistenceInfo.config.parsedCommandLine = parsedCommandLine; + configFileExistenceInfo.config.watchedDirectoriesStale = true; + configFileExistenceInfo.config.updateLevel = void 0; + } + if (!oldCommandLine && !isJsonEqual( + // Old options + this.getWatchOptionsFromProjectWatchOptions( + /*projectOptions*/ + void 0 + ), + // New options + this.getWatchOptionsFromProjectWatchOptions(parsedCommandLine.watchOptions) + )) { + (_c = configFileExistenceInfo.watcher) == null ? void 0 : _c.close(); + configFileExistenceInfo.watcher = void 0; + } + this.createConfigFileWatcherForParsedConfig(configFilename, canonicalConfigFilePath, forProject); + updateSharedExtendedConfigFileWatcher( + canonicalConfigFilePath, + parsedCommandLine.options, + this.sharedExtendedConfigFileWatchers, + (extendedConfigFileName, extendedConfigFilePath) => this.watchFactory.watchFile( + extendedConfigFileName, + () => { + var _a2; + cleanExtendedConfigCache(this.extendedConfigCache, extendedConfigFilePath, (fileName) => this.toPath(fileName)); + let ensureProjectsForOpenFiles = false; + (_a2 = this.sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) == null ? void 0 : _a2.projects.forEach((canonicalPath) => { + ensureProjectsForOpenFiles = this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalPath, `Change in extended config file ${extendedConfigFileName} detected`) || ensureProjectsForOpenFiles; + }); + if (ensureProjectsForOpenFiles) + this.delayEnsureProjectForOpenFiles(); + }, + 2e3 /* High */, + this.hostConfiguration.watchOptions, + WatchType.ExtendedConfigFile, + configFilename + ), + (fileName) => this.toPath(fileName) + ); + return configFileExistenceInfo; + } + /** @internal */ + watchWildcards(configFileName, { exists, config }, forProject) { + config.projects.set(forProject.canonicalConfigFilePath, true); + if (exists) { + if (config.watchedDirectories && !config.watchedDirectoriesStale) + return; + config.watchedDirectoriesStale = false; + updateWatchingWildcardDirectories( + config.watchedDirectories || (config.watchedDirectories = /* @__PURE__ */ new Map()), + new Map(Object.entries(config.parsedCommandLine.wildcardDirectories)), + // Create new directory watcher + (directory, flags) => this.watchWildcardDirectory(directory, flags, configFileName, config) + ); + } else { + config.watchedDirectoriesStale = false; + if (!config.watchedDirectories) + return; + clearMap(config.watchedDirectories, closeFileWatcherOf); + config.watchedDirectories = void 0; + } + } + /** @internal */ + stopWatchingWildCards(canonicalConfigFilePath, forProject) { + const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo.config || !configFileExistenceInfo.config.projects.get(forProject.canonicalConfigFilePath)) { + return; + } + configFileExistenceInfo.config.projects.set(forProject.canonicalConfigFilePath, false); + if (forEachEntry(configFileExistenceInfo.config.projects, identity)) + return; + if (configFileExistenceInfo.config.watchedDirectories) { + clearMap(configFileExistenceInfo.config.watchedDirectories, closeFileWatcherOf); + configFileExistenceInfo.config.watchedDirectories = void 0; + } + configFileExistenceInfo.config.watchedDirectoriesStale = void 0; + } + updateNonInferredProjectFiles(project, files, propertyReader) { + const projectRootFilesMap = project.getRootFilesMap(); + const newRootScriptInfoMap = /* @__PURE__ */ new Map(); + for (const f of files) { + const newRootFile = propertyReader.getFileName(f); + const fileName = toNormalizedPath(newRootFile); + const isDynamic = isDynamicFileName(fileName); + let path; + if (!isDynamic && !project.fileExists(newRootFile)) { + path = normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName); + const existingValue = projectRootFilesMap.get(path); + if (existingValue) { + if (existingValue.info) { + project.removeFile( + existingValue.info, + /*fileExists*/ + false, + /*detachFromProject*/ + true + ); + existingValue.info = void 0; + } + existingValue.fileName = fileName; + } else { + projectRootFilesMap.set(path, { fileName }); + } + } else { + const scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions); + const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); + const scriptInfo = Debug.checkDefined(this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath( + fileName, + project.currentDirectory, + scriptKind, + hasMixedContent, + project.directoryStructureHost + )); + path = scriptInfo.path; + const existingValue = projectRootFilesMap.get(path); + if (!existingValue || existingValue.info !== scriptInfo) { + project.addRoot(scriptInfo, fileName); + if (scriptInfo.isScriptOpen()) { + this.removeRootOfInferredProjectIfNowPartOfOtherProject(scriptInfo); + } + } else { + existingValue.fileName = fileName; + } + } + newRootScriptInfoMap.set(path, true); + } + if (projectRootFilesMap.size > newRootScriptInfoMap.size) { + projectRootFilesMap.forEach((value, path) => { + if (!newRootScriptInfoMap.has(path)) { + if (value.info) { + project.removeFile( + value.info, + project.fileExists(path), + /*detachFromProject*/ + true + ); + } else { + projectRootFilesMap.delete(path); + } + } + }); + } + } + updateRootAndOptionsOfNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, watchOptions) { + project.setCompilerOptions(newOptions); + project.setWatchOptions(watchOptions); + if (compileOnSave !== void 0) { + project.compileOnSaveEnabled = compileOnSave; + } + this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition); + } + /** + * Reload the file names from config file specs and update the project graph + * + * @internal + */ + reloadFileNamesOfConfiguredProject(project) { + const fileNames = this.reloadFileNamesOfParsedConfig(project.getConfigFilePath(), this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath).config); + project.updateErrorOnNoInputFiles(fileNames); + this.updateNonInferredProjectFiles(project, fileNames.concat(project.getExternalFiles(1 /* RootNamesAndUpdate */)), fileNamePropertyReader); + project.markAsDirty(); + return project.updateGraph(); + } + /** @internal */ + reloadFileNamesOfParsedConfig(configFileName, config) { + if (config.updateLevel === void 0) + return config.parsedCommandLine.fileNames; + Debug.assert(config.updateLevel === 1 /* RootNamesAndUpdate */); + const configFileSpecs = config.parsedCommandLine.options.configFile.configFileSpecs; + const fileNames = getFileNamesFromConfigSpecs( + configFileSpecs, + getDirectoryPath(configFileName), + config.parsedCommandLine.options, + config.cachedDirectoryStructureHost, + this.hostConfiguration.extraFileExtensions + ); + config.parsedCommandLine = { ...config.parsedCommandLine, fileNames }; + return fileNames; + } + /** @internal */ + setFileNamesOfAutpImportProviderOrAuxillaryProject(project, fileNames) { + this.updateNonInferredProjectFiles(project, fileNames, fileNamePropertyReader); + } + /** + * Read the config file of the project again by clearing the cache and update the project graph + * + * @internal + */ + reloadConfiguredProject(project, reason, isInitialLoad, clearSemanticCache) { + const host = project.getCachedDirectoryStructureHost(); + if (clearSemanticCache) + this.clearSemanticCache(project); + host.clearCache(); + const configFileName = project.getConfigFilePath(); + this.logger.info(`${isInitialLoad ? "Loading" : "Reloading"} configured project ${configFileName}`); + this.loadConfiguredProject(project, reason); + project.updateGraph(); + this.sendConfigFileDiagEvent(project, configFileName); + } + /** @internal */ + clearSemanticCache(project) { + project.resolutionCache.clear(); + project.getLanguageService( + /*ensureSynchronized*/ + false + ).cleanupSemanticCache(); + project.cleanupProgram(); + project.markAsDirty(); + } + sendConfigFileDiagEvent(project, triggerFile) { + if (!this.eventHandler || this.suppressDiagnosticEvents) { + return; + } + const diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics(); + diagnostics.push(...project.getAllProjectErrors()); + this.eventHandler( + { + eventName: ConfigFileDiagEvent, + data: { configFileName: project.getConfigFilePath(), diagnostics, triggerFile } + } + ); + } + getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) { + if (!this.useInferredProjectPerProjectRoot || // Its a dynamic info opened without project root + info.isDynamic && projectRootPath === void 0) { + return void 0; + } + if (projectRootPath) { + const canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath); + for (const project of this.inferredProjects) { + if (project.projectRootPath === canonicalProjectRootPath) { + return project; + } + } + return this.createInferredProject( + projectRootPath, + /*isSingleInferredProject*/ + false, + projectRootPath + ); + } + let bestMatch; + for (const project of this.inferredProjects) { + if (!project.projectRootPath) + continue; + if (!containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) + continue; + if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length) + continue; + bestMatch = project; + } + return bestMatch; + } + getOrCreateSingleInferredProjectIfEnabled() { + if (!this.useSingleInferredProject) { + return void 0; + } + if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === void 0) { + return this.inferredProjects[0]; + } + return this.createInferredProject( + "", + /*isSingleInferredProject*/ + true + ); + } + getOrCreateSingleInferredWithoutProjectRoot(currentDirectory) { + Debug.assert(!this.useSingleInferredProject); + const expectedCurrentDirectory = this.toCanonicalFileName(this.getNormalizedAbsolutePath(currentDirectory)); + for (const inferredProject of this.inferredProjects) { + if (!inferredProject.projectRootPath && inferredProject.isOrphan() && inferredProject.canonicalCurrentDirectory === expectedCurrentDirectory) { + return inferredProject; + } + } + return this.createInferredProject(currentDirectory); + } + createInferredProject(currentDirectory, isSingleInferredProject, projectRootPath) { + const compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; + let watchOptionsAndErrors; + let typeAcquisition; + if (projectRootPath) { + watchOptionsAndErrors = this.watchOptionsForInferredProjectsPerProjectRoot.get(projectRootPath); + typeAcquisition = this.typeAcquisitionForInferredProjectsPerProjectRoot.get(projectRootPath); + } + if (watchOptionsAndErrors === void 0) { + watchOptionsAndErrors = this.watchOptionsForInferredProjects; + } + if (typeAcquisition === void 0) { + typeAcquisition = this.typeAcquisitionForInferredProjects; + } + watchOptionsAndErrors = watchOptionsAndErrors || void 0; + const project = new InferredProject2(this, this.documentRegistry, compilerOptions, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions, projectRootPath, currentDirectory, typeAcquisition); + project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors); + if (isSingleInferredProject) { + this.inferredProjects.unshift(project); + } else { + this.inferredProjects.push(project); + } + return project; + } + /** @internal */ + getOrCreateScriptInfoNotOpenedByClient(uncheckedFileName, currentDirectory, hostToQueryFileExistsOn) { + return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath( + toNormalizedPath(uncheckedFileName), + currentDirectory, + /*scriptKind*/ + void 0, + /*hasMixedContent*/ + void 0, + hostToQueryFileExistsOn + ); + } + getScriptInfo(uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName)); + } + /** @internal */ + getScriptInfoOrConfig(uncheckedFileName) { + const path = toNormalizedPath(uncheckedFileName); + const info = this.getScriptInfoForNormalizedPath(path); + if (info) + return info; + const configProject = this.configuredProjects.get(this.toPath(uncheckedFileName)); + return configProject && configProject.getCompilerOptions().configFile; + } + /** @internal */ + logErrorForScriptInfoNotFound(fileName) { + const names = arrayFrom(this.filenameToScriptInfo.entries(), ([path, scriptInfo]) => ({ path, fileName: scriptInfo.fileName })); + this.logger.msg(`Could not find file ${JSON.stringify(fileName)}. +All files are: ${JSON.stringify(names)}`, "Err" /* Err */); + } + /** + * Returns the projects that contain script info through SymLink + * Note that this does not return projects in info.containingProjects + * + * @internal + */ + getSymlinkedProjects(info) { + let projects; + if (this.realpathToScriptInfos) { + const realpath = info.getRealpathIfDifferent(); + if (realpath) { + forEach(this.realpathToScriptInfos.get(realpath), combineProjects); + } + forEach(this.realpathToScriptInfos.get(info.path), combineProjects); + } + return projects; + function combineProjects(toAddInfo) { + if (toAddInfo !== info) { + for (const project of toAddInfo.containingProjects) { + if (project.languageServiceEnabled && !project.isOrphan() && !project.getCompilerOptions().preserveSymlinks && !info.isAttached(project)) { + if (!projects) { + projects = createMultiMap(); + projects.add(toAddInfo.path, project); + } else if (!forEachEntry(projects, (projs, path) => path === toAddInfo.path ? false : contains(projs, project))) { + projects.add(toAddInfo.path, project); + } + } + } + } + } + } + watchClosedScriptInfo(info) { + Debug.assert(!info.fileWatcher); + if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !startsWith(info.path, this.globalCacheLocationDirectoryPath))) { + const indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFile( + info.fileName, + (_fileName, eventKind) => this.onSourceFileChanged(info, eventKind), + 500 /* Medium */, + this.hostConfiguration.watchOptions, + WatchType.ClosedScriptInfo + ); + } else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules)); + } + } + } + createNodeModulesWatcher(dir) { + const watcher = this.watchFactory.watchDirectory( + dir, + (fileOrDirectory) => { + var _a; + const fileOrDirectoryPath = removeIgnoredPath(this.toPath(fileOrDirectory)); + if (!fileOrDirectoryPath) + return; + const basename = getBaseFileName(fileOrDirectoryPath); + if (((_a = result.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.size) && (basename === "package.json" || basename === "node_modules")) { + result.affectedModuleSpecifierCacheProjects.forEach((projectName) => { + var _a2, _b; + (_b = (_a2 = this.findProject(projectName)) == null ? void 0 : _a2.getModuleSpecifierCache()) == null ? void 0 : _b.clear(); + }); + } + if (result.refreshScriptInfoRefCount) { + if (dir === fileOrDirectoryPath) { + this.refreshScriptInfosInDirectory(dir); + } else { + const info = this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + this.refreshScriptInfo(info); + } + } else if (!hasExtension(fileOrDirectoryPath)) { + this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + } + }, + 1 /* Recursive */, + this.hostConfiguration.watchOptions, + WatchType.NodeModules + ); + const result = { + refreshScriptInfoRefCount: 0, + affectedModuleSpecifierCacheProjects: void 0, + close: () => { + var _a; + if (!result.refreshScriptInfoRefCount && !((_a = result.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.size)) { + watcher.close(); + this.nodeModulesWatchers.delete(dir); + } + } + }; + this.nodeModulesWatchers.set(dir, result); + return result; + } + /** @internal */ + watchPackageJsonsInNodeModules(dir, project) { + const watcher = this.nodeModulesWatchers.get(dir) || this.createNodeModulesWatcher(dir); + (watcher.affectedModuleSpecifierCacheProjects || (watcher.affectedModuleSpecifierCacheProjects = /* @__PURE__ */ new Set())).add(project.getProjectName()); + return { + close: () => { + var _a; + (_a = watcher.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.delete(project.getProjectName()); + watcher.close(); + } + }; + } + watchClosedScriptInfoInNodeModules(dir) { + const watchDir = dir + "/node_modules"; + const watcher = this.nodeModulesWatchers.get(watchDir) || this.createNodeModulesWatcher(watchDir); + watcher.refreshScriptInfoRefCount++; + return { + close: () => { + watcher.refreshScriptInfoRefCount--; + watcher.close(); + } + }; + } + getModifiedTime(info) { + return (this.host.getModifiedTime(info.path) || missingFileModifiedTime).getTime(); + } + refreshScriptInfo(info) { + const mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + const eventKind = getFileWatcherEventKind(info.mTime, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info, eventKind); + } + } + refreshScriptInfosInDirectory(dir) { + dir = dir + directorySeparator; + this.filenameToScriptInfo.forEach((info) => { + if (isScriptInfoWatchedFromNodeModules(info) && startsWith(info.path, dir)) { + this.refreshScriptInfo(info); + } + }); + } + stopWatchingScriptInfo(info) { + if (info.fileWatcher) { + info.fileWatcher.close(); + info.fileWatcher = void 0; + } + } + getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + if (isRootedDiskPath(fileName) || isDynamicFileName(fileName)) { + return this.getOrCreateScriptInfoWorker( + fileName, + currentDirectory, + /*openedByClient*/ + false, + /*fileContent*/ + void 0, + scriptKind, + hasMixedContent, + hostToQueryFileExistsOn + ); + } + const info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)); + if (info) { + return info; + } + return void 0; + } + getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, currentDirectory, fileContent, scriptKind, hasMixedContent) { + return this.getOrCreateScriptInfoWorker( + fileName, + currentDirectory, + /*openedByClient*/ + true, + fileContent, + scriptKind, + hasMixedContent + ); + } + getOrCreateScriptInfoForNormalizedPath(fileName, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + } + getOrCreateScriptInfoWorker(fileName, currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + Debug.assert(fileContent === void 0 || openedByClient, "ScriptInfo needs to be opened by client to be able to set its user defined content"); + const path = normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName); + let info = this.getScriptInfoForPath(path); + if (!info) { + const isDynamic = isDynamicFileName(fileName); + Debug.assert(isRootedDiskPath(fileName) || isDynamic || openedByClient, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })} +Script info with non-dynamic relative file name can only be open script info or in context of host currentDirectory`); + Debug.assert(!isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })} +Open script files with non rooted disk path opened with current directory context cannot have same canonical names`); + Debug.assert(!isDynamic || this.currentDirectory === currentDirectory || this.useInferredProjectPerProjectRoot, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })} +Dynamic files must always be opened with service's current directory or service should support inferred project per projectRootPath.`); + if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { + return; + } + info = new ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path, this.filenameToScriptInfoVersion.get(path)); + this.filenameToScriptInfo.set(info.path, info); + this.filenameToScriptInfoVersion.delete(info.path); + if (!openedByClient) { + this.watchClosedScriptInfo(info); + } else if (!isRootedDiskPath(fileName) && (!isDynamic || this.currentDirectory !== currentDirectory)) { + this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info); + } + } + if (openedByClient) { + this.stopWatchingScriptInfo(info); + info.open(fileContent); + if (hasMixedContent) { + info.registerFileUpdate(); + } + } + return info; + } + /** + * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred + */ + getScriptInfoForNormalizedPath(fileName) { + return !isRootedDiskPath(fileName) && this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)) || this.getScriptInfoForPath(normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName)); + } + getScriptInfoForPath(fileName) { + return this.filenameToScriptInfo.get(fileName); + } + /** @internal */ + getDocumentPositionMapper(project, generatedFileName, sourceFileName) { + const declarationInfo = this.getOrCreateScriptInfoNotOpenedByClient(generatedFileName, project.currentDirectory, this.host); + if (!declarationInfo) { + if (sourceFileName) { + project.addGeneratedFileWatch(generatedFileName, sourceFileName); + } + return void 0; + } + declarationInfo.getSnapshot(); + if (isString(declarationInfo.sourceMapFilePath)) { + const sourceMapFileInfo2 = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath); + if (sourceMapFileInfo2) { + sourceMapFileInfo2.getSnapshot(); + if (sourceMapFileInfo2.documentPositionMapper !== void 0) { + sourceMapFileInfo2.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo2.sourceInfos); + return sourceMapFileInfo2.documentPositionMapper ? sourceMapFileInfo2.documentPositionMapper : void 0; + } + } + declarationInfo.sourceMapFilePath = void 0; + } else if (declarationInfo.sourceMapFilePath) { + declarationInfo.sourceMapFilePath.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, declarationInfo.sourceMapFilePath.sourceInfos); + return void 0; + } else if (declarationInfo.sourceMapFilePath !== void 0) { + return void 0; + } + let sourceMapFileInfo; + let mapFileNameFromDeclarationInfo; + let readMapFile = (mapFileName, mapFileNameFromDts) => { + const mapInfo = this.getOrCreateScriptInfoNotOpenedByClient(mapFileName, project.currentDirectory, this.host); + if (!mapInfo) { + mapFileNameFromDeclarationInfo = mapFileNameFromDts; + return void 0; + } + sourceMapFileInfo = mapInfo; + const snap = mapInfo.getSnapshot(); + if (mapInfo.documentPositionMapper !== void 0) + return mapInfo.documentPositionMapper; + return getSnapshotText(snap); + }; + const projectName = project.projectName; + const documentPositionMapper = getDocumentPositionMapper( + { getCanonicalFileName: this.toCanonicalFileName, log: (s) => this.logger.info(s), getSourceFileLike: (f) => this.getSourceFileLike(f, projectName, declarationInfo) }, + declarationInfo.fileName, + declarationInfo.textStorage.getLineInfo(), + readMapFile + ); + readMapFile = void 0; + if (sourceMapFileInfo) { + declarationInfo.sourceMapFilePath = sourceMapFileInfo.path; + sourceMapFileInfo.declarationInfoPath = declarationInfo.path; + sourceMapFileInfo.documentPositionMapper = documentPositionMapper || false; + sourceMapFileInfo.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo.sourceInfos); + } else if (mapFileNameFromDeclarationInfo) { + declarationInfo.sourceMapFilePath = { + watcher: this.addMissingSourceMapFile( + project.currentDirectory === this.currentDirectory ? mapFileNameFromDeclarationInfo : getNormalizedAbsolutePath(mapFileNameFromDeclarationInfo, project.currentDirectory), + declarationInfo.path + ), + sourceInfos: this.addSourceInfoToSourceMap(sourceFileName, project) + }; + } else { + declarationInfo.sourceMapFilePath = false; + } + return documentPositionMapper; + } + addSourceInfoToSourceMap(sourceFileName, project, sourceInfos) { + if (sourceFileName) { + const sourceInfo = this.getOrCreateScriptInfoNotOpenedByClient(sourceFileName, project.currentDirectory, project.directoryStructureHost); + (sourceInfos || (sourceInfos = /* @__PURE__ */ new Set())).add(sourceInfo.path); + } + return sourceInfos; + } + addMissingSourceMapFile(mapFileName, declarationInfoPath) { + const fileWatcher = this.watchFactory.watchFile( + mapFileName, + () => { + const declarationInfo = this.getScriptInfoForPath(declarationInfoPath); + if (declarationInfo && declarationInfo.sourceMapFilePath && !isString(declarationInfo.sourceMapFilePath)) { + this.delayUpdateProjectGraphs( + declarationInfo.containingProjects, + /*clearSourceMapperCache*/ + true + ); + this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos); + declarationInfo.closeSourceMapFileWatcher(); + } + }, + 2e3 /* High */, + this.hostConfiguration.watchOptions, + WatchType.MissingSourceMapFile + ); + return fileWatcher; + } + /** @internal */ + getSourceFileLike(fileName, projectNameOrProject, declarationInfo) { + const project = projectNameOrProject.projectName ? projectNameOrProject : this.findProject(projectNameOrProject); + if (project) { + const path = project.toPath(fileName); + const sourceFile = project.getSourceFile(path); + if (sourceFile && sourceFile.resolvedPath === path) + return sourceFile; + } + const info = this.getOrCreateScriptInfoNotOpenedByClient(fileName, (project || this).currentDirectory, project ? project.directoryStructureHost : this.host); + if (!info) + return void 0; + if (declarationInfo && isString(declarationInfo.sourceMapFilePath) && info !== declarationInfo) { + const sourceMapInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath); + if (sourceMapInfo) { + (sourceMapInfo.sourceInfos || (sourceMapInfo.sourceInfos = /* @__PURE__ */ new Set())).add(info.path); + } + } + if (info.cacheSourceFile) + return info.cacheSourceFile.sourceFile; + if (!info.sourceFileLike) { + info.sourceFileLike = { + get text() { + Debug.fail("shouldnt need text"); + return ""; + }, + getLineAndCharacterOfPosition: (pos) => { + const lineOffset = info.positionToLineOffset(pos); + return { line: lineOffset.line - 1, character: lineOffset.offset - 1 }; + }, + getPositionOfLineAndCharacter: (line, character, allowEdits) => info.lineOffsetToPosition(line + 1, character + 1, allowEdits) + }; + } + return info.sourceFileLike; + } + /** @internal */ + setPerformanceEventHandler(performanceEventHandler) { + this.performanceEventHandler = performanceEventHandler; + } + setHostConfiguration(args) { + var _a; + if (args.file) { + const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(args.file)); + if (info) { + info.setOptions(convertFormatOptions(args.formatOptions), args.preferences); + this.logger.info(`Host configuration update for file ${args.file}`); + } + } else { + if (args.hostInfo !== void 0) { + this.hostConfiguration.hostInfo = args.hostInfo; + this.logger.info(`Host information ${args.hostInfo}`); + } + if (args.formatOptions) { + this.hostConfiguration.formatCodeOptions = { ...this.hostConfiguration.formatCodeOptions, ...convertFormatOptions(args.formatOptions) }; + this.logger.info("Format host information updated"); + } + if (args.preferences) { + const { + lazyConfiguredProjectsFromExternalProject, + includePackageJsonAutoImports + } = this.hostConfiguration.preferences; + this.hostConfiguration.preferences = { ...this.hostConfiguration.preferences, ...args.preferences }; + if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { + this.configuredProjects.forEach((project) => { + if (project.hasExternalProjectRef() && project.pendingUpdateLevel === 2 /* Full */ && !this.pendingProjectUpdates.has(project.getProjectName())) { + project.updateGraph(); + } + }); + } + if (includePackageJsonAutoImports !== args.preferences.includePackageJsonAutoImports) { + this.invalidateProjectPackageJson( + /*packageJsonPath*/ + void 0 + ); + } + } + if (args.extraFileExtensions) { + this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; + this.reloadProjects(); + this.logger.info("Host file extension mappings updated"); + } + if (args.watchOptions) { + this.hostConfiguration.watchOptions = (_a = convertWatchOptions(args.watchOptions)) == null ? void 0 : _a.watchOptions; + this.logger.info(`Host watch options changed to ${JSON.stringify(this.hostConfiguration.watchOptions)}, it will be take effect for next watches.`); + } + } + } + /** @internal */ + getWatchOptions(project) { + return this.getWatchOptionsFromProjectWatchOptions(project.getWatchOptions()); + } + /** @internal */ + getWatchOptionsFromProjectWatchOptions(projectOptions) { + return projectOptions && this.hostConfiguration.watchOptions ? { ...this.hostConfiguration.watchOptions, ...projectOptions } : projectOptions || this.hostConfiguration.watchOptions; + } + closeLog() { + this.logger.close(); + } + /** + * This function rebuilds the project for every file opened by the client + * This does not reload contents of open files from disk. But we could do that if needed + */ + reloadProjects() { + this.logger.info("reload projects."); + this.filenameToScriptInfo.forEach((info) => { + if (this.openFiles.has(info.path)) + return; + if (!info.fileWatcher) + return; + this.onSourceFileChanged(info, this.host.fileExists(info.fileName) ? 1 /* Changed */ : 2 /* Deleted */); + }); + this.pendingProjectUpdates.forEach((_project, projectName) => { + this.throttledOperations.cancel(projectName); + this.pendingProjectUpdates.delete(projectName); + }); + this.throttledOperations.cancel(ensureProjectForOpenFileSchedule); + this.pendingEnsureProjectForOpenFiles = false; + this.configFileExistenceInfoCache.forEach((info) => { + if (info.config) + info.config.updateLevel = 2 /* Full */; + }); + this.reloadConfiguredProjectForFiles( + this.openFiles, + /*clearSemanticCache*/ + true, + /*delayReload*/ + false, + returnTrue, + "User requested reload projects" + ); + this.externalProjects.forEach((project) => { + this.clearSemanticCache(project); + project.updateGraph(); + }); + this.inferredProjects.forEach((project) => this.clearSemanticCache(project)); + this.ensureProjectForOpenFiles(); + } + /** + * This function goes through all the openFiles and tries to file the config file for them. + * If the config file is found and it refers to existing project, it reloads it either immediately + * or schedules it for reload depending on delayReload option + * If there is no existing project it just opens the configured project for the config file + * reloadForInfo provides a way to filter out files to reload configured project for + */ + reloadConfiguredProjectForFiles(openFiles, clearSemanticCache, delayReload, shouldReloadProjectFor, reason) { + const updatedProjects = /* @__PURE__ */ new Map(); + const reloadChildProject = (child) => { + if (!updatedProjects.has(child.canonicalConfigFilePath)) { + updatedProjects.set(child.canonicalConfigFilePath, true); + this.reloadConfiguredProject( + child, + reason, + /*isInitialLoad*/ + false, + clearSemanticCache + ); + } + }; + openFiles == null ? void 0 : openFiles.forEach((openFileValue, path) => { + this.configFileForOpenFiles.delete(path); + if (!shouldReloadProjectFor(openFileValue)) { + return; + } + const info = this.getScriptInfoForPath(path); + Debug.assert(info.isScriptOpen()); + const configFileName = this.getConfigFileNameForFile(info); + if (configFileName) { + const project = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName); + if (!updatedProjects.has(project.canonicalConfigFilePath)) { + updatedProjects.set(project.canonicalConfigFilePath, true); + if (delayReload) { + project.pendingUpdateLevel = 2 /* Full */; + project.pendingUpdateReason = reason; + if (clearSemanticCache) + this.clearSemanticCache(project); + this.delayUpdateProjectGraph(project); + } else { + this.reloadConfiguredProject( + project, + reason, + /*isInitialLoad*/ + false, + clearSemanticCache + ); + if (!projectContainsInfoDirectly(project, info)) { + const referencedProject = forEachResolvedProjectReferenceProject( + project, + info.path, + (child) => { + reloadChildProject(child); + return projectContainsInfoDirectly(child, info); + }, + 1 /* FindCreate */ + ); + if (referencedProject) { + forEachResolvedProjectReferenceProject( + project, + /*fileName*/ + void 0, + reloadChildProject, + 0 /* Find */ + ); + } + } + } + } + } + }); + } + /** + * Remove the root of inferred project if script info is part of another project + */ + removeRootOfInferredProjectIfNowPartOfOtherProject(info) { + Debug.assert(info.containingProjects.length > 0); + const firstProject = info.containingProjects[0]; + if (!firstProject.isOrphan() && isInferredProject(firstProject) && firstProject.isRoot(info) && forEach(info.containingProjects, (p) => p !== firstProject && !p.isOrphan())) { + firstProject.removeFile( + info, + /*fileExists*/ + true, + /*detachFromProject*/ + true + ); + } + } + /** + * This function is to update the project structure for every inferred project. + * It is called on the premise that all the configured projects are + * up to date. + * This will go through open files and assign them to inferred project if open file is not part of any other project + * After that all the inferred project graphs are updated + */ + ensureProjectForOpenFiles() { + this.logger.info("Before ensureProjectForOpenFiles:"); + this.printProjects(); + this.openFiles.forEach((projectRootPath, path) => { + const info = this.getScriptInfoForPath(path); + if (info.isOrphan()) { + this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + } else { + this.removeRootOfInferredProjectIfNowPartOfOtherProject(info); + } + }); + this.pendingEnsureProjectForOpenFiles = false; + this.inferredProjects.forEach(updateProjectIfDirty); + this.logger.info("After ensureProjectForOpenFiles:"); + this.printProjects(); + } + /** + * Open file whose contents is managed by the client + * @param filename is absolute pathname + * @param fileContent is a known version of the file content that is more up to date than the one on disk + */ + openClientFile(fileName, fileContent, scriptKind, projectRootPath) { + return this.openClientFileWithNormalizedPath( + toNormalizedPath(fileName), + fileContent, + scriptKind, + /*hasMixedContent*/ + false, + projectRootPath ? toNormalizedPath(projectRootPath) : void 0 + ); + } + /** @internal */ + getOriginalLocationEnsuringConfiguredProject(project, location) { + const isSourceOfProjectReferenceRedirect = project.isSourceOfProjectReferenceRedirect(location.fileName); + const originalLocation = isSourceOfProjectReferenceRedirect ? location : project.getSourceMapper().tryGetSourcePosition(location); + if (!originalLocation) + return void 0; + const { fileName } = originalLocation; + const scriptInfo = this.getScriptInfo(fileName); + if (!scriptInfo && !this.host.fileExists(fileName)) + return void 0; + const originalFileInfo = { fileName: toNormalizedPath(fileName), path: this.toPath(fileName) }; + const configFileName = this.getConfigFileNameForFile(originalFileInfo); + if (!configFileName) + return void 0; + let configuredProject = this.findConfiguredProjectByProjectName(configFileName); + if (!configuredProject) { + if (project.getCompilerOptions().disableReferencedProjectLoad) { + if (isSourceOfProjectReferenceRedirect) { + return location; + } + return (scriptInfo == null ? void 0 : scriptInfo.containingProjects.length) ? originalLocation : location; + } + configuredProject = this.createAndLoadConfiguredProject(configFileName, `Creating project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}`); + } + updateProjectIfDirty(configuredProject); + const projectContainsOriginalInfo = (project2) => { + const info = this.getScriptInfo(fileName); + return info && projectContainsInfoDirectly(project2, info); + }; + if (configuredProject.isSolution() || !projectContainsOriginalInfo(configuredProject)) { + configuredProject = forEachResolvedProjectReferenceProject( + configuredProject, + fileName, + (child) => { + updateProjectIfDirty(child); + return projectContainsOriginalInfo(child) ? child : void 0; + }, + 2 /* FindCreateLoad */, + `Creating project referenced in solution ${configuredProject.projectName} to find possible configured project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}` + ); + if (!configuredProject) + return void 0; + if (configuredProject === project) + return originalLocation; + } + addOriginalConfiguredProject(configuredProject); + const originalScriptInfo = this.getScriptInfo(fileName); + if (!originalScriptInfo || !originalScriptInfo.containingProjects.length) + return void 0; + originalScriptInfo.containingProjects.forEach((project2) => { + if (isConfiguredProject(project2)) { + addOriginalConfiguredProject(project2); + } + }); + return originalLocation; + function addOriginalConfiguredProject(originalProject) { + if (!project.originalConfiguredProjects) { + project.originalConfiguredProjects = /* @__PURE__ */ new Set(); + } + project.originalConfiguredProjects.add(originalProject.canonicalConfigFilePath); + } + } + /** @internal */ + fileExists(fileName) { + return !!this.getScriptInfoForNormalizedPath(fileName) || this.host.fileExists(fileName); + } + findExternalProjectContainingOpenScriptInfo(info) { + return find(this.externalProjects, (proj) => { + updateProjectIfDirty(proj); + return proj.containsScriptInfo(info); + }); + } + getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { + const info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); + this.openFiles.set(info.path, projectRootPath); + return info; + } + assignProjectToOpenedScriptInfo(info) { + let configFileName; + let configFileErrors; + let project = this.findExternalProjectContainingOpenScriptInfo(info); + let retainProjects; + let projectForConfigFileDiag; + let defaultConfigProjectIsCreated = false; + if (!project && this.serverMode === 0 /* Semantic */) { + configFileName = this.getConfigFileNameForFile(info); + if (configFileName) { + project = this.findConfiguredProjectByProjectName(configFileName); + if (!project) { + project = this.createLoadAndUpdateConfiguredProject(configFileName, `Creating possible configured project for ${info.fileName} to open`); + defaultConfigProjectIsCreated = true; + } else { + updateProjectIfDirty(project); + } + projectForConfigFileDiag = project.containsScriptInfo(info) ? project : void 0; + retainProjects = project; + if (!projectContainsInfoDirectly(project, info)) { + forEachResolvedProjectReferenceProject( + project, + info.path, + (child) => { + updateProjectIfDirty(child); + if (!isArray(retainProjects)) { + retainProjects = [project, child]; + } else { + retainProjects.push(child); + } + if (projectContainsInfoDirectly(child, info)) { + projectForConfigFileDiag = child; + return child; + } + if (!projectForConfigFileDiag && child.containsScriptInfo(info)) { + projectForConfigFileDiag = child; + } + }, + 2 /* FindCreateLoad */, + `Creating project referenced in solution ${project.projectName} to find possible configured project for ${info.fileName} to open` + ); + } + if (projectForConfigFileDiag) { + configFileName = projectForConfigFileDiag.getConfigFilePath(); + if (projectForConfigFileDiag !== project || defaultConfigProjectIsCreated) { + configFileErrors = projectForConfigFileDiag.getAllProjectErrors(); + this.sendConfigFileDiagEvent(projectForConfigFileDiag, info.fileName); + } + } else { + configFileName = void 0; + } + this.createAncestorProjects(info, project); + } + } + info.containingProjects.forEach(updateProjectIfDirty); + if (info.isOrphan()) { + if (isArray(retainProjects)) { + retainProjects.forEach((project2) => this.sendConfigFileDiagEvent(project2, info.fileName)); + } else if (retainProjects) { + this.sendConfigFileDiagEvent(retainProjects, info.fileName); + } + Debug.assert(this.openFiles.has(info.path)); + this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path)); + } + Debug.assert(!info.isOrphan()); + return { configFileName, configFileErrors, retainProjects }; + } + createAncestorProjects(info, project) { + if (!info.isAttached(project)) + return; + while (true) { + if (!project.isInitialLoadPending() && (!project.getCompilerOptions().composite || project.getCompilerOptions().disableSolutionSearching)) + return; + const configFileName = this.getConfigFileNameForFile({ + fileName: project.getConfigFilePath(), + path: info.path, + configFileInfo: true + }); + if (!configFileName) + return; + const ancestor = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProjectWithDelayLoad(configFileName, `Creating project possibly referencing default composite project ${project.getProjectName()} of open file ${info.fileName}`); + if (ancestor.isInitialLoadPending()) { + ancestor.setPotentialProjectReference(project.canonicalConfigFilePath); + } + project = ancestor; + } + } + /** @internal */ + loadAncestorProjectTree(forProjects) { + forProjects = forProjects || mapDefinedEntries( + this.configuredProjects, + (key, project) => !project.isInitialLoadPending() ? [key, true] : void 0 + ); + const seenProjects = /* @__PURE__ */ new Set(); + for (const project of arrayFrom(this.configuredProjects.values())) { + if (forEachPotentialProjectReference(project, (potentialRefPath) => forProjects.has(potentialRefPath))) { + updateProjectIfDirty(project); + } + this.ensureProjectChildren(project, forProjects, seenProjects); + } + } + ensureProjectChildren(project, forProjects, seenProjects) { + var _a; + if (!tryAddToSet(seenProjects, project.canonicalConfigFilePath)) + return; + if (project.getCompilerOptions().disableReferencedProjectLoad) + return; + const children = (_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences(); + if (!children) + return; + for (const child of children) { + if (!child) + continue; + const referencedProject = forEachResolvedProjectReference(child.references, (ref) => forProjects.has(ref.sourceFile.path) ? ref : void 0); + if (!referencedProject) + continue; + const configFileName = toNormalizedPath(child.sourceFile.fileName); + const childProject = project.projectService.findConfiguredProjectByProjectName(configFileName) || project.projectService.createAndLoadConfiguredProject(configFileName, `Creating project referenced by : ${project.projectName} as it references project ${referencedProject.sourceFile.fileName}`); + updateProjectIfDirty(childProject); + this.ensureProjectChildren(childProject, forProjects, seenProjects); + } + } + cleanupAfterOpeningFile(toRetainConfigProjects) { + this.removeOrphanConfiguredProjects(toRetainConfigProjects); + for (const inferredProject of this.inferredProjects.slice()) { + if (inferredProject.isOrphan()) { + this.removeProject(inferredProject); + } + } + this.removeOrphanScriptInfos(); + } + openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { + const info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath); + const { retainProjects, ...result } = this.assignProjectToOpenedScriptInfo(info); + this.cleanupAfterOpeningFile(retainProjects); + this.telemetryOnOpenFile(info); + this.printProjects(); + return result; + } + removeOrphanConfiguredProjects(toRetainConfiguredProjects) { + const toRemoveConfiguredProjects = new Map(this.configuredProjects); + const markOriginalProjectsAsUsed = (project) => { + if (!project.isOrphan() && project.originalConfiguredProjects) { + project.originalConfiguredProjects.forEach( + (_value, configuredProjectPath) => { + const project2 = this.getConfiguredProjectByCanonicalConfigFilePath(configuredProjectPath); + return project2 && retainConfiguredProject(project2); + } + ); + } + }; + if (toRetainConfiguredProjects) { + if (isArray(toRetainConfiguredProjects)) { + toRetainConfiguredProjects.forEach(retainConfiguredProject); + } else { + retainConfiguredProject(toRetainConfiguredProjects); + } + } + this.inferredProjects.forEach(markOriginalProjectsAsUsed); + this.externalProjects.forEach(markOriginalProjectsAsUsed); + this.configuredProjects.forEach((project) => { + if (project.hasOpenRef()) { + retainConfiguredProject(project); + } else if (toRemoveConfiguredProjects.has(project.canonicalConfigFilePath)) { + forEachReferencedProject( + project, + (ref) => isRetained(ref) && retainConfiguredProject(project) + ); + } + }); + toRemoveConfiguredProjects.forEach((project) => this.removeProject(project)); + function isRetained(project) { + return project.hasOpenRef() || !toRemoveConfiguredProjects.has(project.canonicalConfigFilePath); + } + function retainConfiguredProject(project) { + if (toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath)) { + markOriginalProjectsAsUsed(project); + forEachReferencedProject(project, retainConfiguredProject); + } + } + } + removeOrphanScriptInfos() { + const toRemoveScriptInfos = new Map(this.filenameToScriptInfo); + this.filenameToScriptInfo.forEach((info) => { + if (!info.isScriptOpen() && info.isOrphan() && !info.isContainedByBackgroundProject()) { + if (!info.sourceMapFilePath) + return; + let sourceInfos; + if (isString(info.sourceMapFilePath)) { + const sourceMapInfo = this.getScriptInfoForPath(info.sourceMapFilePath); + sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos; + } else { + sourceInfos = info.sourceMapFilePath.sourceInfos; + } + if (!sourceInfos) + return; + if (!forEachKey(sourceInfos, (path) => { + const info2 = this.getScriptInfoForPath(path); + return !!info2 && (info2.isScriptOpen() || !info2.isOrphan()); + })) { + return; + } + } + toRemoveScriptInfos.delete(info.path); + if (info.sourceMapFilePath) { + let sourceInfos; + if (isString(info.sourceMapFilePath)) { + toRemoveScriptInfos.delete(info.sourceMapFilePath); + const sourceMapInfo = this.getScriptInfoForPath(info.sourceMapFilePath); + sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos; + } else { + sourceInfos = info.sourceMapFilePath.sourceInfos; + } + if (sourceInfos) { + sourceInfos.forEach((_value, path) => toRemoveScriptInfos.delete(path)); + } + } + }); + toRemoveScriptInfos.forEach((info) => { + this.stopWatchingScriptInfo(info); + this.deleteScriptInfo(info); + info.closeSourceMapFileWatcher(); + }); + } + telemetryOnOpenFile(scriptInfo) { + if (this.serverMode !== 0 /* Semantic */ || !this.eventHandler || !scriptInfo.isJavaScript() || !addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) { + return; + } + const project = this.ensureDefaultProjectForFile(scriptInfo); + if (!project.languageServiceEnabled) { + return; + } + const sourceFile = project.getSourceFile(scriptInfo.path); + const checkJs = !!sourceFile && !!sourceFile.checkJsDirective; + this.eventHandler({ eventName: OpenFileInfoTelemetryEvent, data: { info: { checkJs } } }); + } + closeClientFile(uncheckedFileName, skipAssignOrphanScriptInfosToInferredProject) { + const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName)); + const result = info ? this.closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) : false; + if (!skipAssignOrphanScriptInfosToInferredProject) { + this.printProjects(); + } + return result; + } + collectChanges(lastKnownProjectVersions, currentProjects, includeProjectReferenceRedirectInfo, result) { + for (const proj of currentProjects) { + const knownProject = find(lastKnownProjectVersions, (p) => p.projectName === proj.getProjectName()); + result.push(proj.getChangesSinceVersion(knownProject && knownProject.version, includeProjectReferenceRedirectInfo)); + } + } + /** @internal */ + synchronizeProjectList(knownProjects, includeProjectReferenceRedirectInfo) { + const files = []; + this.collectChanges(knownProjects, this.externalProjects, includeProjectReferenceRedirectInfo, files); + this.collectChanges(knownProjects, this.configuredProjects.values(), includeProjectReferenceRedirectInfo, files); + this.collectChanges(knownProjects, this.inferredProjects, includeProjectReferenceRedirectInfo, files); + return files; + } + /** @internal */ + applyChangesInOpenFiles(openFiles, changedFiles, closedFiles) { + let openScriptInfos; + let assignOrphanScriptInfosToInferredProject = false; + if (openFiles) { + for (const file of openFiles) { + const info = this.getOrCreateOpenScriptInfo( + toNormalizedPath(file.fileName), + file.content, + tryConvertScriptKindName(file.scriptKind), + file.hasMixedContent, + file.projectRootPath ? toNormalizedPath(file.projectRootPath) : void 0 + ); + (openScriptInfos || (openScriptInfos = [])).push(info); + } + } + if (changedFiles) { + for (const file of changedFiles) { + const scriptInfo = this.getScriptInfo(file.fileName); + Debug.assert(!!scriptInfo); + this.applyChangesToFile(scriptInfo, file.changes); + } + } + if (closedFiles) { + for (const file of closedFiles) { + assignOrphanScriptInfosToInferredProject = this.closeClientFile( + file, + /*skipAssignOrphanScriptInfosToInferredProject*/ + true + ) || assignOrphanScriptInfosToInferredProject; + } + } + let retainProjects; + if (openScriptInfos) { + retainProjects = flatMap(openScriptInfos, (info) => this.assignProjectToOpenedScriptInfo(info).retainProjects); + } + if (assignOrphanScriptInfosToInferredProject) { + this.assignOrphanScriptInfosToInferredProject(); + } + if (openScriptInfos) { + this.cleanupAfterOpeningFile(retainProjects); + openScriptInfos.forEach((info) => this.telemetryOnOpenFile(info)); + this.printProjects(); + } else if (length(closedFiles)) { + this.printProjects(); + } + } + /** @internal */ + applyChangesToFile(scriptInfo, changes) { + for (const change of changes) { + scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); + } + } + closeConfiguredProjectReferencedFromExternalProject(configFile) { + const configuredProject = this.findConfiguredProjectByProjectName(configFile); + if (configuredProject) { + configuredProject.deleteExternalProjectReference(); + if (!configuredProject.hasOpenRef()) { + this.removeProject(configuredProject); + return; + } + } + } + closeExternalProject(uncheckedFileName) { + const fileName = toNormalizedPath(uncheckedFileName); + const configFiles = this.externalProjectToConfiguredProjectMap.get(fileName); + if (configFiles) { + for (const configFile of configFiles) { + this.closeConfiguredProjectReferencedFromExternalProject(configFile); + } + this.externalProjectToConfiguredProjectMap.delete(fileName); + } else { + const externalProject = this.findExternalProjectByProjectName(uncheckedFileName); + if (externalProject) { + this.removeProject(externalProject); + } + } + } + openExternalProjects(projects) { + const projectsToClose = arrayToMap(this.externalProjects, (p) => p.getProjectName(), (_) => true); + forEachKey(this.externalProjectToConfiguredProjectMap, (externalProjectName) => { + projectsToClose.set(externalProjectName, true); + }); + for (const externalProject of projects) { + this.openExternalProject(externalProject); + projectsToClose.delete(externalProject.projectFileName); + } + forEachKey(projectsToClose, (externalProjectName) => { + this.closeExternalProject(externalProjectName); + }); + } + static escapeFilenameForRegex(filename) { + return filename.replace(this.filenameEscapeRegexp, "\\$&"); + } + resetSafeList() { + this.safelist = defaultTypeSafeList; + } + applySafeList(proj) { + const { rootFiles } = proj; + const typeAcquisition = proj.typeAcquisition; + Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now"); + if (typeAcquisition.enable === false || typeAcquisition.disableFilenameBasedTypeAcquisition) { + return []; + } + const typeAcqInclude = typeAcquisition.include || (typeAcquisition.include = []); + const excludeRules = []; + const normalizedNames = rootFiles.map((f) => normalizeSlashes(f.fileName)); + const excludedFiles = []; + for (const name of Object.keys(this.safelist)) { + const rule2 = this.safelist[name]; + for (const root of normalizedNames) { + if (rule2.match.test(root)) { + this.logger.info(`Excluding files based on rule ${name} matching file '${root}'`); + if (rule2.types) { + for (const type of rule2.types) { + if (!typeAcqInclude.includes(type)) { + typeAcqInclude.push(type); + } + } + } + if (rule2.exclude) { + for (const exclude of rule2.exclude) { + const processedRule = root.replace(rule2.match, (...groups) => { + return exclude.map((groupNumberOrString) => { + if (typeof groupNumberOrString === "number") { + if (!isString(groups[groupNumberOrString])) { + this.logger.info(`Incorrect RegExp specification in safelist rule ${name} - not enough groups`); + return "\\*"; + } + return _ProjectService.escapeFilenameForRegex(groups[groupNumberOrString]); + } + return groupNumberOrString; + }).join(""); + }); + if (!excludeRules.includes(processedRule)) { + excludeRules.push(processedRule); + } + } + } else { + const escaped = _ProjectService.escapeFilenameForRegex(root); + if (!excludeRules.includes(escaped)) { + excludeRules.push(escaped); + } + } + } + } + } + const excludeRegexes = excludeRules.map((e) => new RegExp(e, "i")); + const filesToKeep = []; + for (let i = 0; i < proj.rootFiles.length; i++) { + if (excludeRegexes.some((re) => re.test(normalizedNames[i]))) { + excludedFiles.push(normalizedNames[i]); + } else { + let exclude = false; + if (typeAcquisition.enable) { + const baseName = getBaseFileName(toFileNameLowerCase(normalizedNames[i])); + if (fileExtensionIs(baseName, "js")) { + const inferredTypingName = removeFileExtension(baseName); + const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName); + const typeName = this.legacySafelist.get(cleanedTypingName); + if (typeName !== void 0) { + this.logger.info(`Excluded '${normalizedNames[i]}' because it matched ${cleanedTypingName} from the legacy safelist`); + excludedFiles.push(normalizedNames[i]); + exclude = true; + if (!typeAcqInclude.includes(typeName)) { + typeAcqInclude.push(typeName); + } + } + } + } + if (!exclude) { + if (/^.+[.-]min\.js$/.test(normalizedNames[i])) { + excludedFiles.push(normalizedNames[i]); + } else { + filesToKeep.push(proj.rootFiles[i]); + } + } + } + } + proj.rootFiles = filesToKeep; + return excludedFiles; + } + openExternalProject(proj) { + proj.typeAcquisition = proj.typeAcquisition || {}; + proj.typeAcquisition.include = proj.typeAcquisition.include || []; + proj.typeAcquisition.exclude = proj.typeAcquisition.exclude || []; + if (proj.typeAcquisition.enable === void 0) { + proj.typeAcquisition.enable = hasNoTypeScriptSource(proj.rootFiles.map((f) => f.fileName)); + } + const excludedFiles = this.applySafeList(proj); + let tsConfigFiles; + const rootFiles = []; + for (const file of proj.rootFiles) { + const normalized = toNormalizedPath(file.fileName); + if (getBaseConfigFileName(normalized)) { + if (this.serverMode === 0 /* Semantic */ && this.host.fileExists(normalized)) { + (tsConfigFiles || (tsConfigFiles = [])).push(normalized); + } + } else { + rootFiles.push(file); + } + } + if (tsConfigFiles) { + tsConfigFiles.sort(); + } + const externalProject = this.findExternalProjectByProjectName(proj.projectFileName); + let exisingConfigFiles; + if (externalProject) { + externalProject.excludedFiles = excludedFiles; + if (!tsConfigFiles) { + const compilerOptions = convertCompilerOptions(proj.options); + const watchOptionsAndErrors = convertWatchOptions(proj.options, externalProject.getCurrentDirectory()); + const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(proj.projectFileName, compilerOptions, proj.rootFiles, externalFilePropertyReader); + if (lastFileExceededProgramSize) { + externalProject.disableLanguageService(lastFileExceededProgramSize); + } else { + externalProject.enableLanguageService(); + } + externalProject.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors); + this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions); + externalProject.updateGraph(); + return; + } + this.closeExternalProject(proj.projectFileName); + } else if (this.externalProjectToConfiguredProjectMap.get(proj.projectFileName)) { + if (!tsConfigFiles) { + this.closeExternalProject(proj.projectFileName); + } else { + const oldConfigFiles = this.externalProjectToConfiguredProjectMap.get(proj.projectFileName); + let iNew = 0; + let iOld = 0; + while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) { + const newConfig = tsConfigFiles[iNew]; + const oldConfig = oldConfigFiles[iOld]; + if (oldConfig < newConfig) { + this.closeConfiguredProjectReferencedFromExternalProject(oldConfig); + iOld++; + } else if (oldConfig > newConfig) { + iNew++; + } else { + (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig); + iOld++; + iNew++; + } + } + for (let i = iOld; i < oldConfigFiles.length; i++) { + this.closeConfiguredProjectReferencedFromExternalProject(oldConfigFiles[i]); + } + } + } + if (tsConfigFiles) { + this.externalProjectToConfiguredProjectMap.set(proj.projectFileName, tsConfigFiles); + for (const tsconfigFile of tsConfigFiles) { + let project = this.findConfiguredProjectByProjectName(tsconfigFile); + if (!project) { + project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? this.createConfiguredProjectWithDelayLoad(tsconfigFile, `Creating configured project in external project: ${proj.projectFileName}`) : this.createLoadAndUpdateConfiguredProject(tsconfigFile, `Creating configured project in external project: ${proj.projectFileName}`); + } + if (project && !contains(exisingConfigFiles, tsconfigFile)) { + project.addExternalProjectReference(); + } + } + } else { + this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); + const project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + project.updateGraph(); + } + } + hasDeferredExtension() { + for (const extension of this.hostConfiguration.extraFileExtensions) { + if (extension.scriptKind === 7 /* Deferred */) { + return true; + } + } + return false; + } + /** + * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin either asynchronously or synchronously + * @internal + */ + requestEnablePlugin(project, pluginConfigEntry, searchPaths) { + if (!this.host.importPlugin && !this.host.require) { + this.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); + return; + } + this.logger.info(`Enabling plugin ${pluginConfigEntry.name} from candidate paths: ${searchPaths.join(",")}`); + if (!pluginConfigEntry.name || parsePackageName(pluginConfigEntry.name).rest) { + this.logger.info(`Skipped loading plugin ${pluginConfigEntry.name || JSON.stringify(pluginConfigEntry)} because only package name is allowed plugin name`); + return; + } + if (this.host.importPlugin) { + const importPromise = Project3.importServicePluginAsync( + pluginConfigEntry, + searchPaths, + this.host, + (s) => this.logger.info(s) + ); + this.pendingPluginEnablements ?? (this.pendingPluginEnablements = /* @__PURE__ */ new Map()); + let promises = this.pendingPluginEnablements.get(project); + if (!promises) + this.pendingPluginEnablements.set(project, promises = []); + promises.push(importPromise); + return; + } + this.endEnablePlugin( + project, + Project3.importServicePluginSync( + pluginConfigEntry, + searchPaths, + this.host, + (s) => this.logger.info(s) + ) + ); + } + /** + * Performs the remaining steps of enabling a plugin after its module has been instantiated. + * @internal + */ + endEnablePlugin(project, { pluginConfigEntry, resolvedModule, errorLogs }) { + var _a; + if (resolvedModule) { + const configurationOverride = (_a = this.currentPluginConfigOverrides) == null ? void 0 : _a.get(pluginConfigEntry.name); + if (configurationOverride) { + const pluginName = pluginConfigEntry.name; + pluginConfigEntry = configurationOverride; + pluginConfigEntry.name = pluginName; + } + project.enableProxy(resolvedModule, pluginConfigEntry); + } else { + forEach(errorLogs, (message) => this.logger.info(message)); + this.logger.info(`Couldn't find ${pluginConfigEntry.name}`); + } + } + /** @internal */ + hasNewPluginEnablementRequests() { + return !!this.pendingPluginEnablements; + } + /** @internal */ + hasPendingPluginEnablements() { + return !!this.currentPluginEnablementPromise; + } + /** + * Waits for any ongoing plugin enablement requests to complete. + * + * @internal + */ + async waitForPendingPlugins() { + while (this.currentPluginEnablementPromise) { + await this.currentPluginEnablementPromise; + } + } + /** + * Starts enabling any requested plugins without waiting for the result. + * + * @internal + */ + enableRequestedPlugins() { + if (this.pendingPluginEnablements) { + void this.enableRequestedPluginsAsync(); + } + } + async enableRequestedPluginsAsync() { + if (this.currentPluginEnablementPromise) { + await this.waitForPendingPlugins(); + } + if (!this.pendingPluginEnablements) { + return; + } + const entries = arrayFrom(this.pendingPluginEnablements.entries()); + this.pendingPluginEnablements = void 0; + this.currentPluginEnablementPromise = this.enableRequestedPluginsWorker(entries); + await this.currentPluginEnablementPromise; + } + async enableRequestedPluginsWorker(pendingPlugins) { + Debug.assert(this.currentPluginEnablementPromise === void 0); + await Promise.all(map(pendingPlugins, ([project, promises]) => this.enableRequestedPluginsForProjectAsync(project, promises))); + this.currentPluginEnablementPromise = void 0; + this.sendProjectsUpdatedInBackgroundEvent(); + } + async enableRequestedPluginsForProjectAsync(project, promises) { + const results = await Promise.all(promises); + if (project.isClosed()) { + return; + } + for (const result of results) { + this.endEnablePlugin(project, result); + } + this.delayUpdateProjectGraph(project); + } + configurePlugin(args) { + this.forEachEnabledProject((project) => project.onPluginConfigurationChanged(args.pluginName, args.configuration)); + this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || /* @__PURE__ */ new Map(); + this.currentPluginConfigOverrides.set(args.pluginName, args.configuration); + } + /** @internal */ + getPackageJsonsVisibleToFile(fileName, rootDir) { + const packageJsonCache = this.packageJsonCache; + const rootPath = rootDir && this.toPath(rootDir); + const filePath = this.toPath(fileName); + const result = []; + const processDirectory = (directory) => { + switch (packageJsonCache.directoryHasPackageJson(directory)) { + case 3 /* Maybe */: + packageJsonCache.searchDirectoryAndAncestors(directory); + return processDirectory(directory); + case -1 /* True */: + const packageJsonFileName = combinePaths(directory, "package.json"); + this.watchPackageJsonFile(packageJsonFileName); + const info = packageJsonCache.getInDirectory(directory); + if (info) + result.push(info); + } + if (rootPath && rootPath === directory) { + return true; + } + }; + forEachAncestorDirectory(getDirectoryPath(filePath), processDirectory); + return result; + } + /** @internal */ + getNearestAncestorDirectoryWithPackageJson(fileName) { + return forEachAncestorDirectory(fileName, (directory) => { + switch (this.packageJsonCache.directoryHasPackageJson(this.toPath(directory))) { + case -1 /* True */: + return directory; + case 0 /* False */: + return void 0; + case 3 /* Maybe */: + return this.host.fileExists(combinePaths(directory, "package.json")) ? directory : void 0; + } + }); + } + /** @internal */ + watchPackageJsonFile(path) { + const watchers = this.packageJsonFilesMap || (this.packageJsonFilesMap = /* @__PURE__ */ new Map()); + if (!watchers.has(path)) { + this.invalidateProjectPackageJson(path); + watchers.set( + path, + this.watchFactory.watchFile( + path, + (fileName, eventKind) => { + const path2 = this.toPath(fileName); + switch (eventKind) { + case 0 /* Created */: + return Debug.fail(); + case 1 /* Changed */: + this.packageJsonCache.addOrUpdate(path2); + this.invalidateProjectPackageJson(path2); + break; + case 2 /* Deleted */: + this.packageJsonCache.delete(path2); + this.invalidateProjectPackageJson(path2); + watchers.get(path2).close(); + watchers.delete(path2); + } + }, + 250 /* Low */, + this.hostConfiguration.watchOptions, + WatchType.PackageJson + ) + ); + } + } + /** @internal */ + onAddPackageJson(path) { + this.packageJsonCache.addOrUpdate(path); + this.watchPackageJsonFile(path); + } + /** @internal */ + includePackageJsonAutoImports() { + switch (this.hostConfiguration.preferences.includePackageJsonAutoImports) { + case "on": + return 1 /* On */; + case "off": + return 0 /* Off */; + default: + return 2 /* Auto */; + } + } + /** @internal */ + invalidateProjectPackageJson(packageJsonPath) { + this.configuredProjects.forEach(invalidate); + this.inferredProjects.forEach(invalidate); + this.externalProjects.forEach(invalidate); + function invalidate(project) { + if (packageJsonPath) { + project.onPackageJsonChange(packageJsonPath); + } else { + project.onAutoImportProviderSettingsChanged(); + } + } + } + /** @internal */ + getIncompleteCompletionsCache() { + return this.incompleteCompletionsCache || (this.incompleteCompletionsCache = createIncompleteCompletionsCache()); + } + }; + /** Makes a filename safe to insert in a RegExp */ + _ProjectService.filenameEscapeRegexp = /[-/\\^$*+?.()|[\]{}]/g; + ProjectService3 = _ProjectService; + } + }); + + // src/server/moduleSpecifierCache.ts + function createModuleSpecifierCache(host) { + let containedNodeModulesWatchers; + let cache; + let currentKey; + const result = { + get(fromFileName, toFileName2, preferences, options) { + if (!cache || currentKey !== key(fromFileName, preferences, options)) + return void 0; + return cache.get(toFileName2); + }, + set(fromFileName, toFileName2, preferences, options, modulePaths, moduleSpecifiers) { + ensureCache(fromFileName, preferences, options).set(toFileName2, createInfo( + modulePaths, + moduleSpecifiers, + /*isBlockedByPackageJsonDependencies*/ + false + )); + if (moduleSpecifiers) { + for (const p of modulePaths) { + if (p.isInNodeModules) { + const nodeModulesPath = p.path.substring(0, p.path.indexOf(nodeModulesPathPart) + nodeModulesPathPart.length - 1); + if (!(containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.has(nodeModulesPath))) { + (containedNodeModulesWatchers || (containedNodeModulesWatchers = /* @__PURE__ */ new Map())).set( + nodeModulesPath, + host.watchNodeModulesForPackageJsonChanges(nodeModulesPath) + ); + } + } + } + } + }, + setModulePaths(fromFileName, toFileName2, preferences, options, modulePaths) { + const cache2 = ensureCache(fromFileName, preferences, options); + const info = cache2.get(toFileName2); + if (info) { + info.modulePaths = modulePaths; + } else { + cache2.set(toFileName2, createInfo( + modulePaths, + /*moduleSpecifiers*/ + void 0, + /*isBlockedByPackageJsonDependencies*/ + void 0 + )); + } + }, + setBlockedByPackageJsonDependencies(fromFileName, toFileName2, preferences, options, isBlockedByPackageJsonDependencies) { + const cache2 = ensureCache(fromFileName, preferences, options); + const info = cache2.get(toFileName2); + if (info) { + info.isBlockedByPackageJsonDependencies = isBlockedByPackageJsonDependencies; + } else { + cache2.set(toFileName2, createInfo( + /*modulePaths*/ + void 0, + /*moduleSpecifiers*/ + void 0, + isBlockedByPackageJsonDependencies + )); + } + }, + clear() { + containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.forEach((watcher) => watcher.close()); + cache == null ? void 0 : cache.clear(); + containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.clear(); + currentKey = void 0; + }, + count() { + return cache ? cache.size : 0; + } + }; + if (Debug.isDebugging) { + Object.defineProperty(result, "__cache", { get: () => cache }); + } + return result; + function ensureCache(fromFileName, preferences, options) { + const newKey = key(fromFileName, preferences, options); + if (cache && currentKey !== newKey) { + result.clear(); + } + currentKey = newKey; + return cache || (cache = /* @__PURE__ */ new Map()); + } + function key(fromFileName, preferences, options) { + return `${fromFileName},${preferences.importModuleSpecifierEnding},${preferences.importModuleSpecifierPreference},${options.overrideImportMode}`; + } + function createInfo(modulePaths, moduleSpecifiers, isBlockedByPackageJsonDependencies) { + return { modulePaths, moduleSpecifiers, isBlockedByPackageJsonDependencies }; + } + } + var init_moduleSpecifierCache = __esm({ + "src/server/moduleSpecifierCache.ts"() { + "use strict"; + init_ts7(); + } + }); + + // src/server/packageJsonCache.ts + function createPackageJsonCache(host) { + const packageJsons = /* @__PURE__ */ new Map(); + const directoriesWithoutPackageJson = /* @__PURE__ */ new Map(); + return { + addOrUpdate, + forEach: packageJsons.forEach.bind(packageJsons), + get: packageJsons.get.bind(packageJsons), + delete: (fileName) => { + packageJsons.delete(fileName); + directoriesWithoutPackageJson.set(getDirectoryPath(fileName), true); + }, + getInDirectory: (directory) => { + return packageJsons.get(combinePaths(directory, "package.json")) || void 0; + }, + directoryHasPackageJson, + searchDirectoryAndAncestors: (directory) => { + forEachAncestorDirectory(directory, (ancestor) => { + if (directoryHasPackageJson(ancestor) !== 3 /* Maybe */) { + return true; + } + const packageJsonFileName = host.toPath(combinePaths(ancestor, "package.json")); + if (tryFileExists(host, packageJsonFileName)) { + addOrUpdate(packageJsonFileName); + } else { + directoriesWithoutPackageJson.set(ancestor, true); + } + }); + } + }; + function addOrUpdate(fileName) { + const packageJsonInfo = Debug.checkDefined(createPackageJsonInfo(fileName, host.host)); + packageJsons.set(fileName, packageJsonInfo); + directoriesWithoutPackageJson.delete(getDirectoryPath(fileName)); + } + function directoryHasPackageJson(directory) { + return packageJsons.has(combinePaths(directory, "package.json")) ? -1 /* True */ : directoriesWithoutPackageJson.has(directory) ? 0 /* False */ : 3 /* Maybe */; + } + } + var init_packageJsonCache = __esm({ + "src/server/packageJsonCache.ts"() { + "use strict"; + init_ts7(); + } + }); + + // src/server/session.ts + function hrTimeToMilliseconds(time) { + const seconds = time[0]; + const nanoseconds = time[1]; + return (1e9 * seconds + nanoseconds) / 1e6; + } + function isDeclarationFileInJSOnlyNonConfiguredProject(project, file) { + if ((isInferredProject(project) || isExternalProject(project)) && project.isJsOnlyProject()) { + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + return scriptInfo && !scriptInfo.isJavaScript(); + } + return false; + } + function dtsChangeCanAffectEmit(compilationSettings) { + return getEmitDeclarations(compilationSettings) || !!compilationSettings.emitDecoratorMetadata; + } + function formatDiag(fileName, project, diag2) { + const scriptInfo = project.getScriptInfoForNormalizedPath(fileName); + return { + start: scriptInfo.positionToLineOffset(diag2.start), + end: scriptInfo.positionToLineOffset(diag2.start + diag2.length), + // TODO: GH#18217 + text: flattenDiagnosticMessageText(diag2.messageText, "\n"), + code: diag2.code, + category: diagnosticCategoryName(diag2), + reportsUnnecessary: diag2.reportsUnnecessary, + reportsDeprecated: diag2.reportsDeprecated, + source: diag2.source, + relatedInformation: map(diag2.relatedInformation, formatRelatedInformation) + }; + } + function formatRelatedInformation(info) { + if (!info.file) { + return { + message: flattenDiagnosticMessageText(info.messageText, "\n"), + category: diagnosticCategoryName(info), + code: info.code + }; + } + return { + span: { + start: convertToLocation(getLineAndCharacterOfPosition(info.file, info.start)), + end: convertToLocation(getLineAndCharacterOfPosition(info.file, info.start + info.length)), + // TODO: GH#18217 + file: info.file.fileName + }, + message: flattenDiagnosticMessageText(info.messageText, "\n"), + category: diagnosticCategoryName(info), + code: info.code + }; + } + function convertToLocation(lineAndCharacter) { + return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 }; + } + function formatDiagnosticToProtocol(diag2, includeFileName) { + const start = diag2.file && convertToLocation(getLineAndCharacterOfPosition(diag2.file, diag2.start)); + const end = diag2.file && convertToLocation(getLineAndCharacterOfPosition(diag2.file, diag2.start + diag2.length)); + const text = flattenDiagnosticMessageText(diag2.messageText, "\n"); + const { code, source } = diag2; + const category = diagnosticCategoryName(diag2); + const common = { + start, + end, + text, + code, + category, + reportsUnnecessary: diag2.reportsUnnecessary, + reportsDeprecated: diag2.reportsDeprecated, + source, + relatedInformation: map(diag2.relatedInformation, formatRelatedInformation) + }; + return includeFileName ? { ...common, fileName: diag2.file && diag2.file.fileName } : common; + } + function allEditsBeforePos(edits, pos) { + return edits.every((edit) => textSpanEnd(edit.span) < pos); + } + function formatMessage2(msg, logger, byteLength, newLine) { + const verboseLogging = logger.hasLevel(3 /* verbose */); + const json = JSON.stringify(msg); + if (verboseLogging) { + logger.info(`${msg.type}:${stringifyIndented(msg)}`); + } + const len = byteLength(json, "utf8"); + return `Content-Length: ${1 + len}\r +\r +${json}${newLine}`; + } + function toEvent(eventName, body) { + return { + seq: 0, + type: "event", + event: eventName, + body + }; + } + function combineProjectOutput(defaultValue, getValue, projects, action) { + const outputs = flatMapToMutable(isArray(projects) ? projects : projects.projects, (project) => action(project, defaultValue)); + if (!isArray(projects) && projects.symLinkedProjects) { + projects.symLinkedProjects.forEach((projects2, path) => { + const value = getValue(path); + outputs.push(...flatMap(projects2, (project) => action(project, value))); + }); + } + return deduplicate(outputs, equateValues); + } + function createDocumentSpanSet() { + return createSet(({ textSpan }) => textSpan.start + 100003 * textSpan.length, documentSpansEqual); + } + function getRenameLocationsWorker(projects, defaultProject, initialLocation, findInStrings, findInComments, preferences) { + const perProjectResults = getPerProjectReferences( + projects, + defaultProject, + initialLocation, + /*isForRename*/ + true, + (project, position) => project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, preferences), + (renameLocation, cb) => cb(documentSpanLocation(renameLocation)) + ); + if (isArray(perProjectResults)) { + return perProjectResults; + } + const results = []; + const seen = createDocumentSpanSet(); + perProjectResults.forEach((projectResults, project) => { + for (const result of projectResults) { + if (!seen.has(result) && !getMappedLocationForProject(documentSpanLocation(result), project)) { + results.push(result); + seen.add(result); + } + } + }); + return results; + } + function getDefinitionLocation(defaultProject, initialLocation, isForRename) { + const infos = defaultProject.getLanguageService().getDefinitionAtPosition( + initialLocation.fileName, + initialLocation.pos, + /*searchOtherFilesOnly*/ + false, + /*stopAtAlias*/ + isForRename + ); + const info = infos && firstOrUndefined(infos); + return info && !info.isLocal ? { fileName: info.fileName, pos: info.textSpan.start } : void 0; + } + function getReferencesWorker(projects, defaultProject, initialLocation, logger) { + var _a, _b; + const perProjectResults = getPerProjectReferences( + projects, + defaultProject, + initialLocation, + /*isForRename*/ + false, + (project, position) => { + logger.info(`Finding references to ${position.fileName} position ${position.pos} in project ${project.getProjectName()}`); + return project.getLanguageService().findReferences(position.fileName, position.pos); + }, + (referencedSymbol, cb) => { + cb(documentSpanLocation(referencedSymbol.definition)); + for (const ref of referencedSymbol.references) { + cb(documentSpanLocation(ref)); + } + } + ); + if (isArray(perProjectResults)) { + return perProjectResults; + } + const defaultProjectResults = perProjectResults.get(defaultProject); + if (((_b = (_a = defaultProjectResults == null ? void 0 : defaultProjectResults[0]) == null ? void 0 : _a.references[0]) == null ? void 0 : _b.isDefinition) === void 0) { + perProjectResults.forEach((projectResults) => { + for (const referencedSymbol of projectResults) { + for (const ref of referencedSymbol.references) { + delete ref.isDefinition; + } + } + }); + } else { + const knownSymbolSpans = createDocumentSpanSet(); + for (const referencedSymbol of defaultProjectResults) { + for (const ref of referencedSymbol.references) { + if (ref.isDefinition) { + knownSymbolSpans.add(ref); + break; + } + } + } + const updatedProjects = /* @__PURE__ */ new Set(); + while (true) { + let progress = false; + perProjectResults.forEach((referencedSymbols, project) => { + if (updatedProjects.has(project)) + return; + const updated = project.getLanguageService().updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans); + if (updated) { + updatedProjects.add(project); + progress = true; + } + }); + if (!progress) + break; + } + perProjectResults.forEach((referencedSymbols, project) => { + if (updatedProjects.has(project)) + return; + for (const referencedSymbol of referencedSymbols) { + for (const ref of referencedSymbol.references) { + ref.isDefinition = false; + } + } + }); + } + const results = []; + const seenRefs = createDocumentSpanSet(); + perProjectResults.forEach((projectResults, project) => { + for (const referencedSymbol of projectResults) { + const mappedDefinitionFile = getMappedLocationForProject(documentSpanLocation(referencedSymbol.definition), project); + const definition = mappedDefinitionFile === void 0 ? referencedSymbol.definition : { + ...referencedSymbol.definition, + textSpan: createTextSpan(mappedDefinitionFile.pos, referencedSymbol.definition.textSpan.length), + // Why would the length be the same in the original? + fileName: mappedDefinitionFile.fileName, + contextSpan: getMappedContextSpanForProject(referencedSymbol.definition, project) + }; + let symbolToAddTo = find(results, (o) => documentSpansEqual(o.definition, definition)); + if (!symbolToAddTo) { + symbolToAddTo = { definition, references: [] }; + results.push(symbolToAddTo); + } + for (const ref of referencedSymbol.references) { + if (!seenRefs.has(ref) && !getMappedLocationForProject(documentSpanLocation(ref), project)) { + seenRefs.add(ref); + symbolToAddTo.references.push(ref); + } + } + } + }); + return results.filter((o) => o.references.length !== 0); + } + function forEachProjectInProjects(projects, path, cb) { + for (const project of isArray(projects) ? projects : projects.projects) { + cb(project, path); + } + if (!isArray(projects) && projects.symLinkedProjects) { + projects.symLinkedProjects.forEach((symlinkedProjects, symlinkedPath) => { + for (const project of symlinkedProjects) { + cb(project, symlinkedPath); + } + }); + } + } + function getPerProjectReferences(projects, defaultProject, initialLocation, isForRename, getResultsForPosition, forPositionInResult) { + const resultsMap = /* @__PURE__ */ new Map(); + const queue = createQueue(); + queue.enqueue({ project: defaultProject, location: initialLocation }); + forEachProjectInProjects(projects, initialLocation.fileName, (project, path) => { + const location = { fileName: path, pos: initialLocation.pos }; + queue.enqueue({ project, location }); + }); + const projectService = defaultProject.projectService; + const cancellationToken = defaultProject.getCancellationToken(); + const defaultDefinition = getDefinitionLocation(defaultProject, initialLocation, isForRename); + const getGeneratedDefinition = memoize( + () => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? defaultDefinition : defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition) + ); + const getSourceDefinition = memoize( + () => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? defaultDefinition : defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition) + ); + const searchedProjectKeys = /* @__PURE__ */ new Set(); + onCancellation: + while (!queue.isEmpty()) { + while (!queue.isEmpty()) { + if (cancellationToken.isCancellationRequested()) + break onCancellation; + const { project, location } = queue.dequeue(); + if (resultsMap.has(project)) + continue; + if (isLocationProjectReferenceRedirect(project, location)) + continue; + updateProjectIfDirty(project); + if (!project.containsFile(toNormalizedPath(location.fileName))) { + continue; + } + const projectResults = searchPosition(project, location); + resultsMap.set(project, projectResults ?? emptyArray2); + searchedProjectKeys.add(getProjectKey(project)); + } + if (defaultDefinition) { + projectService.loadAncestorProjectTree(searchedProjectKeys); + projectService.forEachEnabledProject((project) => { + if (cancellationToken.isCancellationRequested()) + return; + if (resultsMap.has(project)) + return; + const location = mapDefinitionInProject(defaultDefinition, project, getGeneratedDefinition, getSourceDefinition); + if (location) { + queue.enqueue({ project, location }); + } + }); + } + } + if (resultsMap.size === 1) { + return firstIterator(resultsMap.values()); + } + return resultsMap; + function searchPosition(project, location) { + const projectResults = getResultsForPosition(project, location); + if (!projectResults) + return void 0; + for (const result of projectResults) { + forPositionInResult(result, (position) => { + const originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, position); + if (!originalLocation) + return; + const originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); + for (const project2 of originalScriptInfo.containingProjects) { + if (!project2.isOrphan() && !resultsMap.has(project2)) { + queue.enqueue({ project: project2, location: originalLocation }); + } + } + const symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo); + if (symlinkedProjectsMap) { + symlinkedProjectsMap.forEach((symlinkedProjects, symlinkedPath) => { + for (const symlinkedProject of symlinkedProjects) { + if (!symlinkedProject.isOrphan() && !resultsMap.has(symlinkedProject)) { + queue.enqueue({ project: symlinkedProject, location: { fileName: symlinkedPath, pos: originalLocation.pos } }); + } + } + }); + } + }); + } + return projectResults; + } + } + function mapDefinitionInProject(definition, project, getGeneratedDefinition, getSourceDefinition) { + if (project.containsFile(toNormalizedPath(definition.fileName)) && !isLocationProjectReferenceRedirect(project, definition)) { + return definition; + } + const generatedDefinition = getGeneratedDefinition(); + if (generatedDefinition && project.containsFile(toNormalizedPath(generatedDefinition.fileName))) + return generatedDefinition; + const sourceDefinition = getSourceDefinition(); + return sourceDefinition && project.containsFile(toNormalizedPath(sourceDefinition.fileName)) ? sourceDefinition : void 0; + } + function isLocationProjectReferenceRedirect(project, location) { + if (!location) + return false; + const program = project.getLanguageService().getProgram(); + if (!program) + return false; + const sourceFile = program.getSourceFile(location.fileName); + return !!sourceFile && sourceFile.resolvedPath !== sourceFile.path && sourceFile.resolvedPath !== project.toPath(location.fileName); + } + function getProjectKey(project) { + return isConfiguredProject(project) ? project.canonicalConfigFilePath : project.getProjectName(); + } + function documentSpanLocation({ fileName, textSpan }) { + return { fileName, pos: textSpan.start }; + } + function getMappedLocationForProject(location, project) { + return getMappedLocation(location, project.getSourceMapper(), (p) => project.projectService.fileExists(p)); + } + function getMappedDocumentSpanForProject(documentSpan, project) { + return getMappedDocumentSpan(documentSpan, project.getSourceMapper(), (p) => project.projectService.fileExists(p)); + } + function getMappedContextSpanForProject(documentSpan, project) { + return getMappedContextSpan(documentSpan, project.getSourceMapper(), (p) => project.projectService.fileExists(p)); + } + function toProtocolTextSpan(textSpan, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(textSpan.start), + end: scriptInfo.positionToLineOffset(textSpanEnd(textSpan)) + }; + } + function toProtocolTextSpanWithContext(span, contextSpan, scriptInfo) { + const textSpan = toProtocolTextSpan(span, scriptInfo); + const contextTextSpan = contextSpan && toProtocolTextSpan(contextSpan, scriptInfo); + return contextTextSpan ? { ...textSpan, contextStart: contextTextSpan.start, contextEnd: contextTextSpan.end } : textSpan; + } + function convertTextChangeToCodeEdit(change, scriptInfo) { + return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, textSpanEnd(change.span)), newText: change.newText }; + } + function positionToLineOffset(info, position) { + return isConfigFile(info) ? locationFromLineAndCharacter(info.getLineAndCharacterOfPosition(position)) : info.positionToLineOffset(position); + } + function convertLinkedEditInfoToRanges(linkedEdit, scriptInfo) { + const ranges = linkedEdit.ranges.map( + (r) => { + return { + start: scriptInfo.positionToLineOffset(r.start), + end: scriptInfo.positionToLineOffset(r.start + r.length) + }; + } + ); + if (!linkedEdit.wordPattern) + return { ranges }; + return { ranges, wordPattern: linkedEdit.wordPattern }; + } + function locationFromLineAndCharacter(lc) { + return { line: lc.line + 1, offset: lc.character + 1 }; + } + function convertNewFileTextChangeToCodeEdit(textChanges2) { + Debug.assert(textChanges2.textChanges.length === 1); + const change = first(textChanges2.textChanges); + Debug.assert(change.span.start === 0 && change.span.length === 0); + return { fileName: textChanges2.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] }; + } + function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) { + const newText = applyEdits(oldText, renameFilename, edits); + const { line, character } = computeLineAndCharacterOfPosition(computeLineStarts(newText), renameLocation); + return { line: line + 1, offset: character + 1 }; + } + function applyEdits(text, textFilename, edits) { + for (const { fileName, textChanges: textChanges2 } of edits) { + if (fileName !== textFilename) { + continue; + } + for (let i = textChanges2.length - 1; i >= 0; i--) { + const { newText, span: { start, length: length2 } } = textChanges2[i]; + text = text.slice(0, start) + newText + text.slice(start + length2); + } + } + return text; + } + function referenceEntryToReferencesResponseItem(projectService, { fileName, textSpan, contextSpan, isWriteAccess: isWriteAccess2, isDefinition }, { disableLineTextInReferences }) { + const scriptInfo = Debug.checkDefined(projectService.getScriptInfo(fileName)); + const span = toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo); + const lineText = disableLineTextInReferences ? void 0 : getLineText(scriptInfo, span); + return { + file: fileName, + ...span, + lineText, + isWriteAccess: isWriteAccess2, + isDefinition + }; + } + function getLineText(scriptInfo, span) { + const lineSpan = scriptInfo.lineToTextSpan(span.start.line - 1); + return scriptInfo.getSnapshot().getText(lineSpan.start, textSpanEnd(lineSpan)).replace(/\r|\n/g, ""); + } + function isCompletionEntryData(data) { + return data === void 0 || data && typeof data === "object" && typeof data.exportName === "string" && (data.fileName === void 0 || typeof data.fileName === "string") && (data.ambientModuleName === void 0 || typeof data.ambientModuleName === "string" && (data.isPackageJsonImport === void 0 || typeof data.isPackageJsonImport === "boolean")); + } + var nullCancellationToken, CommandNames, MultistepOperation, invalidPartialSemanticModeCommands, invalidSyntacticModeCommands, Session3; + var init_session = __esm({ + "src/server/session.ts"() { + "use strict"; + init_ts7(); + init_ts_server3(); + init_protocol(); + nullCancellationToken = { + isCancellationRequested: () => false, + setRequest: () => void 0, + resetRequest: () => void 0 + }; + CommandNames = CommandTypes; + MultistepOperation = class { + constructor(operationHost) { + this.operationHost = operationHost; + } + startNew(action) { + this.complete(); + this.requestId = this.operationHost.getCurrentRequestId(); + this.executeAction(action); + } + complete() { + if (this.requestId !== void 0) { + this.operationHost.sendRequestCompletedEvent(this.requestId); + this.requestId = void 0; + } + this.setTimerHandle(void 0); + this.setImmediateId(void 0); + } + immediate(actionType, action) { + const requestId = this.requestId; + Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "immediate: incorrect request id"); + this.setImmediateId( + this.operationHost.getServerHost().setImmediate(() => { + this.immediateId = void 0; + this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action)); + }, actionType) + ); + } + delay(actionType, ms, action) { + const requestId = this.requestId; + Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "delay: incorrect request id"); + this.setTimerHandle( + this.operationHost.getServerHost().setTimeout( + () => { + this.timerHandle = void 0; + this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action)); + }, + ms, + actionType + ) + ); + } + executeAction(action) { + var _a, _b, _c, _d, _e, _f; + let stop = false; + try { + if (this.operationHost.isCancellationRequested()) { + stop = true; + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "stepCanceled", { seq: this.requestId, early: true }); + } else { + (_b = tracing) == null ? void 0 : _b.push(tracing.Phase.Session, "stepAction", { seq: this.requestId }); + action(this); + (_c = tracing) == null ? void 0 : _c.pop(); + } + } catch (e) { + (_d = tracing) == null ? void 0 : _d.popAll(); + stop = true; + if (e instanceof OperationCanceledException) { + (_e = tracing) == null ? void 0 : _e.instant(tracing.Phase.Session, "stepCanceled", { seq: this.requestId }); + } else { + (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "stepError", { seq: this.requestId, message: e.message }); + this.operationHost.logError(e, `delayed processing of request ${this.requestId}`); + } + } + if (stop || !this.hasPendingWork()) { + this.complete(); + } + } + setTimerHandle(timerHandle) { + if (this.timerHandle !== void 0) { + this.operationHost.getServerHost().clearTimeout(this.timerHandle); + } + this.timerHandle = timerHandle; + } + setImmediateId(immediateId) { + if (this.immediateId !== void 0) { + this.operationHost.getServerHost().clearImmediate(this.immediateId); + } + this.immediateId = immediateId; + } + hasPendingWork() { + return !!this.timerHandle || !!this.immediateId; + } + }; + invalidPartialSemanticModeCommands = [ + "openExternalProject" /* OpenExternalProject */, + "openExternalProjects" /* OpenExternalProjects */, + "closeExternalProject" /* CloseExternalProject */, + "synchronizeProjectList" /* SynchronizeProjectList */, + "emit-output" /* EmitOutput */, + "compileOnSaveAffectedFileList" /* CompileOnSaveAffectedFileList */, + "compileOnSaveEmitFile" /* CompileOnSaveEmitFile */, + "compilerOptionsDiagnostics-full" /* CompilerOptionsDiagnosticsFull */, + "encodedSemanticClassifications-full" /* EncodedSemanticClassificationsFull */, + "semanticDiagnosticsSync" /* SemanticDiagnosticsSync */, + "suggestionDiagnosticsSync" /* SuggestionDiagnosticsSync */, + "geterrForProject" /* GeterrForProject */, + "reload" /* Reload */, + "reloadProjects" /* ReloadProjects */, + "getCodeFixes" /* GetCodeFixes */, + "getCodeFixes-full" /* GetCodeFixesFull */, + "getCombinedCodeFix" /* GetCombinedCodeFix */, + "getCombinedCodeFix-full" /* GetCombinedCodeFixFull */, + "applyCodeActionCommand" /* ApplyCodeActionCommand */, + "getSupportedCodeFixes" /* GetSupportedCodeFixes */, + "getApplicableRefactors" /* GetApplicableRefactors */, + "getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */, + "getEditsForRefactor" /* GetEditsForRefactor */, + "getEditsForRefactor-full" /* GetEditsForRefactorFull */, + "organizeImports" /* OrganizeImports */, + "organizeImports-full" /* OrganizeImportsFull */, + "getEditsForFileRename" /* GetEditsForFileRename */, + "getEditsForFileRename-full" /* GetEditsForFileRenameFull */, + "prepareCallHierarchy" /* PrepareCallHierarchy */, + "provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */, + "provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */ + ]; + invalidSyntacticModeCommands = [ + ...invalidPartialSemanticModeCommands, + "definition" /* Definition */, + "definition-full" /* DefinitionFull */, + "definitionAndBoundSpan" /* DefinitionAndBoundSpan */, + "definitionAndBoundSpan-full" /* DefinitionAndBoundSpanFull */, + "typeDefinition" /* TypeDefinition */, + "implementation" /* Implementation */, + "implementation-full" /* ImplementationFull */, + "references" /* References */, + "references-full" /* ReferencesFull */, + "rename" /* Rename */, + "renameLocations-full" /* RenameLocationsFull */, + "rename-full" /* RenameInfoFull */, + "quickinfo" /* Quickinfo */, + "quickinfo-full" /* QuickinfoFull */, + "completionInfo" /* CompletionInfo */, + "completions" /* Completions */, + "completions-full" /* CompletionsFull */, + "completionEntryDetails" /* CompletionDetails */, + "completionEntryDetails-full" /* CompletionDetailsFull */, + "signatureHelp" /* SignatureHelp */, + "signatureHelp-full" /* SignatureHelpFull */, + "navto" /* Navto */, + "navto-full" /* NavtoFull */, + "documentHighlights" /* DocumentHighlights */, + "documentHighlights-full" /* DocumentHighlightsFull */ + ]; + Session3 = class _Session { + constructor(opts) { + this.changeSeq = 0; + this.handlers = new Map(Object.entries({ + // TODO(jakebailey): correctly type the handlers + ["status" /* Status */]: () => { + const response = { version }; + return this.requiredResponse(response); + }, + ["openExternalProject" /* OpenExternalProject */]: (request) => { + this.projectService.openExternalProject(request.arguments); + return this.requiredResponse( + /*response*/ + true + ); + }, + ["openExternalProjects" /* OpenExternalProjects */]: (request) => { + this.projectService.openExternalProjects(request.arguments.projects); + return this.requiredResponse( + /*response*/ + true + ); + }, + ["closeExternalProject" /* CloseExternalProject */]: (request) => { + this.projectService.closeExternalProject(request.arguments.projectFileName); + return this.requiredResponse( + /*response*/ + true + ); + }, + ["synchronizeProjectList" /* SynchronizeProjectList */]: (request) => { + const result = this.projectService.synchronizeProjectList(request.arguments.knownProjects, request.arguments.includeProjectReferenceRedirectInfo); + if (!result.some((p) => p.projectErrors && p.projectErrors.length !== 0)) { + return this.requiredResponse(result); + } + const converted = map(result, (p) => { + if (!p.projectErrors || p.projectErrors.length === 0) { + return p; + } + return { + info: p.info, + changes: p.changes, + files: p.files, + projectErrors: this.convertToDiagnosticsWithLinePosition( + p.projectErrors, + /*scriptInfo*/ + void 0 + ) + }; + }); + return this.requiredResponse(converted); + }, + ["updateOpen" /* UpdateOpen */]: (request) => { + this.changeSeq++; + this.projectService.applyChangesInOpenFiles( + request.arguments.openFiles && mapIterator(request.arguments.openFiles, (file) => ({ + fileName: file.file, + content: file.fileContent, + scriptKind: file.scriptKindName, + projectRootPath: file.projectRootPath + })), + request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, (file) => ({ + fileName: file.fileName, + changes: mapDefinedIterator(arrayReverseIterator(file.textChanges), (change) => { + const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(file.fileName)); + const start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset); + const end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset); + return start >= 0 ? { span: { start, length: end - start }, newText: change.newText } : void 0; + }) + })), + request.arguments.closedFiles + ); + return this.requiredResponse( + /*response*/ + true + ); + }, + ["applyChangedToOpenFiles" /* ApplyChangedToOpenFiles */]: (request) => { + this.changeSeq++; + this.projectService.applyChangesInOpenFiles( + request.arguments.openFiles, + request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, (file) => ({ + fileName: file.fileName, + // apply changes in reverse order + changes: arrayReverseIterator(file.changes) + })), + request.arguments.closedFiles + ); + return this.requiredResponse( + /*response*/ + true + ); + }, + ["exit" /* Exit */]: () => { + this.exit(); + return this.notRequired(); + }, + ["definition" /* Definition */]: (request) => { + return this.requiredResponse(this.getDefinition( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["definition-full" /* DefinitionFull */]: (request) => { + return this.requiredResponse(this.getDefinition( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["definitionAndBoundSpan" /* DefinitionAndBoundSpan */]: (request) => { + return this.requiredResponse(this.getDefinitionAndBoundSpan( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["definitionAndBoundSpan-full" /* DefinitionAndBoundSpanFull */]: (request) => { + return this.requiredResponse(this.getDefinitionAndBoundSpan( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["findSourceDefinition" /* FindSourceDefinition */]: (request) => { + return this.requiredResponse(this.findSourceDefinition(request.arguments)); + }, + ["emit-output" /* EmitOutput */]: (request) => { + return this.requiredResponse(this.getEmitOutput(request.arguments)); + }, + ["typeDefinition" /* TypeDefinition */]: (request) => { + return this.requiredResponse(this.getTypeDefinition(request.arguments)); + }, + ["implementation" /* Implementation */]: (request) => { + return this.requiredResponse(this.getImplementation( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["implementation-full" /* ImplementationFull */]: (request) => { + return this.requiredResponse(this.getImplementation( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["references" /* References */]: (request) => { + return this.requiredResponse(this.getReferences( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["references-full" /* ReferencesFull */]: (request) => { + return this.requiredResponse(this.getReferences( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["rename" /* Rename */]: (request) => { + return this.requiredResponse(this.getRenameLocations( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["renameLocations-full" /* RenameLocationsFull */]: (request) => { + return this.requiredResponse(this.getRenameLocations( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["rename-full" /* RenameInfoFull */]: (request) => { + return this.requiredResponse(this.getRenameInfo(request.arguments)); + }, + ["open" /* Open */]: (request) => { + this.openClientFile( + toNormalizedPath(request.arguments.file), + request.arguments.fileContent, + convertScriptKindName(request.arguments.scriptKindName), + // TODO: GH#18217 + request.arguments.projectRootPath ? toNormalizedPath(request.arguments.projectRootPath) : void 0 + ); + return this.notRequired(); + }, + ["quickinfo" /* Quickinfo */]: (request) => { + return this.requiredResponse(this.getQuickInfoWorker( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["quickinfo-full" /* QuickinfoFull */]: (request) => { + return this.requiredResponse(this.getQuickInfoWorker( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["getOutliningSpans" /* GetOutliningSpans */]: (request) => { + return this.requiredResponse(this.getOutliningSpans( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["outliningSpans" /* GetOutliningSpansFull */]: (request) => { + return this.requiredResponse(this.getOutliningSpans( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["todoComments" /* TodoComments */]: (request) => { + return this.requiredResponse(this.getTodoComments(request.arguments)); + }, + ["indentation" /* Indentation */]: (request) => { + return this.requiredResponse(this.getIndentation(request.arguments)); + }, + ["nameOrDottedNameSpan" /* NameOrDottedNameSpan */]: (request) => { + return this.requiredResponse(this.getNameOrDottedNameSpan(request.arguments)); + }, + ["breakpointStatement" /* BreakpointStatement */]: (request) => { + return this.requiredResponse(this.getBreakpointStatement(request.arguments)); + }, + ["braceCompletion" /* BraceCompletion */]: (request) => { + return this.requiredResponse(this.isValidBraceCompletion(request.arguments)); + }, + ["docCommentTemplate" /* DocCommentTemplate */]: (request) => { + return this.requiredResponse(this.getDocCommentTemplate(request.arguments)); + }, + ["getSpanOfEnclosingComment" /* GetSpanOfEnclosingComment */]: (request) => { + return this.requiredResponse(this.getSpanOfEnclosingComment(request.arguments)); + }, + ["fileReferences" /* FileReferences */]: (request) => { + return this.requiredResponse(this.getFileReferences( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["fileReferences-full" /* FileReferencesFull */]: (request) => { + return this.requiredResponse(this.getFileReferences( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["format" /* Format */]: (request) => { + return this.requiredResponse(this.getFormattingEditsForRange(request.arguments)); + }, + ["formatonkey" /* Formatonkey */]: (request) => { + return this.requiredResponse(this.getFormattingEditsAfterKeystroke(request.arguments)); + }, + ["format-full" /* FormatFull */]: (request) => { + return this.requiredResponse(this.getFormattingEditsForDocumentFull(request.arguments)); + }, + ["formatonkey-full" /* FormatonkeyFull */]: (request) => { + return this.requiredResponse(this.getFormattingEditsAfterKeystrokeFull(request.arguments)); + }, + ["formatRange-full" /* FormatRangeFull */]: (request) => { + return this.requiredResponse(this.getFormattingEditsForRangeFull(request.arguments)); + }, + ["completionInfo" /* CompletionInfo */]: (request) => { + return this.requiredResponse(this.getCompletions(request.arguments, "completionInfo" /* CompletionInfo */)); + }, + ["completions" /* Completions */]: (request) => { + return this.requiredResponse(this.getCompletions(request.arguments, "completions" /* Completions */)); + }, + ["completions-full" /* CompletionsFull */]: (request) => { + return this.requiredResponse(this.getCompletions(request.arguments, "completions-full" /* CompletionsFull */)); + }, + ["completionEntryDetails" /* CompletionDetails */]: (request) => { + return this.requiredResponse(this.getCompletionEntryDetails( + request.arguments, + /*fullResult*/ + false + )); + }, + ["completionEntryDetails-full" /* CompletionDetailsFull */]: (request) => { + return this.requiredResponse(this.getCompletionEntryDetails( + request.arguments, + /*fullResult*/ + true + )); + }, + ["compileOnSaveAffectedFileList" /* CompileOnSaveAffectedFileList */]: (request) => { + return this.requiredResponse(this.getCompileOnSaveAffectedFileList(request.arguments)); + }, + ["compileOnSaveEmitFile" /* CompileOnSaveEmitFile */]: (request) => { + return this.requiredResponse(this.emitFile(request.arguments)); + }, + ["signatureHelp" /* SignatureHelp */]: (request) => { + return this.requiredResponse(this.getSignatureHelpItems( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["signatureHelp-full" /* SignatureHelpFull */]: (request) => { + return this.requiredResponse(this.getSignatureHelpItems( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["compilerOptionsDiagnostics-full" /* CompilerOptionsDiagnosticsFull */]: (request) => { + return this.requiredResponse(this.getCompilerOptionsDiagnostics(request.arguments)); + }, + ["encodedSyntacticClassifications-full" /* EncodedSyntacticClassificationsFull */]: (request) => { + return this.requiredResponse(this.getEncodedSyntacticClassifications(request.arguments)); + }, + ["encodedSemanticClassifications-full" /* EncodedSemanticClassificationsFull */]: (request) => { + return this.requiredResponse(this.getEncodedSemanticClassifications(request.arguments)); + }, + ["cleanup" /* Cleanup */]: () => { + this.cleanup(); + return this.requiredResponse( + /*response*/ + true + ); + }, + ["semanticDiagnosticsSync" /* SemanticDiagnosticsSync */]: (request) => { + return this.requiredResponse(this.getSemanticDiagnosticsSync(request.arguments)); + }, + ["syntacticDiagnosticsSync" /* SyntacticDiagnosticsSync */]: (request) => { + return this.requiredResponse(this.getSyntacticDiagnosticsSync(request.arguments)); + }, + ["suggestionDiagnosticsSync" /* SuggestionDiagnosticsSync */]: (request) => { + return this.requiredResponse(this.getSuggestionDiagnosticsSync(request.arguments)); + }, + ["geterr" /* Geterr */]: (request) => { + this.errorCheck.startNew((next) => this.getDiagnostics(next, request.arguments.delay, request.arguments.files)); + return this.notRequired(); + }, + ["geterrForProject" /* GeterrForProject */]: (request) => { + this.errorCheck.startNew((next) => this.getDiagnosticsForProject(next, request.arguments.delay, request.arguments.file)); + return this.notRequired(); + }, + ["change" /* Change */]: (request) => { + this.change(request.arguments); + return this.notRequired(); + }, + ["configure" /* Configure */]: (request) => { + this.projectService.setHostConfiguration(request.arguments); + this.doOutput( + /*info*/ + void 0, + "configure" /* Configure */, + request.seq, + /*success*/ + true + ); + return this.notRequired(); + }, + ["reload" /* Reload */]: (request) => { + this.reload(request.arguments, request.seq); + return this.requiredResponse({ reloadFinished: true }); + }, + ["saveto" /* Saveto */]: (request) => { + const savetoArgs = request.arguments; + this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); + return this.notRequired(); + }, + ["close" /* Close */]: (request) => { + const closeArgs = request.arguments; + this.closeClientFile(closeArgs.file); + return this.notRequired(); + }, + ["navto" /* Navto */]: (request) => { + return this.requiredResponse(this.getNavigateToItems( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["navto-full" /* NavtoFull */]: (request) => { + return this.requiredResponse(this.getNavigateToItems( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["brace" /* Brace */]: (request) => { + return this.requiredResponse(this.getBraceMatching( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["brace-full" /* BraceFull */]: (request) => { + return this.requiredResponse(this.getBraceMatching( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["navbar" /* NavBar */]: (request) => { + return this.requiredResponse(this.getNavigationBarItems( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["navbar-full" /* NavBarFull */]: (request) => { + return this.requiredResponse(this.getNavigationBarItems( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["navtree" /* NavTree */]: (request) => { + return this.requiredResponse(this.getNavigationTree( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["navtree-full" /* NavTreeFull */]: (request) => { + return this.requiredResponse(this.getNavigationTree( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["documentHighlights" /* DocumentHighlights */]: (request) => { + return this.requiredResponse(this.getDocumentHighlights( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["documentHighlights-full" /* DocumentHighlightsFull */]: (request) => { + return this.requiredResponse(this.getDocumentHighlights( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["compilerOptionsForInferredProjects" /* CompilerOptionsForInferredProjects */]: (request) => { + this.setCompilerOptionsForInferredProjects(request.arguments); + return this.requiredResponse( + /*response*/ + true + ); + }, + ["projectInfo" /* ProjectInfo */]: (request) => { + return this.requiredResponse(this.getProjectInfo(request.arguments)); + }, + ["reloadProjects" /* ReloadProjects */]: () => { + this.projectService.reloadProjects(); + return this.notRequired(); + }, + ["jsxClosingTag" /* JsxClosingTag */]: (request) => { + return this.requiredResponse(this.getJsxClosingTag(request.arguments)); + }, + ["linkedEditingRange" /* LinkedEditingRange */]: (request) => { + return this.requiredResponse(this.getLinkedEditingRange(request.arguments)); + }, + ["getCodeFixes" /* GetCodeFixes */]: (request) => { + return this.requiredResponse(this.getCodeFixes( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["getCodeFixes-full" /* GetCodeFixesFull */]: (request) => { + return this.requiredResponse(this.getCodeFixes( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["getCombinedCodeFix" /* GetCombinedCodeFix */]: (request) => { + return this.requiredResponse(this.getCombinedCodeFix( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["getCombinedCodeFix-full" /* GetCombinedCodeFixFull */]: (request) => { + return this.requiredResponse(this.getCombinedCodeFix( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["applyCodeActionCommand" /* ApplyCodeActionCommand */]: (request) => { + return this.requiredResponse(this.applyCodeActionCommand(request.arguments)); + }, + ["getSupportedCodeFixes" /* GetSupportedCodeFixes */]: (request) => { + return this.requiredResponse(this.getSupportedCodeFixes(request.arguments)); + }, + ["getApplicableRefactors" /* GetApplicableRefactors */]: (request) => { + return this.requiredResponse(this.getApplicableRefactors(request.arguments)); + }, + ["getEditsForRefactor" /* GetEditsForRefactor */]: (request) => { + return this.requiredResponse(this.getEditsForRefactor( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */]: (request) => { + return this.requiredResponse(this.getMoveToRefactoringFileSuggestions(request.arguments)); + }, + ["getEditsForRefactor-full" /* GetEditsForRefactorFull */]: (request) => { + return this.requiredResponse(this.getEditsForRefactor( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["organizeImports" /* OrganizeImports */]: (request) => { + return this.requiredResponse(this.organizeImports( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["organizeImports-full" /* OrganizeImportsFull */]: (request) => { + return this.requiredResponse(this.organizeImports( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["getEditsForFileRename" /* GetEditsForFileRename */]: (request) => { + return this.requiredResponse(this.getEditsForFileRename( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["getEditsForFileRename-full" /* GetEditsForFileRenameFull */]: (request) => { + return this.requiredResponse(this.getEditsForFileRename( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["configurePlugin" /* ConfigurePlugin */]: (request) => { + this.configurePlugin(request.arguments); + this.doOutput( + /*info*/ + void 0, + "configurePlugin" /* ConfigurePlugin */, + request.seq, + /*success*/ + true + ); + return this.notRequired(); + }, + ["selectionRange" /* SelectionRange */]: (request) => { + return this.requiredResponse(this.getSmartSelectionRange( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["selectionRange-full" /* SelectionRangeFull */]: (request) => { + return this.requiredResponse(this.getSmartSelectionRange( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["prepareCallHierarchy" /* PrepareCallHierarchy */]: (request) => { + return this.requiredResponse(this.prepareCallHierarchy(request.arguments)); + }, + ["provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */]: (request) => { + return this.requiredResponse(this.provideCallHierarchyIncomingCalls(request.arguments)); + }, + ["provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */]: (request) => { + return this.requiredResponse(this.provideCallHierarchyOutgoingCalls(request.arguments)); + }, + ["toggleLineComment" /* ToggleLineComment */]: (request) => { + return this.requiredResponse(this.toggleLineComment( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["toggleLineComment-full" /* ToggleLineCommentFull */]: (request) => { + return this.requiredResponse(this.toggleLineComment( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["toggleMultilineComment" /* ToggleMultilineComment */]: (request) => { + return this.requiredResponse(this.toggleMultilineComment( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["toggleMultilineComment-full" /* ToggleMultilineCommentFull */]: (request) => { + return this.requiredResponse(this.toggleMultilineComment( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["commentSelection" /* CommentSelection */]: (request) => { + return this.requiredResponse(this.commentSelection( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["commentSelection-full" /* CommentSelectionFull */]: (request) => { + return this.requiredResponse(this.commentSelection( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["uncommentSelection" /* UncommentSelection */]: (request) => { + return this.requiredResponse(this.uncommentSelection( + request.arguments, + /*simplifiedResult*/ + true + )); + }, + ["uncommentSelection-full" /* UncommentSelectionFull */]: (request) => { + return this.requiredResponse(this.uncommentSelection( + request.arguments, + /*simplifiedResult*/ + false + )); + }, + ["provideInlayHints" /* ProvideInlayHints */]: (request) => { + return this.requiredResponse(this.provideInlayHints(request.arguments)); + } + })); + this.host = opts.host; + this.cancellationToken = opts.cancellationToken; + this.typingsInstaller = opts.typingsInstaller || nullTypingsInstaller; + this.byteLength = opts.byteLength; + this.hrtime = opts.hrtime; + this.logger = opts.logger; + this.canUseEvents = opts.canUseEvents; + this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; + this.noGetErrOnBackgroundUpdate = opts.noGetErrOnBackgroundUpdate; + const { throttleWaitMilliseconds } = opts; + this.eventHandler = this.canUseEvents ? opts.eventHandler || ((event) => this.defaultEventHandler(event)) : void 0; + const multistepOperationHost = { + executeWithRequestId: (requestId, action) => this.executeWithRequestId(requestId, action), + getCurrentRequestId: () => this.currentRequestId, + getServerHost: () => this.host, + logError: (err, cmd) => this.logError(err, cmd), + sendRequestCompletedEvent: (requestId) => this.sendRequestCompletedEvent(requestId), + isCancellationRequested: () => this.cancellationToken.isCancellationRequested() + }; + this.errorCheck = new MultistepOperation(multistepOperationHost); + const settings = { + host: this.host, + logger: this.logger, + cancellationToken: this.cancellationToken, + useSingleInferredProject: opts.useSingleInferredProject, + useInferredProjectPerProjectRoot: opts.useInferredProjectPerProjectRoot, + typingsInstaller: this.typingsInstaller, + throttleWaitMilliseconds, + eventHandler: this.eventHandler, + suppressDiagnosticEvents: this.suppressDiagnosticEvents, + globalPlugins: opts.globalPlugins, + pluginProbeLocations: opts.pluginProbeLocations, + allowLocalPluginLoads: opts.allowLocalPluginLoads, + typesMapLocation: opts.typesMapLocation, + serverMode: opts.serverMode, + session: this, + canUseWatchEvents: opts.canUseWatchEvents, + incrementalVerifier: opts.incrementalVerifier + }; + this.projectService = new ProjectService3(settings); + this.projectService.setPerformanceEventHandler(this.performanceEventHandler.bind(this)); + this.gcTimer = new GcTimer( + this.host, + /*delay*/ + 7e3, + this.logger + ); + switch (this.projectService.serverMode) { + case 0 /* Semantic */: + break; + case 1 /* PartialSemantic */: + invalidPartialSemanticModeCommands.forEach( + (commandName) => this.handlers.set(commandName, (request) => { + throw new Error(`Request: ${request.command} not allowed in LanguageServiceMode.PartialSemantic`); + }) + ); + break; + case 2 /* Syntactic */: + invalidSyntacticModeCommands.forEach( + (commandName) => this.handlers.set(commandName, (request) => { + throw new Error(`Request: ${request.command} not allowed in LanguageServiceMode.Syntactic`); + }) + ); + break; + default: + Debug.assertNever(this.projectService.serverMode); + } + } + sendRequestCompletedEvent(requestId) { + this.event({ request_seq: requestId }, "requestCompleted"); + } + addPerformanceData(key, value) { + if (!this.performanceData) { + this.performanceData = {}; + } + this.performanceData[key] = (this.performanceData[key] ?? 0) + value; + } + performanceEventHandler(event) { + switch (event.kind) { + case "UpdateGraph": + this.addPerformanceData("updateGraphDurationMs", event.durationMs); + break; + case "CreatePackageJsonAutoImportProvider": + this.addPerformanceData("createAutoImportProviderProgramDurationMs", event.durationMs); + break; + } + } + defaultEventHandler(event) { + switch (event.eventName) { + case ProjectsUpdatedInBackgroundEvent: + this.projectsUpdatedInBackgroundEvent(event.data.openFiles); + break; + case ProjectLoadingStartEvent: + this.event({ + projectName: event.data.project.getProjectName(), + reason: event.data.reason + }, event.eventName); + break; + case ProjectLoadingFinishEvent: + this.event({ + projectName: event.data.project.getProjectName() + }, event.eventName); + break; + case LargeFileReferencedEvent: + case CreateFileWatcherEvent: + case CreateDirectoryWatcherEvent: + case CloseFileWatcherEvent: + this.event(event.data, event.eventName); + break; + case ConfigFileDiagEvent: + this.event({ + triggerFile: event.data.triggerFile, + configFile: event.data.configFileName, + diagnostics: map(event.data.diagnostics, (diagnostic) => formatDiagnosticToProtocol( + diagnostic, + /*includeFileName*/ + true + )) + }, event.eventName); + break; + case ProjectLanguageServiceStateEvent: { + this.event({ + projectName: event.data.project.getProjectName(), + languageServiceEnabled: event.data.languageServiceEnabled + }, event.eventName); + break; + } + case ProjectInfoTelemetryEvent: { + const eventName = "telemetry"; + this.event({ + telemetryEventName: event.eventName, + payload: event.data + }, eventName); + break; + } + } + } + projectsUpdatedInBackgroundEvent(openFiles) { + this.projectService.logger.info(`got projects updated in background, updating diagnostics for ${openFiles}`); + if (openFiles.length) { + if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) { + this.errorCheck.startNew((next) => this.updateErrorCheck( + next, + openFiles, + 100, + /*requireOpen*/ + true + )); + } + this.event({ + openFiles + }, ProjectsUpdatedInBackgroundEvent); + } + } + logError(err, cmd) { + this.logErrorWorker(err, cmd); + } + logErrorWorker(err, cmd, fileRequest) { + let msg = "Exception on executing command " + cmd; + if (err.message) { + msg += ":\n" + indent2(err.message); + if (err.stack) { + msg += "\n" + indent2(err.stack); + } + } + if (this.logger.hasLevel(3 /* verbose */)) { + if (fileRequest) { + try { + const { file, project } = this.getFileAndProject(fileRequest); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + const text = getSnapshotText(scriptInfo.getSnapshot()); + msg += ` + +File text of ${fileRequest.file}:${indent2(text)} +`; + } + } catch { + } + } + if (err.ProgramFiles) { + msg += ` + +Program files: ${JSON.stringify(err.ProgramFiles)} +`; + msg += ` + +Projects:: +`; + let counter = 0; + const addProjectInfo = (project) => { + msg += ` +Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter} +`; + msg += project.filesToString( + /*writeProjectFileNames*/ + true + ); + msg += "\n-----------------------------------------------\n"; + counter++; + }; + this.projectService.externalProjects.forEach(addProjectInfo); + this.projectService.configuredProjects.forEach(addProjectInfo); + this.projectService.inferredProjects.forEach(addProjectInfo); + } + } + this.logger.msg(msg, "Err" /* Err */); + } + send(msg) { + if (msg.type === "event" && !this.canUseEvents) { + if (this.logger.hasLevel(3 /* verbose */)) { + this.logger.info(`Session does not support events: ignored event: ${JSON.stringify(msg)}`); + } + return; + } + this.writeMessage(msg); + } + writeMessage(msg) { + var _a; + const msgText = formatMessage2(msg, this.logger, this.byteLength, this.host.newLine); + (_a = perfLogger) == null ? void 0 : _a.logEvent(`Response message size: ${msgText.length}`); + this.host.write(msgText); + } + event(body, eventName) { + this.send(toEvent(eventName, body)); + } + /** @internal */ + doOutput(info, cmdName, reqSeq, success, message) { + const res = { + seq: 0, + type: "response", + command: cmdName, + request_seq: reqSeq, + success, + performanceData: this.performanceData + }; + if (success) { + let metadata; + if (isArray(info)) { + res.body = info; + metadata = info.metadata; + delete info.metadata; + } else if (typeof info === "object") { + if (info.metadata) { + const { metadata: infoMetadata, ...body } = info; + res.body = body; + metadata = infoMetadata; + } else { + res.body = info; + } + } else { + res.body = info; + } + if (metadata) + res.metadata = metadata; + } else { + Debug.assert(info === void 0); + } + if (message) { + res.message = message; + } + this.send(res); + } + semanticCheck(file, project) { + var _a, _b; + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "semanticCheck", { file, configFilePath: project.canonicalConfigFilePath }); + const diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file) ? emptyArray2 : project.getLanguageService().getSemanticDiagnostics(file).filter((d) => !!d.file); + this.sendDiagnosticsEvent(file, project, diags, "semanticDiag"); + (_b = tracing) == null ? void 0 : _b.pop(); + } + syntacticCheck(file, project) { + var _a, _b; + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "syntacticCheck", { file, configFilePath: project.canonicalConfigFilePath }); + this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag"); + (_b = tracing) == null ? void 0 : _b.pop(); + } + suggestionCheck(file, project) { + var _a, _b; + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "suggestionCheck", { file, configFilePath: project.canonicalConfigFilePath }); + this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag"); + (_b = tracing) == null ? void 0 : _b.pop(); + } + sendDiagnosticsEvent(file, project, diagnostics, kind) { + try { + this.event({ file, diagnostics: diagnostics.map((diag2) => formatDiag(file, project, diag2)) }, kind); + } catch (err) { + this.logError(err, kind); + } + } + /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */ + updateErrorCheck(next, checkList, ms, requireOpen = true) { + Debug.assert(!this.suppressDiagnosticEvents); + const seq = this.changeSeq; + const followMs = Math.min(ms, 200); + let index = 0; + const goNext = () => { + index++; + if (checkList.length > index) { + next.delay("checkOne", followMs, checkOne); + } + }; + const checkOne = () => { + if (this.changeSeq !== seq) { + return; + } + let item = checkList[index]; + if (isString(item)) { + item = this.toPendingErrorCheck(item); + if (!item) { + goNext(); + return; + } + } + const { fileName, project } = item; + updateProjectIfDirty(project); + if (!project.containsFile(fileName, requireOpen)) { + return; + } + this.syntacticCheck(fileName, project); + if (this.changeSeq !== seq) { + return; + } + if (project.projectService.serverMode !== 0 /* Semantic */) { + goNext(); + return; + } + next.immediate("semanticCheck", () => { + this.semanticCheck(fileName, project); + if (this.changeSeq !== seq) { + return; + } + if (this.getPreferences(fileName).disableSuggestions) { + goNext(); + return; + } + next.immediate("suggestionCheck", () => { + this.suggestionCheck(fileName, project); + goNext(); + }); + }); + }; + if (checkList.length > index && this.changeSeq === seq) { + next.delay("checkOne", ms, checkOne); + } + } + cleanProjects(caption, projects) { + if (!projects) { + return; + } + this.logger.info(`cleaning ${caption}`); + for (const p of projects) { + p.getLanguageService( + /*ensureSynchronized*/ + false + ).cleanupSemanticCache(); + p.cleanupProgram(); + } + } + cleanup() { + this.cleanProjects("inferred projects", this.projectService.inferredProjects); + this.cleanProjects("configured projects", arrayFrom(this.projectService.configuredProjects.values())); + this.cleanProjects("external projects", this.projectService.externalProjects); + if (this.host.gc) { + this.logger.info(`host.gc()`); + this.host.gc(); + } + } + getEncodedSyntacticClassifications(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + return languageService.getEncodedSyntacticClassifications(file, args); + } + getEncodedSemanticClassifications(args) { + const { file, project } = this.getFileAndProject(args); + const format = args.format === "2020" ? "2020" /* TwentyTwenty */ : "original" /* Original */; + return project.getLanguageService().getEncodedSemanticClassifications(file, args, format); + } + getProject(projectFileName) { + return projectFileName === void 0 ? void 0 : this.projectService.findProject(projectFileName); + } + getConfigFileAndProject(args) { + const project = this.getProject(args.projectFileName); + const file = toNormalizedPath(args.file); + return { + configFile: project && project.hasConfigFile(file) ? file : void 0, + project + }; + } + getConfigFileDiagnostics(configFile, project, includeLinePosition) { + const projectErrors = project.getAllProjectErrors(); + const optionsErrors = project.getLanguageService().getCompilerOptionsDiagnostics(); + const diagnosticsForConfigFile = filter( + concatenate(projectErrors, optionsErrors), + (diagnostic) => !!diagnostic.file && diagnostic.file.fileName === configFile + ); + return includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : map( + diagnosticsForConfigFile, + (diagnostic) => formatDiagnosticToProtocol( + diagnostic, + /*includeFileName*/ + false + ) + ); + } + convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics) { + return diagnostics.map((d) => ({ + message: flattenDiagnosticMessageText(d.messageText, this.host.newLine), + start: d.start, + // TODO: GH#18217 + length: d.length, + // TODO: GH#18217 + category: diagnosticCategoryName(d), + code: d.code, + source: d.source, + startLocation: d.file && convertToLocation(getLineAndCharacterOfPosition(d.file, d.start)), + // TODO: GH#18217 + endLocation: d.file && convertToLocation(getLineAndCharacterOfPosition(d.file, d.start + d.length)), + // TODO: GH#18217 + reportsUnnecessary: d.reportsUnnecessary, + reportsDeprecated: d.reportsDeprecated, + relatedInformation: map(d.relatedInformation, formatRelatedInformation) + })); + } + getCompilerOptionsDiagnostics(args) { + const project = this.getProject(args.projectFileName); + return this.convertToDiagnosticsWithLinePosition( + filter( + project.getLanguageService().getCompilerOptionsDiagnostics(), + (diagnostic) => !diagnostic.file + ), + /*scriptInfo*/ + void 0 + ); + } + convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) { + return diagnostics.map( + (d) => ({ + message: flattenDiagnosticMessageText(d.messageText, this.host.newLine), + start: d.start, + length: d.length, + category: diagnosticCategoryName(d), + code: d.code, + source: d.source, + startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), + // TODO: GH#18217 + endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length), + reportsUnnecessary: d.reportsUnnecessary, + reportsDeprecated: d.reportsDeprecated, + relatedInformation: map(d.relatedInformation, formatRelatedInformation) + }) + ); + } + getDiagnosticsWorker(args, isSemantic, selector, includeLinePosition) { + const { project, file } = this.getFileAndProject(args); + if (isSemantic && isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) { + return emptyArray2; + } + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + const diagnostics = selector(project, file); + return includeLinePosition ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) : diagnostics.map((d) => formatDiag(file, project, d)); + } + getDefinition(args, simplifiedResult) { + const { file, project } = this.getFileAndProject(args); + const position = this.getPositionInFile(args, file); + const definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getDefinitionAtPosition(file, position) || emptyArray2, project); + return simplifiedResult ? this.mapDefinitionInfo(definitions, project) : definitions.map(_Session.mapToOriginalLocation); + } + mapDefinitionInfoLocations(definitions, project) { + return definitions.map((info) => { + const newDocumentSpan = getMappedDocumentSpanForProject(info, project); + return !newDocumentSpan ? info : { + ...newDocumentSpan, + containerKind: info.containerKind, + containerName: info.containerName, + kind: info.kind, + name: info.name, + failedAliasResolution: info.failedAliasResolution, + ...info.unverified && { unverified: info.unverified } + }; + }); + } + getDefinitionAndBoundSpan(args, simplifiedResult) { + const { file, project } = this.getFileAndProject(args); + const position = this.getPositionInFile(args, file); + const scriptInfo = Debug.checkDefined(project.getScriptInfo(file)); + const unmappedDefinitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position); + if (!unmappedDefinitionAndBoundSpan || !unmappedDefinitionAndBoundSpan.definitions) { + return { + definitions: emptyArray2, + textSpan: void 0 + // TODO: GH#18217 + }; + } + const definitions = this.mapDefinitionInfoLocations(unmappedDefinitionAndBoundSpan.definitions, project); + const { textSpan } = unmappedDefinitionAndBoundSpan; + if (simplifiedResult) { + return { + definitions: this.mapDefinitionInfo(definitions, project), + textSpan: toProtocolTextSpan(textSpan, scriptInfo) + }; + } + return { + definitions: definitions.map(_Session.mapToOriginalLocation), + textSpan + }; + } + findSourceDefinition(args) { + var _a; + const { file, project } = this.getFileAndProject(args); + const position = this.getPositionInFile(args, file); + const unmappedDefinitions = project.getLanguageService().getDefinitionAtPosition(file, position); + let definitions = this.mapDefinitionInfoLocations(unmappedDefinitions || emptyArray2, project).slice(); + const needsJsResolution = this.projectService.serverMode === 0 /* Semantic */ && (!some(definitions, (d) => toNormalizedPath(d.fileName) !== file && !d.isAmbient) || some(definitions, (d) => !!d.failedAliasResolution)); + if (needsJsResolution) { + const definitionSet = createSet((d) => d.textSpan.start, documentSpansEqual); + definitions == null ? void 0 : definitions.forEach((d) => definitionSet.add(d)); + const noDtsProject = project.getNoDtsResolutionProject(file); + const ls = noDtsProject.getLanguageService(); + const jsDefinitions = (_a = ls.getDefinitionAtPosition( + file, + position, + /*searchOtherFilesOnly*/ + true, + /*stopAtAlias*/ + false + )) == null ? void 0 : _a.filter((d) => toNormalizedPath(d.fileName) !== file); + if (some(jsDefinitions)) { + for (const jsDefinition of jsDefinitions) { + if (jsDefinition.unverified) { + const refined = tryRefineDefinition(jsDefinition, project.getLanguageService().getProgram(), ls.getProgram()); + if (some(refined)) { + for (const def of refined) { + definitionSet.add(def); + } + continue; + } + } + definitionSet.add(jsDefinition); + } + } else { + const ambientCandidates = definitions.filter((d) => toNormalizedPath(d.fileName) !== file && d.isAmbient); + for (const candidate of some(ambientCandidates) ? ambientCandidates : getAmbientCandidatesByClimbingAccessChain()) { + const fileNameToSearch = findImplementationFileFromDtsFileName(candidate.fileName, file, noDtsProject); + if (!fileNameToSearch) + continue; + const info = this.projectService.getOrCreateScriptInfoNotOpenedByClient( + fileNameToSearch, + noDtsProject.currentDirectory, + noDtsProject.directoryStructureHost + ); + if (!info) + continue; + if (!noDtsProject.containsScriptInfo(info)) { + noDtsProject.addRoot(info); + noDtsProject.updateGraph(); + } + const noDtsProgram = ls.getProgram(); + const fileToSearch = Debug.checkDefined(noDtsProgram.getSourceFile(fileNameToSearch)); + for (const match of searchForDeclaration(candidate.name, fileToSearch, noDtsProgram)) { + definitionSet.add(match); + } + } + } + definitions = arrayFrom(definitionSet.values()); + } + definitions = definitions.filter((d) => !d.isAmbient && !d.failedAliasResolution); + return this.mapDefinitionInfo(definitions, project); + function findImplementationFileFromDtsFileName(fileName, resolveFromFile, auxiliaryProject) { + var _a2, _b, _c; + const nodeModulesPathParts = getNodeModulePathParts(fileName); + if (nodeModulesPathParts && fileName.lastIndexOf(nodeModulesPathPart) === nodeModulesPathParts.topLevelNodeModulesIndex) { + const packageDirectory = fileName.substring(0, nodeModulesPathParts.packageRootIndex); + const packageJsonCache = (_a2 = project.getModuleResolutionCache()) == null ? void 0 : _a2.getPackageJsonInfoCache(); + const compilerOptions = project.getCompilationSettings(); + const packageJson = getPackageScopeForPath(getNormalizedAbsolutePath(packageDirectory + "/package.json", project.getCurrentDirectory()), getTemporaryModuleResolutionState(packageJsonCache, project, compilerOptions)); + if (!packageJson) + return void 0; + const entrypoints = getEntrypointsFromPackageJsonInfo( + packageJson, + { moduleResolution: 2 /* Node10 */ }, + project, + project.getModuleResolutionCache() + ); + const packageNamePathPart = fileName.substring( + nodeModulesPathParts.topLevelPackageNameIndex + 1, + nodeModulesPathParts.packageRootIndex + ); + const packageName = getPackageNameFromTypesPackageName(unmangleScopedPackageName(packageNamePathPart)); + const path = project.toPath(fileName); + if (entrypoints && some(entrypoints, (e) => project.toPath(e) === path)) { + return (_b = auxiliaryProject.resolutionCache.resolveSingleModuleNameWithoutWatching(packageName, resolveFromFile).resolvedModule) == null ? void 0 : _b.resolvedFileName; + } else { + const pathToFileInPackage = fileName.substring(nodeModulesPathParts.packageRootIndex + 1); + const specifier = `${packageName}/${removeFileExtension(pathToFileInPackage)}`; + return (_c = auxiliaryProject.resolutionCache.resolveSingleModuleNameWithoutWatching(specifier, resolveFromFile).resolvedModule) == null ? void 0 : _c.resolvedFileName; + } + } + return void 0; + } + function getAmbientCandidatesByClimbingAccessChain() { + const ls = project.getLanguageService(); + const program = ls.getProgram(); + const initialNode = getTouchingPropertyName(program.getSourceFile(file), position); + if ((isStringLiteralLike(initialNode) || isIdentifier(initialNode)) && isAccessExpression(initialNode.parent)) { + return forEachNameInAccessChainWalkingLeft(initialNode, (nameInChain) => { + var _a2; + if (nameInChain === initialNode) + return void 0; + const candidates = (_a2 = ls.getDefinitionAtPosition( + file, + nameInChain.getStart(), + /*searchOtherFilesOnly*/ + true, + /*stopAtAlias*/ + false + )) == null ? void 0 : _a2.filter((d) => toNormalizedPath(d.fileName) !== file && d.isAmbient).map((d) => ({ + fileName: d.fileName, + name: getTextOfIdentifierOrLiteral(initialNode) + })); + if (some(candidates)) { + return candidates; + } + }) || emptyArray2; + } + return emptyArray2; + } + function tryRefineDefinition(definition, program, noDtsProgram) { + var _a2; + const fileToSearch = noDtsProgram.getSourceFile(definition.fileName); + if (!fileToSearch) { + return void 0; + } + const initialNode = getTouchingPropertyName(program.getSourceFile(file), position); + const symbol = program.getTypeChecker().getSymbolAtLocation(initialNode); + const importSpecifier = symbol && getDeclarationOfKind(symbol, 276 /* ImportSpecifier */); + if (!importSpecifier) + return void 0; + const nameToSearch = ((_a2 = importSpecifier.propertyName) == null ? void 0 : _a2.text) || importSpecifier.name.text; + return searchForDeclaration(nameToSearch, fileToSearch, noDtsProgram); + } + function searchForDeclaration(declarationName, fileToSearch, noDtsProgram) { + const matches = ts_FindAllReferences_exports.Core.getTopMostDeclarationNamesInFile(declarationName, fileToSearch); + return mapDefined(matches, (match) => { + const symbol = noDtsProgram.getTypeChecker().getSymbolAtLocation(match); + const decl = getDeclarationFromName(match); + if (symbol && decl) { + return ts_GoToDefinition_exports.createDefinitionInfo( + decl, + noDtsProgram.getTypeChecker(), + symbol, + decl, + /*unverified*/ + true + ); + } + }); + } + } + getEmitOutput(args) { + const { file, project } = this.getFileAndProject(args); + if (!project.shouldEmitFile(project.getScriptInfo(file))) { + return { emitSkipped: true, outputFiles: [], diagnostics: [] }; + } + const result = project.getLanguageService().getEmitOutput(file); + return args.richResponse ? { + ...result, + diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(result.diagnostics) : result.diagnostics.map((d) => formatDiagnosticToProtocol( + d, + /*includeFileName*/ + true + )) + } : result; + } + mapJSDocTagInfo(tags, project, richResponse) { + return tags ? tags.map((tag) => { + var _a; + return { + ...tag, + text: richResponse ? this.mapDisplayParts(tag.text, project) : (_a = tag.text) == null ? void 0 : _a.map((part) => part.text).join("") + }; + }) : []; + } + mapDisplayParts(parts, project) { + if (!parts) { + return []; + } + return parts.map( + (part) => part.kind !== "linkName" ? part : { + ...part, + target: this.toFileSpan(part.target.fileName, part.target.textSpan, project) + } + ); + } + mapSignatureHelpItems(items, project, richResponse) { + return items.map((item) => ({ + ...item, + documentation: this.mapDisplayParts(item.documentation, project), + parameters: item.parameters.map((p) => ({ ...p, documentation: this.mapDisplayParts(p.documentation, project) })), + tags: this.mapJSDocTagInfo(item.tags, project, richResponse) + })); + } + mapDefinitionInfo(definitions, project) { + return definitions.map((def) => ({ ...this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project), ...def.unverified && { unverified: def.unverified } })); + } + /* + * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in + * the same project which corresponds to the file. VS Code has no problem with this, and luckily we have two protocols. + * This retains the existing behavior for the "simplified" (VS Code) protocol but stores the .d.ts location in a + * set of additional fields, and does the reverse for VS (store the .d.ts location where + * it used to be and stores the .ts location in the additional fields). + */ + static mapToOriginalLocation(def) { + if (def.originalFileName) { + Debug.assert(def.originalTextSpan !== void 0, "originalTextSpan should be present if originalFileName is"); + return { + ...def, + fileName: def.originalFileName, + textSpan: def.originalTextSpan, + targetFileName: def.fileName, + targetTextSpan: def.textSpan, + contextSpan: def.originalContextSpan, + targetContextSpan: def.contextSpan + }; + } + return def; + } + toFileSpan(fileName, textSpan, project) { + const ls = project.getLanguageService(); + const start = ls.toLineColumnOffset(fileName, textSpan.start); + const end = ls.toLineColumnOffset(fileName, textSpanEnd(textSpan)); + return { + file: fileName, + start: { line: start.line + 1, offset: start.character + 1 }, + end: { line: end.line + 1, offset: end.character + 1 } + }; + } + toFileSpanWithContext(fileName, textSpan, contextSpan, project) { + const fileSpan = this.toFileSpan(fileName, textSpan, project); + const context = contextSpan && this.toFileSpan(fileName, contextSpan, project); + return context ? { ...fileSpan, contextStart: context.start, contextEnd: context.end } : fileSpan; + } + getTypeDefinition(args) { + const { file, project } = this.getFileAndProject(args); + const position = this.getPositionInFile(args, file); + const definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getTypeDefinitionAtPosition(file, position) || emptyArray2, project); + return this.mapDefinitionInfo(definitions, project); + } + mapImplementationLocations(implementations, project) { + return implementations.map((info) => { + const newDocumentSpan = getMappedDocumentSpanForProject(info, project); + return !newDocumentSpan ? info : { + ...newDocumentSpan, + kind: info.kind, + displayParts: info.displayParts + }; + }); + } + getImplementation(args, simplifiedResult) { + const { file, project } = this.getFileAndProject(args); + const position = this.getPositionInFile(args, file); + const implementations = this.mapImplementationLocations(project.getLanguageService().getImplementationAtPosition(file, position) || emptyArray2, project); + return simplifiedResult ? implementations.map(({ fileName, textSpan, contextSpan }) => this.toFileSpanWithContext(fileName, textSpan, contextSpan, project)) : implementations.map(_Session.mapToOriginalLocation); + } + getSyntacticDiagnosticsSync(args) { + const { configFile } = this.getConfigFileAndProject(args); + if (configFile) { + return emptyArray2; + } + return this.getDiagnosticsWorker( + args, + /*isSemantic*/ + false, + (project, file) => project.getLanguageService().getSyntacticDiagnostics(file), + !!args.includeLinePosition + ); + } + getSemanticDiagnosticsSync(args) { + const { configFile, project } = this.getConfigFileAndProject(args); + if (configFile) { + return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition); + } + return this.getDiagnosticsWorker( + args, + /*isSemantic*/ + true, + (project2, file) => project2.getLanguageService().getSemanticDiagnostics(file).filter((d) => !!d.file), + !!args.includeLinePosition + ); + } + getSuggestionDiagnosticsSync(args) { + const { configFile } = this.getConfigFileAndProject(args); + if (configFile) { + return emptyArray2; + } + return this.getDiagnosticsWorker( + args, + /*isSemantic*/ + true, + (project, file) => project.getLanguageService().getSuggestionDiagnostics(file), + !!args.includeLinePosition + ); + } + getJsxClosingTag(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const position = this.getPositionInFile(args, file); + const tag = languageService.getJsxClosingTagAtPosition(file, position); + return tag === void 0 ? void 0 : { newText: tag.newText, caretOffset: 0 }; + } + getLinkedEditingRange(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const position = this.getPositionInFile(args, file); + const linkedEditInfo = languageService.getLinkedEditingRangeAtPosition(file, position); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + if (scriptInfo === void 0 || linkedEditInfo === void 0) + return void 0; + return convertLinkedEditInfoToRanges(linkedEditInfo, scriptInfo); + } + getDocumentHighlights(args, simplifiedResult) { + const { file, project } = this.getFileAndProject(args); + const position = this.getPositionInFile(args, file); + const documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); + if (!documentHighlights) + return emptyArray2; + if (!simplifiedResult) + return documentHighlights; + return documentHighlights.map(({ fileName, highlightSpans }) => { + const scriptInfo = project.getScriptInfo(fileName); + return { + file: fileName, + highlightSpans: highlightSpans.map(({ textSpan, kind, contextSpan }) => ({ + ...toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo), + kind + })) + }; + }); + } + provideInlayHints(args) { + 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) => { + const { position, displayParts } = hint; + return { + ...hint, + position: scriptInfo.positionToLineOffset(position), + displayParts: displayParts == null ? void 0 : displayParts.map(({ text, span, file: file2 }) => { + if (span) { + Debug.assertIsDefined(file2, "Target file should be defined together with its span."); + const scriptInfo2 = this.projectService.getScriptInfo(file2); + return { + text, + span: { + start: scriptInfo2.positionToLineOffset(span.start), + end: scriptInfo2.positionToLineOffset(span.start + span.length), + file: file2 + } + }; + } else { + return { text }; + } + }) + }; + }); + } + setCompilerOptionsForInferredProjects(args) { + this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath); + } + getProjectInfo(args) { + return this.getProjectInfoWorker( + args.file, + args.projectFileName, + args.needFileNameList, + /*excludeConfigFiles*/ + false + ); + } + getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) { + const { project } = this.getFileAndProjectWorker(uncheckedFileName, projectFileName); + updateProjectIfDirty(project); + const projectInfo = { + configFileName: project.getProjectName(), + languageServiceDisabled: !project.languageServiceEnabled, + fileNames: needFileNameList ? project.getFileNames( + /*excludeFilesFromExternalLibraries*/ + false, + excludeConfigFiles + ) : void 0 + }; + return projectInfo; + } + getRenameInfo(args) { + const { file, project } = this.getFileAndProject(args); + const position = this.getPositionInFile(args, file); + const preferences = this.getPreferences(file); + return project.getLanguageService().getRenameInfo(file, position, preferences); + } + getProjects(args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) { + let projects; + let symLinkedProjects; + if (args.projectFileName) { + const project = this.getProject(args.projectFileName); + if (project) { + projects = [project]; + } + } else { + const scriptInfo = getScriptInfoEnsuringProjectsUptoDate ? this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) : this.projectService.getScriptInfo(args.file); + if (!scriptInfo) { + if (ignoreNoProjectError) + return emptyArray2; + this.projectService.logErrorForScriptInfoNotFound(args.file); + return Errors.ThrowNoProject(); + } else if (!getScriptInfoEnsuringProjectsUptoDate) { + this.projectService.ensureDefaultProjectForFile(scriptInfo); + } + projects = scriptInfo.containingProjects; + symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); + } + projects = filter(projects, (p) => p.languageServiceEnabled && !p.isOrphan()); + if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) { + this.projectService.logErrorForScriptInfoNotFound(args.file ?? args.projectFileName); + return Errors.ThrowNoProject(); + } + return symLinkedProjects ? { projects, symLinkedProjects } : projects; + } + getDefaultProject(args) { + if (args.projectFileName) { + const project = this.getProject(args.projectFileName); + if (project) { + return project; + } + if (!args.file) { + return Errors.ThrowNoProject(); + } + } + const info = this.projectService.getScriptInfo(args.file); + return info.getDefaultProject(); + } + getRenameLocations(args, simplifiedResult) { + const file = toNormalizedPath(args.file); + const position = this.getPositionInFile(args, file); + const projects = this.getProjects(args); + const defaultProject = this.getDefaultProject(args); + const preferences = this.getPreferences(file); + const renameInfo = this.mapRenameInfo( + defaultProject.getLanguageService().getRenameInfo(file, position, preferences), + Debug.checkDefined(this.projectService.getScriptInfo(file)) + ); + if (!renameInfo.canRename) + return simplifiedResult ? { info: renameInfo, locs: [] } : []; + const locations = getRenameLocationsWorker( + projects, + defaultProject, + { fileName: args.file, pos: position }, + !!args.findInStrings, + !!args.findInComments, + preferences + ); + if (!simplifiedResult) + return locations; + return { info: renameInfo, locs: this.toSpanGroups(locations) }; + } + mapRenameInfo(info, scriptInfo) { + if (info.canRename) { + const { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan } = info; + return identity( + { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan: toProtocolTextSpan(triggerSpan, scriptInfo) } + ); + } else { + return info; + } + } + toSpanGroups(locations) { + const map2 = /* @__PURE__ */ new Map(); + for (const { fileName, textSpan, contextSpan, originalContextSpan: _2, originalTextSpan: _, originalFileName: _1, ...prefixSuffixText } of locations) { + let group2 = map2.get(fileName); + if (!group2) + map2.set(fileName, group2 = { file: fileName, locs: [] }); + const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(fileName)); + group2.locs.push({ ...toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo), ...prefixSuffixText }); + } + return arrayFrom(map2.values()); + } + getReferences(args, simplifiedResult) { + const file = toNormalizedPath(args.file); + const projects = this.getProjects(args); + const position = this.getPositionInFile(args, file); + const references = getReferencesWorker( + projects, + this.getDefaultProject(args), + { fileName: args.file, pos: position }, + this.logger + ); + if (!simplifiedResult) + return references; + const preferences = this.getPreferences(file); + const defaultProject = this.getDefaultProject(args); + const scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); + const nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); + const symbolDisplayString = nameInfo ? displayPartsToString(nameInfo.displayParts) : ""; + const nameSpan = nameInfo && nameInfo.textSpan; + const symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; + const symbolName2 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, textSpanEnd(nameSpan)) : ""; + const refs = flatMap(references, (referencedSymbol) => { + return referencedSymbol.references.map((entry) => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences)); + }); + return { refs, symbolName: symbolName2, symbolStartOffset, symbolDisplayString }; + } + getFileReferences(args, simplifiedResult) { + const projects = this.getProjects(args); + const fileName = args.file; + const preferences = this.getPreferences(toNormalizedPath(fileName)); + const references = []; + const seen = createDocumentSpanSet(); + forEachProjectInProjects( + projects, + /*path*/ + void 0, + (project) => { + if (project.getCancellationToken().isCancellationRequested()) + return; + const projectOutputs = project.getLanguageService().getFileReferences(fileName); + if (projectOutputs) { + for (const referenceEntry of projectOutputs) { + if (!seen.has(referenceEntry)) { + references.push(referenceEntry); + seen.add(referenceEntry); + } + } + } + } + ); + if (!simplifiedResult) + return references; + const refs = references.map((entry) => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences)); + return { + refs, + symbolName: `"${args.file}"` + }; + } + /** + * @param fileName is the name of the file to be opened + * @param fileContent is a version of the file content that is known to be more up to date than the one on disk + */ + openClientFile(fileName, fileContent, scriptKind, projectRootPath) { + this.projectService.openClientFileWithNormalizedPath( + fileName, + fileContent, + scriptKind, + /*hasMixedContent*/ + false, + projectRootPath + ); + } + getPosition(args, scriptInfo) { + return args.position !== void 0 ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); + } + getPositionInFile(args, file) { + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + return this.getPosition(args, scriptInfo); + } + getFileAndProject(args) { + return this.getFileAndProjectWorker(args.file, args.projectFileName); + } + getFileAndLanguageServiceForSyntacticOperation(args) { + const { file, project } = this.getFileAndProject(args); + return { + file, + languageService: project.getLanguageService( + /*ensureSynchronized*/ + false + ) + }; + } + getFileAndProjectWorker(uncheckedFileName, projectFileName) { + const file = toNormalizedPath(uncheckedFileName); + const project = this.getProject(projectFileName) || this.projectService.ensureDefaultProjectForFile(file); + return { file, project }; + } + getOutliningSpans(args, simplifiedResult) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const spans = languageService.getOutliningSpans(file); + if (simplifiedResult) { + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + return spans.map((s) => ({ + textSpan: toProtocolTextSpan(s.textSpan, scriptInfo), + hintSpan: toProtocolTextSpan(s.hintSpan, scriptInfo), + bannerText: s.bannerText, + autoCollapse: s.autoCollapse, + kind: s.kind + })); + } else { + return spans; + } + } + getTodoComments(args) { + const { file, project } = this.getFileAndProject(args); + return project.getLanguageService().getTodoComments(file, args.descriptors); + } + getDocCommentTemplate(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const position = this.getPositionInFile(args, file); + return languageService.getDocCommentTemplateAtPosition(file, position, this.getPreferences(file), this.getFormatOptions(file)); + } + getSpanOfEnclosingComment(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const onlyMultiLine = args.onlyMultiLine; + const position = this.getPositionInFile(args, file); + return languageService.getSpanOfEnclosingComment(file, position, onlyMultiLine); + } + getIndentation(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const position = this.getPositionInFile(args, file); + const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file); + const indentation = languageService.getIndentationAtPosition(file, position, options); + return { position, indentation }; + } + getBreakpointStatement(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const position = this.getPositionInFile(args, file); + return languageService.getBreakpointStatementAtPosition(file, position); + } + getNameOrDottedNameSpan(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const position = this.getPositionInFile(args, file); + return languageService.getNameOrDottedNameSpan(file, position, position); + } + isValidBraceCompletion(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const position = this.getPositionInFile(args, file); + return languageService.isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); + } + getQuickInfoWorker(args, simplifiedResult) { + const { file, project } = this.getFileAndProject(args); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + const quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); + if (!quickInfo) { + return void 0; + } + const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; + if (simplifiedResult) { + const displayString = displayPartsToString(quickInfo.displayParts); + return { + kind: quickInfo.kind, + kindModifiers: quickInfo.kindModifiers, + start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), + end: scriptInfo.positionToLineOffset(textSpanEnd(quickInfo.textSpan)), + displayString, + documentation: useDisplayParts ? this.mapDisplayParts(quickInfo.documentation, project) : displayPartsToString(quickInfo.documentation), + tags: this.mapJSDocTagInfo(quickInfo.tags, project, useDisplayParts) + }; + } else { + return useDisplayParts ? quickInfo : { + ...quickInfo, + tags: this.mapJSDocTagInfo( + quickInfo.tags, + project, + /*richResponse*/ + false + ) + }; + } + } + getFormattingEditsForRange(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + const startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); + const endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + const edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.getFormatOptions(file)); + if (!edits) { + return void 0; + } + return edits.map((edit) => this.convertTextChangeToCodeEdit(edit, scriptInfo)); + } + getFormattingEditsForRangeFull(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file); + return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); + } + getFormattingEditsForDocumentFull(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file); + return languageService.getFormattingEditsForDocument(file, options); + } + getFormattingEditsAfterKeystrokeFull(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file); + return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); + } + getFormattingEditsAfterKeystroke(args) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + const position = scriptInfo.lineOffsetToPosition(args.line, args.offset); + const formatOptions = this.getFormatOptions(file); + const edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); + if (args.key === "\n" && (!edits || edits.length === 0 || allEditsBeforePos(edits, position))) { + const { lineText, absolutePosition } = scriptInfo.textStorage.getAbsolutePositionAndLineText(args.line); + if (lineText && lineText.search("\\S") < 0) { + const preferredIndent = languageService.getIndentationAtPosition(file, position, formatOptions); + let hasIndent = 0; + let i, len; + for (i = 0, len = lineText.length; i < len; i++) { + if (lineText.charAt(i) === " ") { + hasIndent++; + } else if (lineText.charAt(i) === " ") { + hasIndent += formatOptions.tabSize; + } else { + break; + } + } + if (preferredIndent !== hasIndent) { + const firstNoWhiteSpacePosition = absolutePosition + i; + edits.push({ + span: createTextSpanFromBounds(absolutePosition, firstNoWhiteSpacePosition), + newText: ts_formatting_exports.getIndentationString(preferredIndent, formatOptions) + }); + } + } + } + if (!edits) { + return void 0; + } + return edits.map((edit) => { + return { + start: scriptInfo.positionToLineOffset(edit.span.start), + end: scriptInfo.positionToLineOffset(textSpanEnd(edit.span)), + newText: edit.newText ? edit.newText : "" + }; + }); + } + getCompletions(args, kind) { + const { file, project } = this.getFileAndProject(args); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + const position = this.getPosition(args, scriptInfo); + const completions = project.getLanguageService().getCompletionsAtPosition( + file, + position, + { + ...convertUserPreferences(this.getPreferences(file)), + triggerCharacter: args.triggerCharacter, + triggerKind: args.triggerKind, + includeExternalModuleExports: args.includeExternalModuleExports, + includeInsertTextCompletions: args.includeInsertTextCompletions + }, + project.projectService.getFormatCodeOptions(file) + ); + if (completions === void 0) + return void 0; + if (kind === "completions-full" /* CompletionsFull */) + return completions; + const prefix = args.prefix || ""; + const entries = mapDefined(completions.entries, (entry) => { + if (completions.isMemberCompletion || startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { + const { + name, + kind: kind2, + kindModifiers, + sortText, + insertText, + filterText, + replacementSpan, + hasAction, + source, + sourceDisplay, + labelDetails, + isSnippet, + isRecommended, + isPackageJsonImport, + isImportStatementCompletion, + data + } = entry; + const convertedSpan = replacementSpan ? toProtocolTextSpan(replacementSpan, scriptInfo) : void 0; + return { + name, + kind: kind2, + kindModifiers, + sortText, + insertText, + filterText, + replacementSpan: convertedSpan, + isSnippet, + hasAction: hasAction || void 0, + source, + sourceDisplay, + labelDetails, + isRecommended, + isPackageJsonImport, + isImportStatementCompletion, + data + }; + } + }); + if (kind === "completions" /* Completions */) { + if (completions.metadata) + entries.metadata = completions.metadata; + return entries; + } + const res = { + ...completions, + optionalReplacementSpan: completions.optionalReplacementSpan && toProtocolTextSpan(completions.optionalReplacementSpan, scriptInfo), + entries + }; + return res; + } + getCompletionEntryDetails(args, fullResult) { + const { file, project } = this.getFileAndProject(args); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + const position = this.getPosition(args, scriptInfo); + const formattingOptions = project.projectService.getFormatCodeOptions(file); + const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; + const result = mapDefined(args.entryNames, (entryName) => { + const { name, source, data } = typeof entryName === "string" ? { name: entryName, source: void 0, data: void 0 } : entryName; + return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, this.getPreferences(file), data ? cast(data, isCompletionEntryData) : void 0); + }); + return fullResult ? useDisplayParts ? result : result.map((details) => ({ ...details, tags: this.mapJSDocTagInfo( + details.tags, + project, + /*richResponse*/ + false + ) })) : result.map((details) => ({ + ...details, + codeActions: map(details.codeActions, (action) => this.mapCodeAction(action)), + documentation: this.mapDisplayParts(details.documentation, project), + tags: this.mapJSDocTagInfo(details.tags, project, useDisplayParts) + })); + } + getCompileOnSaveAffectedFileList(args) { + const projects = this.getProjects( + args, + /*getScriptInfoEnsuringProjectsUptoDate*/ + true, + /*ignoreNoProjectError*/ + true + ); + const info = this.projectService.getScriptInfo(args.file); + if (!info) { + return emptyArray2; + } + return combineProjectOutput( + info, + (path) => this.projectService.getScriptInfoForPath(path), + projects, + (project, info2) => { + if (!project.compileOnSaveEnabled || !project.languageServiceEnabled || project.isOrphan()) { + return void 0; + } + const compilationSettings = project.getCompilationSettings(); + if (!!compilationSettings.noEmit || isDeclarationFileName(info2.fileName) && !dtsChangeCanAffectEmit(compilationSettings)) { + return void 0; + } + return { + projectFileName: project.getProjectName(), + fileNames: project.getCompileOnSaveAffectedFileList(info2), + projectUsesOutFile: !!outFile(compilationSettings) + }; + } + ); + } + emitFile(args) { + const { file, project } = this.getFileAndProject(args); + if (!project) { + Errors.ThrowNoProject(); + } + if (!project.languageServiceEnabled) { + return args.richResponse ? { emitSkipped: true, diagnostics: [] } : false; + } + const scriptInfo = project.getScriptInfo(file); + const { emitSkipped, diagnostics } = project.emitFile(scriptInfo, (path, data, writeByteOrderMark) => this.host.writeFile(path, data, writeByteOrderMark)); + return args.richResponse ? { + emitSkipped, + diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics) : diagnostics.map((d) => formatDiagnosticToProtocol( + d, + /*includeFileName*/ + true + )) + } : !emitSkipped; + } + getSignatureHelpItems(args, simplifiedResult) { + const { file, project } = this.getFileAndProject(args); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + const position = this.getPosition(args, scriptInfo); + const helpItems = project.getLanguageService().getSignatureHelpItems(file, position, args); + const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; + if (helpItems && simplifiedResult) { + const span = helpItems.applicableSpan; + return { + ...helpItems, + applicableSpan: { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(span.start + span.length) + }, + items: this.mapSignatureHelpItems(helpItems.items, project, useDisplayParts) + }; + } else if (useDisplayParts || !helpItems) { + return helpItems; + } else { + return { + ...helpItems, + items: helpItems.items.map((item) => ({ ...item, tags: this.mapJSDocTagInfo( + item.tags, + project, + /*richResponse*/ + false + ) })) + }; + } + } + toPendingErrorCheck(uncheckedFileName) { + const fileName = toNormalizedPath(uncheckedFileName); + const project = this.projectService.tryGetDefaultProjectForFile(fileName); + return project && { fileName, project }; + } + getDiagnostics(next, delay, fileNames) { + if (this.suppressDiagnosticEvents) { + return; + } + if (fileNames.length > 0) { + this.updateErrorCheck(next, fileNames, delay); + } + } + change(args) { + const scriptInfo = this.projectService.getScriptInfo(args.file); + Debug.assert(!!scriptInfo); + scriptInfo.textStorage.switchToScriptVersionCache(); + const start = scriptInfo.lineOffsetToPosition(args.line, args.offset); + const end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + if (start >= 0) { + this.changeSeq++; + this.projectService.applyChangesToFile( + scriptInfo, + singleIterator({ + span: { start, length: end - start }, + newText: args.insertString + // TODO: GH#18217 + }) + ); + } + } + reload(args, reqSeq) { + const file = toNormalizedPath(args.file); + const tempFileName = args.tmpfile === void 0 ? void 0 : toNormalizedPath(args.tmpfile); + const info = this.projectService.getScriptInfoForNormalizedPath(file); + if (info) { + this.changeSeq++; + if (info.reloadFromFile(tempFileName)) { + this.doOutput( + /*info*/ + void 0, + "reload" /* Reload */, + reqSeq, + /*success*/ + true + ); + } + } + } + saveToTmp(fileName, tempFileName) { + const scriptInfo = this.projectService.getScriptInfo(fileName); + if (scriptInfo) { + scriptInfo.saveTo(tempFileName); + } + } + closeClientFile(fileName) { + if (!fileName) { + return; + } + const file = normalizePath(fileName); + this.projectService.closeClientFile(file); + } + mapLocationNavigationBarItems(items, scriptInfo) { + return map(items, (item) => ({ + text: item.text, + kind: item.kind, + kindModifiers: item.kindModifiers, + spans: item.spans.map((span) => toProtocolTextSpan(span, scriptInfo)), + childItems: this.mapLocationNavigationBarItems(item.childItems, scriptInfo), + indent: item.indent + })); + } + getNavigationBarItems(args, simplifiedResult) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const items = languageService.getNavigationBarItems(file); + return !items ? void 0 : simplifiedResult ? this.mapLocationNavigationBarItems(items, this.projectService.getScriptInfoForNormalizedPath(file)) : items; + } + toLocationNavigationTree(tree, scriptInfo) { + return { + text: tree.text, + kind: tree.kind, + kindModifiers: tree.kindModifiers, + spans: tree.spans.map((span) => toProtocolTextSpan(span, scriptInfo)), + nameSpan: tree.nameSpan && toProtocolTextSpan(tree.nameSpan, scriptInfo), + childItems: map(tree.childItems, (item) => this.toLocationNavigationTree(item, scriptInfo)) + }; + } + getNavigationTree(args, simplifiedResult) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const tree = languageService.getNavigationTree(file); + return !tree ? void 0 : simplifiedResult ? this.toLocationNavigationTree(tree, this.projectService.getScriptInfoForNormalizedPath(file)) : tree; + } + getNavigateToItems(args, simplifiedResult) { + const full = this.getFullNavigateToItems(args); + return !simplifiedResult ? flatMap(full, ({ navigateToItems }) => navigateToItems) : flatMap( + full, + ({ project, navigateToItems }) => navigateToItems.map((navItem) => { + const scriptInfo = project.getScriptInfo(navItem.fileName); + const bakedItem = { + name: navItem.name, + kind: navItem.kind, + kindModifiers: navItem.kindModifiers, + isCaseSensitive: navItem.isCaseSensitive, + matchKind: navItem.matchKind, + file: navItem.fileName, + start: scriptInfo.positionToLineOffset(navItem.textSpan.start), + end: scriptInfo.positionToLineOffset(textSpanEnd(navItem.textSpan)) + }; + if (navItem.kindModifiers && navItem.kindModifiers !== "") { + bakedItem.kindModifiers = navItem.kindModifiers; + } + if (navItem.containerName && navItem.containerName.length > 0) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && navItem.containerKind.length > 0) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }) + ); + } + getFullNavigateToItems(args) { + const { currentFileOnly, searchValue, maxResultCount, projectFileName } = args; + if (currentFileOnly) { + Debug.assertIsDefined(args.file); + const { file, project } = this.getFileAndProject(args); + return [{ project, navigateToItems: project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file) }]; + } + const preferences = this.getHostPreferences(); + const outputs = []; + const seenItems = /* @__PURE__ */ new Map(); + if (!args.file && !projectFileName) { + this.projectService.loadAncestorProjectTree(); + this.projectService.forEachEnabledProject((project) => addItemsForProject(project)); + } else { + const projects = this.getProjects(args); + forEachProjectInProjects( + projects, + /*path*/ + void 0, + (project) => addItemsForProject(project) + ); + } + return outputs; + function addItemsForProject(project) { + const projectItems = project.getLanguageService().getNavigateToItems( + searchValue, + maxResultCount, + /*fileName*/ + void 0, + /*excludeDts*/ + project.isNonTsProject(), + /*excludeLibFiles*/ + preferences.excludeLibrarySymbolsInNavTo + ); + const unseenItems = filter(projectItems, (item) => tryAddSeenItem(item) && !getMappedLocationForProject(documentSpanLocation(item), project)); + if (unseenItems.length) { + outputs.push({ project, navigateToItems: unseenItems }); + } + } + function tryAddSeenItem(item) { + const name = item.name; + if (!seenItems.has(name)) { + seenItems.set(name, [item]); + return true; + } + const seen = seenItems.get(name); + for (const seenItem of seen) { + if (navigateToItemIsEqualTo(seenItem, item)) { + return false; + } + } + seen.push(item); + return true; + } + function navigateToItemIsEqualTo(a, b) { + if (a === b) { + return true; + } + if (!a || !b) { + return false; + } + return a.containerKind === b.containerKind && a.containerName === b.containerName && a.fileName === b.fileName && a.isCaseSensitive === b.isCaseSensitive && a.kind === b.kind && a.kindModifiers === b.kindModifiers && a.matchKind === b.matchKind && a.name === b.name && a.textSpan.start === b.textSpan.start && a.textSpan.length === b.textSpan.length; + } + } + getSupportedCodeFixes(args) { + if (!args) + return getSupportedCodeFixes(); + if (args.file) { + const { file, project: project2 } = this.getFileAndProject(args); + return project2.getLanguageService().getSupportedCodeFixes(file); + } + const project = this.getProject(args.projectFileName); + if (!project) + Errors.ThrowNoProject(); + return project.getLanguageService().getSupportedCodeFixes(); + } + isLocation(locationOrSpan) { + return locationOrSpan.line !== void 0; + } + extractPositionOrRange(args, scriptInfo) { + let position; + let textRange; + if (this.isLocation(args)) { + position = getPosition(args); + } else { + textRange = this.getRange(args, scriptInfo); + } + return Debug.checkDefined(position === void 0 ? textRange : position); + function getPosition(loc) { + return loc.position !== void 0 ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); + } + } + getRange(args, scriptInfo) { + const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo); + return { pos: startPosition, end: endPosition }; + } + getApplicableRefactors(args) { + const { file, project } = this.getFileAndProject(args); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file), args.triggerReason, args.kind, args.includeInteractiveActions); + } + getEditsForRefactor(args, simplifiedResult) { + const { file, project } = this.getFileAndProject(args); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + const result = project.getLanguageService().getEditsForRefactor( + file, + this.getFormatOptions(file), + this.extractPositionOrRange(args, scriptInfo), + args.refactor, + args.action, + this.getPreferences(file), + args.interactiveRefactorArguments + ); + if (result === void 0) { + return { + edits: [] + }; + } + if (simplifiedResult) { + const { renameFilename, renameLocation, edits } = result; + let mappedRenameLocation; + if (renameFilename !== void 0 && renameLocation !== void 0) { + const renameScriptInfo = project.getScriptInfoForNormalizedPath(toNormalizedPath(renameFilename)); + mappedRenameLocation = getLocationInNewDocument(getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits); + } + return { + renameLocation: mappedRenameLocation, + renameFilename, + edits: this.mapTextChangesToCodeEdits(edits), + notApplicableReason: result.notApplicableReason + }; + } + return result; + } + getMoveToRefactoringFileSuggestions(args) { + const { file, project } = this.getFileAndProject(args); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + return project.getLanguageService().getMoveToRefactoringFileSuggestions(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file)); + } + organizeImports(args, simplifiedResult) { + Debug.assert(args.scope.type === "file"); + const { file, project } = this.getFileAndProject(args.scope.args); + const changes = project.getLanguageService().organizeImports( + { + fileName: file, + mode: args.mode ?? (args.skipDestructiveCodeActions ? "SortAndCombine" /* SortAndCombine */ : void 0), + type: "file" + }, + this.getFormatOptions(file), + this.getPreferences(file) + ); + if (simplifiedResult) { + return this.mapTextChangesToCodeEdits(changes); + } else { + return changes; + } + } + getEditsForFileRename(args, simplifiedResult) { + const oldPath = toNormalizedPath(args.oldFilePath); + const newPath = toNormalizedPath(args.newFilePath); + const formatOptions = this.getHostFormatOptions(); + const preferences = this.getHostPreferences(); + const seenFiles = /* @__PURE__ */ new Set(); + const textChanges2 = []; + this.projectService.loadAncestorProjectTree(); + this.projectService.forEachEnabledProject((project) => { + const projectTextChanges = project.getLanguageService().getEditsForFileRename(oldPath, newPath, formatOptions, preferences); + const projectFiles = []; + for (const textChange of projectTextChanges) { + if (!seenFiles.has(textChange.fileName)) { + textChanges2.push(textChange); + projectFiles.push(textChange.fileName); + } + } + for (const file of projectFiles) { + seenFiles.add(file); + } + }); + return simplifiedResult ? textChanges2.map((c) => this.mapTextChangeToCodeEdit(c)) : textChanges2; + } + getCodeFixes(args, simplifiedResult) { + const { file, project } = this.getFileAndProject(args); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo); + let codeActions; + try { + codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); + } catch (e) { + const ls = project.getLanguageService(); + const existingDiagCodes = [ + ...ls.getSyntacticDiagnostics(file), + ...ls.getSemanticDiagnostics(file), + ...ls.getSuggestionDiagnostics(file) + ].map( + (d) => decodedTextSpanIntersectsWith(startPosition, endPosition - startPosition, d.start, d.length) && d.code + ); + const badCode = args.errorCodes.find((c) => !existingDiagCodes.includes(c)); + if (badCode !== void 0) { + e.message = `BADCLIENT: Bad error code, ${badCode} not found in range ${startPosition}..${endPosition} (found: ${existingDiagCodes.join(", ")}); could have caused this error: +${e.message}`; + } + throw e; + } + return simplifiedResult ? codeActions.map((codeAction) => this.mapCodeFixAction(codeAction)) : codeActions; + } + getCombinedCodeFix({ scope, fixId: fixId52 }, simplifiedResult) { + Debug.assert(scope.type === "file"); + const { file, project } = this.getFileAndProject(scope.args); + const res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId52, this.getFormatOptions(file), this.getPreferences(file)); + if (simplifiedResult) { + return { changes: this.mapTextChangesToCodeEdits(res.changes), commands: res.commands }; + } else { + return res; + } + } + applyCodeActionCommand(args) { + const commands = args.command; + for (const command of toArray(commands)) { + const { file, project } = this.getFileAndProject(command); + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then( + (_result) => { + }, + (_error) => { + } + ); + } + return {}; + } + getStartAndEndPosition(args, scriptInfo) { + let startPosition, endPosition; + if (args.startPosition !== void 0) { + startPosition = args.startPosition; + } else { + startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + args.startPosition = startPosition; + } + if (args.endPosition !== void 0) { + endPosition = args.endPosition; + } else { + endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + args.endPosition = endPosition; + } + return { startPosition, endPosition }; + } + mapCodeAction({ description: description3, changes, commands }) { + return { description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands }; + } + mapCodeFixAction({ fixName: fixName8, description: description3, changes, commands, fixId: fixId52, fixAllDescription }) { + return { fixName: fixName8, description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands, fixId: fixId52, fixAllDescription }; + } + mapTextChangesToCodeEdits(textChanges2) { + return textChanges2.map((change) => this.mapTextChangeToCodeEdit(change)); + } + mapTextChangeToCodeEdit(textChanges2) { + const scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges2.fileName); + if (!!textChanges2.isNewFile === !!scriptInfo) { + if (!scriptInfo) { + this.projectService.logErrorForScriptInfoNotFound(textChanges2.fileName); + } + Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges2.isNewFile, hasScriptInfo: !!scriptInfo })); + } + return scriptInfo ? { fileName: textChanges2.fileName, textChanges: textChanges2.textChanges.map((textChange) => convertTextChangeToCodeEdit(textChange, scriptInfo)) } : convertNewFileTextChangeToCodeEdit(textChanges2); + } + convertTextChangeToCodeEdit(change, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(change.span.start), + end: scriptInfo.positionToLineOffset(change.span.start + change.span.length), + newText: change.newText ? change.newText : "" + }; + } + getBraceMatching(args, simplifiedResult) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + const position = this.getPosition(args, scriptInfo); + const spans = languageService.getBraceMatchingAtPosition(file, position); + return !spans ? void 0 : simplifiedResult ? spans.map((span) => toProtocolTextSpan(span, scriptInfo)) : spans; + } + getDiagnosticsForProject(next, delay, fileName) { + if (this.suppressDiagnosticEvents) { + return; + } + const { fileNames, languageServiceDisabled } = this.getProjectInfoWorker( + fileName, + /*projectFileName*/ + void 0, + /*needFileNameList*/ + true, + /*excludeConfigFiles*/ + true + ); + if (languageServiceDisabled) { + return; + } + const fileNamesInProject = fileNames.filter((value) => !value.includes("lib.d.ts")); + if (fileNamesInProject.length === 0) { + return; + } + const highPriorityFiles = []; + const mediumPriorityFiles = []; + const lowPriorityFiles = []; + const veryLowPriorityFiles = []; + const normalizedFileName = toNormalizedPath(fileName); + const project = this.projectService.ensureDefaultProjectForFile(normalizedFileName); + for (const fileNameInProject of fileNamesInProject) { + if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) { + highPriorityFiles.push(fileNameInProject); + } else { + const info = this.projectService.getScriptInfo(fileNameInProject); + if (!info.isScriptOpen()) { + if (isDeclarationFileName(fileNameInProject)) { + veryLowPriorityFiles.push(fileNameInProject); + } else { + lowPriorityFiles.push(fileNameInProject); + } + } else { + mediumPriorityFiles.push(fileNameInProject); + } + } + } + const sortedFiles = [...highPriorityFiles, ...mediumPriorityFiles, ...lowPriorityFiles, ...veryLowPriorityFiles]; + const checkList = sortedFiles.map((fileName2) => ({ fileName: fileName2, project })); + this.updateErrorCheck( + next, + checkList, + delay, + /*requireOpen*/ + false + ); + } + configurePlugin(args) { + this.projectService.configurePlugin(args); + } + getSmartSelectionRange(args, simplifiedResult) { + const { locations } = args; + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(file)); + return map(locations, (location) => { + const pos = this.getPosition(location, scriptInfo); + const selectionRange = languageService.getSmartSelectionRange(file, pos); + return simplifiedResult ? this.mapSelectionRange(selectionRange, scriptInfo) : selectionRange; + }); + } + toggleLineComment(args, simplifiedResult) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const scriptInfo = this.projectService.getScriptInfo(file); + const textRange = this.getRange(args, scriptInfo); + const textChanges2 = languageService.toggleLineComment(file, textRange); + if (simplifiedResult) { + const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file); + return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); + } + return textChanges2; + } + toggleMultilineComment(args, simplifiedResult) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + const textRange = this.getRange(args, scriptInfo); + const textChanges2 = languageService.toggleMultilineComment(file, textRange); + if (simplifiedResult) { + const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file); + return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); + } + return textChanges2; + } + commentSelection(args, simplifiedResult) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + const textRange = this.getRange(args, scriptInfo); + const textChanges2 = languageService.commentSelection(file, textRange); + if (simplifiedResult) { + const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file); + return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); + } + return textChanges2; + } + uncommentSelection(args, simplifiedResult) { + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + const textRange = this.getRange(args, scriptInfo); + const textChanges2 = languageService.uncommentSelection(file, textRange); + if (simplifiedResult) { + const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file); + return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); + } + return textChanges2; + } + mapSelectionRange(selectionRange, scriptInfo) { + const result = { + textSpan: toProtocolTextSpan(selectionRange.textSpan, scriptInfo) + }; + if (selectionRange.parent) { + result.parent = this.mapSelectionRange(selectionRange.parent, scriptInfo); + } + return result; + } + getScriptInfoFromProjectService(file) { + const normalizedFile = toNormalizedPath(file); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(normalizedFile); + if (!scriptInfo) { + this.projectService.logErrorForScriptInfoNotFound(normalizedFile); + return Errors.ThrowNoProject(); + } + return scriptInfo; + } + toProtocolCallHierarchyItem(item) { + const scriptInfo = this.getScriptInfoFromProjectService(item.file); + return { + name: item.name, + kind: item.kind, + kindModifiers: item.kindModifiers, + file: item.file, + containerName: item.containerName, + span: toProtocolTextSpan(item.span, scriptInfo), + selectionSpan: toProtocolTextSpan(item.selectionSpan, scriptInfo) + }; + } + toProtocolCallHierarchyIncomingCall(incomingCall) { + const scriptInfo = this.getScriptInfoFromProjectService(incomingCall.from.file); + return { + from: this.toProtocolCallHierarchyItem(incomingCall.from), + fromSpans: incomingCall.fromSpans.map((fromSpan) => toProtocolTextSpan(fromSpan, scriptInfo)) + }; + } + toProtocolCallHierarchyOutgoingCall(outgoingCall, scriptInfo) { + return { + to: this.toProtocolCallHierarchyItem(outgoingCall.to), + fromSpans: outgoingCall.fromSpans.map((fromSpan) => toProtocolTextSpan(fromSpan, scriptInfo)) + }; + } + prepareCallHierarchy(args) { + const { file, project } = this.getFileAndProject(args); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + const position = this.getPosition(args, scriptInfo); + const result = project.getLanguageService().prepareCallHierarchy(file, position); + return result && mapOneOrMany(result, (item) => this.toProtocolCallHierarchyItem(item)); + } + return void 0; + } + provideCallHierarchyIncomingCalls(args) { + const { file, project } = this.getFileAndProject(args); + const scriptInfo = this.getScriptInfoFromProjectService(file); + const incomingCalls = project.getLanguageService().provideCallHierarchyIncomingCalls(file, this.getPosition(args, scriptInfo)); + return incomingCalls.map((call) => this.toProtocolCallHierarchyIncomingCall(call)); + } + provideCallHierarchyOutgoingCalls(args) { + const { file, project } = this.getFileAndProject(args); + const scriptInfo = this.getScriptInfoFromProjectService(file); + const outgoingCalls = project.getLanguageService().provideCallHierarchyOutgoingCalls(file, this.getPosition(args, scriptInfo)); + return outgoingCalls.map((call) => this.toProtocolCallHierarchyOutgoingCall(call, scriptInfo)); + } + getCanonicalFileName(fileName) { + const name = this.host.useCaseSensitiveFileNames ? fileName : toFileNameLowerCase(fileName); + return normalizePath(name); + } + exit() { + } + notRequired() { + return { responseRequired: false }; + } + requiredResponse(response) { + return { response, responseRequired: true }; + } + addProtocolHandler(command, handler) { + if (this.handlers.has(command)) { + throw new Error(`Protocol handler already exists for command "${command}"`); + } + this.handlers.set(command, handler); + } + setCurrentRequest(requestId) { + Debug.assert(this.currentRequestId === void 0); + this.currentRequestId = requestId; + this.cancellationToken.setRequest(requestId); + } + resetCurrentRequest(requestId) { + Debug.assert(this.currentRequestId === requestId); + this.currentRequestId = void 0; + this.cancellationToken.resetRequest(requestId); + } + executeWithRequestId(requestId, f) { + try { + this.setCurrentRequest(requestId); + return f(); + } finally { + this.resetCurrentRequest(requestId); + } + } + executeCommand(request) { + const handler = this.handlers.get(request.command); + if (handler) { + const response = this.executeWithRequestId(request.seq, () => handler(request)); + this.projectService.enableRequestedPlugins(); + return response; + } else { + this.logger.msg(`Unrecognized JSON command:${stringifyIndented(request)}`, "Err" /* Err */); + this.doOutput( + /*info*/ + void 0, + "unknown" /* Unknown */, + request.seq, + /*success*/ + false, + `Unrecognized JSON command: ${request.command}` + ); + return { responseRequired: false }; + } + } + onMessage(message) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; + this.gcTimer.scheduleCollect(); + this.performanceData = void 0; + let start; + if (this.logger.hasLevel(2 /* requestTime */)) { + start = this.hrtime(); + if (this.logger.hasLevel(3 /* verbose */)) { + this.logger.info(`request:${indent2(this.toStringMessage(message))}`); + } + } + let request; + let relevantFile; + try { + request = this.parseMessage(message); + relevantFile = request.arguments && request.arguments.file ? request.arguments : void 0; + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "request", { seq: request.seq, command: request.command }); + (_b = perfLogger) == null ? void 0 : _b.logStartCommand("" + request.command, this.toStringMessage(message).substring(0, 100)); + (_c = tracing) == null ? void 0 : _c.push( + tracing.Phase.Session, + "executeCommand", + { seq: request.seq, command: request.command }, + /*separateBeginAndEnd*/ + true + ); + const { response, responseRequired } = this.executeCommand(request); + (_d = tracing) == null ? void 0 : _d.pop(); + if (this.logger.hasLevel(2 /* requestTime */)) { + const elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); + if (responseRequired) { + this.logger.perftrc(`${request.seq}::${request.command}: elapsed time (in milliseconds) ${elapsedTime}`); + } else { + this.logger.perftrc(`${request.seq}::${request.command}: async elapsed time (in milliseconds) ${elapsedTime}`); + } + } + (_e = perfLogger) == null ? void 0 : _e.logStopCommand("" + request.command, "Success"); + (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "response", { seq: request.seq, command: request.command, success: !!response }); + if (response) { + this.doOutput( + response, + request.command, + request.seq, + /*success*/ + true + ); + } else if (responseRequired) { + this.doOutput( + /*info*/ + void 0, + request.command, + request.seq, + /*success*/ + false, + "No content available." + ); + } + } catch (err) { + (_g = tracing) == null ? void 0 : _g.popAll(); + if (err instanceof OperationCanceledException) { + (_h = perfLogger) == null ? void 0 : _h.logStopCommand("" + (request && request.command), "Canceled: " + err); + (_i = tracing) == null ? void 0 : _i.instant(tracing.Phase.Session, "commandCanceled", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command }); + this.doOutput( + { canceled: true }, + request.command, + request.seq, + /*success*/ + true + ); + return; + } + this.logErrorWorker(err, this.toStringMessage(message), relevantFile); + (_j = perfLogger) == null ? void 0 : _j.logStopCommand("" + (request && request.command), "Error: " + err); + (_k = tracing) == null ? void 0 : _k.instant(tracing.Phase.Session, "commandError", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command, message: err.message }); + this.doOutput( + /*info*/ + void 0, + request ? request.command : "unknown" /* Unknown */, + request ? request.seq : 0, + /*success*/ + false, + "Error processing request. " + err.message + "\n" + err.stack + ); + } + } + parseMessage(message) { + return JSON.parse(message); + } + toStringMessage(message) { + return message; + } + getFormatOptions(file) { + return this.projectService.getFormatCodeOptions(file); + } + getPreferences(file) { + return this.projectService.getPreferences(file); + } + getHostFormatOptions() { + return this.projectService.getHostFormatCodeOptions(); + } + getHostPreferences() { + return this.projectService.getHostPreferences(); + } + }; + } + }); + + // src/server/scriptVersionCache.ts + var lineCollectionCapacity, CharRangeSection, EditWalker, TextChange9, _ScriptVersionCache, ScriptVersionCache, LineIndexSnapshot, LineIndex, LineNode, LineLeaf; + var init_scriptVersionCache = __esm({ + "src/server/scriptVersionCache.ts"() { + "use strict"; + init_ts7(); + init_ts_server3(); + lineCollectionCapacity = 4; + CharRangeSection = /* @__PURE__ */ ((CharRangeSection2) => { + CharRangeSection2[CharRangeSection2["PreStart"] = 0] = "PreStart"; + CharRangeSection2[CharRangeSection2["Start"] = 1] = "Start"; + CharRangeSection2[CharRangeSection2["Entire"] = 2] = "Entire"; + CharRangeSection2[CharRangeSection2["Mid"] = 3] = "Mid"; + CharRangeSection2[CharRangeSection2["End"] = 4] = "End"; + CharRangeSection2[CharRangeSection2["PostEnd"] = 5] = "PostEnd"; + return CharRangeSection2; + })(CharRangeSection || {}); + EditWalker = class { + constructor() { + this.goSubtree = true; + this.lineIndex = new LineIndex(); + this.endBranch = []; + this.state = 2 /* Entire */; + this.initialText = ""; + this.trailingText = ""; + this.lineIndex.root = new LineNode(); + this.startPath = [this.lineIndex.root]; + this.stack = [this.lineIndex.root]; + } + get done() { + return false; + } + insertLines(insertedText, suppressTrailingText) { + if (suppressTrailingText) { + this.trailingText = ""; + } + if (insertedText) { + insertedText = this.initialText + insertedText + this.trailingText; + } else { + insertedText = this.initialText + this.trailingText; + } + const lm = LineIndex.linesFromText(insertedText); + const lines = lm.lines; + if (lines.length > 1 && lines[lines.length - 1] === "") { + lines.pop(); + } + let branchParent; + let lastZeroCount; + for (let k = this.endBranch.length - 1; k >= 0; k--) { + this.endBranch[k].updateCounts(); + if (this.endBranch[k].charCount() === 0) { + lastZeroCount = this.endBranch[k]; + if (k > 0) { + branchParent = this.endBranch[k - 1]; + } else { + branchParent = this.branchNode; + } + } + } + if (lastZeroCount) { + branchParent.remove(lastZeroCount); + } + const leafNode = this.startPath[this.startPath.length - 1]; + if (lines.length > 0) { + leafNode.text = lines[0]; + if (lines.length > 1) { + let insertedNodes = new Array(lines.length - 1); + let startNode2 = leafNode; + for (let i = 1; i < lines.length; i++) { + insertedNodes[i - 1] = new LineLeaf(lines[i]); + } + let pathIndex = this.startPath.length - 2; + while (pathIndex >= 0) { + const insertionNode = this.startPath[pathIndex]; + insertedNodes = insertionNode.insertAt(startNode2, insertedNodes); + pathIndex--; + startNode2 = insertionNode; + } + let insertedNodesLen = insertedNodes.length; + while (insertedNodesLen > 0) { + const newRoot = new LineNode(); + newRoot.add(this.lineIndex.root); + insertedNodes = newRoot.insertAt(this.lineIndex.root, insertedNodes); + insertedNodesLen = insertedNodes.length; + this.lineIndex.root = newRoot; + } + this.lineIndex.root.updateCounts(); + } else { + for (let j = this.startPath.length - 2; j >= 0; j--) { + this.startPath[j].updateCounts(); + } + } + } else { + const insertionNode = this.startPath[this.startPath.length - 2]; + insertionNode.remove(leafNode); + for (let j = this.startPath.length - 2; j >= 0; j--) { + this.startPath[j].updateCounts(); + } + } + return this.lineIndex; + } + post(_relativeStart, _relativeLength, lineCollection) { + if (lineCollection === this.lineCollectionAtBranch) { + this.state = 4 /* End */; + } + this.stack.pop(); + } + pre(_relativeStart, _relativeLength, lineCollection, _parent, nodeType) { + const currentNode = this.stack[this.stack.length - 1]; + if (this.state === 2 /* Entire */ && nodeType === 1 /* Start */) { + this.state = 1 /* Start */; + this.branchNode = currentNode; + this.lineCollectionAtBranch = lineCollection; + } + let child; + function fresh(node) { + if (node.isLeaf()) { + return new LineLeaf(""); + } else + return new LineNode(); + } + switch (nodeType) { + case 0 /* PreStart */: + this.goSubtree = false; + if (this.state !== 4 /* End */) { + currentNode.add(lineCollection); + } + break; + case 1 /* Start */: + if (this.state === 4 /* End */) { + this.goSubtree = false; + } else { + child = fresh(lineCollection); + currentNode.add(child); + this.startPath.push(child); + } + break; + case 2 /* Entire */: + if (this.state !== 4 /* End */) { + child = fresh(lineCollection); + currentNode.add(child); + this.startPath.push(child); + } else { + if (!lineCollection.isLeaf()) { + child = fresh(lineCollection); + currentNode.add(child); + this.endBranch.push(child); + } + } + break; + case 3 /* Mid */: + this.goSubtree = false; + break; + case 4 /* End */: + if (this.state !== 4 /* End */) { + this.goSubtree = false; + } else { + if (!lineCollection.isLeaf()) { + child = fresh(lineCollection); + currentNode.add(child); + this.endBranch.push(child); + } + } + break; + case 5 /* PostEnd */: + this.goSubtree = false; + if (this.state !== 1 /* Start */) { + currentNode.add(lineCollection); + } + break; + } + if (this.goSubtree) { + this.stack.push(child); + } + } + // just gather text from the leaves + leaf(relativeStart, relativeLength, ll) { + if (this.state === 1 /* Start */) { + this.initialText = ll.text.substring(0, relativeStart); + } else if (this.state === 2 /* Entire */) { + this.initialText = ll.text.substring(0, relativeStart); + this.trailingText = ll.text.substring(relativeStart + relativeLength); + } else { + this.trailingText = ll.text.substring(relativeStart + relativeLength); + } + } + }; + TextChange9 = class { + constructor(pos, deleteLen, insertedText) { + this.pos = pos; + this.deleteLen = deleteLen; + this.insertedText = insertedText; + } + getTextChangeRange() { + return createTextChangeRange(createTextSpan(this.pos, this.deleteLen), this.insertedText ? this.insertedText.length : 0); + } + }; + _ScriptVersionCache = class _ScriptVersionCache { + constructor() { + this.changes = []; + this.versions = new Array(_ScriptVersionCache.maxVersions); + this.minVersion = 0; + // no versions earlier than min version will maintain change history + this.currentVersion = 0; + } + versionToIndex(version2) { + if (version2 < this.minVersion || version2 > this.currentVersion) { + return void 0; + } + return version2 % _ScriptVersionCache.maxVersions; + } + currentVersionToIndex() { + return this.currentVersion % _ScriptVersionCache.maxVersions; + } + // REVIEW: can optimize by coalescing simple edits + edit(pos, deleteLen, insertedText) { + this.changes.push(new TextChange9(pos, deleteLen, insertedText)); + if (this.changes.length > _ScriptVersionCache.changeNumberThreshold || deleteLen > _ScriptVersionCache.changeLengthThreshold || insertedText && insertedText.length > _ScriptVersionCache.changeLengthThreshold) { + this.getSnapshot(); + } + } + getSnapshot() { + return this._getSnapshot(); + } + _getSnapshot() { + let snap = this.versions[this.currentVersionToIndex()]; + if (this.changes.length > 0) { + let snapIndex = snap.index; + for (const change of this.changes) { + snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); + } + snap = new LineIndexSnapshot(this.currentVersion + 1, this, snapIndex, this.changes); + this.currentVersion = snap.version; + this.versions[this.currentVersionToIndex()] = snap; + this.changes = []; + if (this.currentVersion - this.minVersion >= _ScriptVersionCache.maxVersions) { + this.minVersion = this.currentVersion - _ScriptVersionCache.maxVersions + 1; + } + } + return snap; + } + getSnapshotVersion() { + return this._getSnapshot().version; + } + getAbsolutePositionAndLineText(oneBasedLine) { + return this._getSnapshot().index.lineNumberToInfo(oneBasedLine); + } + lineOffsetToPosition(line, column) { + return this._getSnapshot().index.absolutePositionOfStartOfLine(line) + (column - 1); + } + positionToLineOffset(position) { + return this._getSnapshot().index.positionToLineOffset(position); + } + lineToTextSpan(line) { + const index = this._getSnapshot().index; + const { lineText, absolutePosition } = index.lineNumberToInfo(line + 1); + const len = lineText !== void 0 ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition; + return createTextSpan(absolutePosition, len); + } + getTextChangesBetweenVersions(oldVersion, newVersion) { + if (oldVersion < newVersion) { + if (oldVersion >= this.minVersion) { + const textChangeRanges = []; + for (let i = oldVersion + 1; i <= newVersion; i++) { + const snap = this.versions[this.versionToIndex(i)]; + for (const textChange of snap.changesSincePreviousVersion) { + textChangeRanges.push(textChange.getTextChangeRange()); + } + } + return collapseTextChangeRangesAcrossMultipleVersions(textChangeRanges); + } else { + return void 0; + } + } else { + return unchangedTextChangeRange; + } + } + getLineCount() { + return this._getSnapshot().index.getLineCount(); + } + static fromString(script) { + const svc = new _ScriptVersionCache(); + const snap = new LineIndexSnapshot(0, svc, new LineIndex()); + svc.versions[svc.currentVersion] = snap; + const lm = LineIndex.linesFromText(script); + snap.index.load(lm.lines); + return svc; + } + }; + _ScriptVersionCache.changeNumberThreshold = 8; + _ScriptVersionCache.changeLengthThreshold = 256; + _ScriptVersionCache.maxVersions = 8; + ScriptVersionCache = _ScriptVersionCache; + LineIndexSnapshot = class _LineIndexSnapshot { + constructor(version2, cache, index, changesSincePreviousVersion = emptyArray2) { + this.version = version2; + this.cache = cache; + this.index = index; + this.changesSincePreviousVersion = changesSincePreviousVersion; + } + getText(rangeStart, rangeEnd) { + return this.index.getText(rangeStart, rangeEnd - rangeStart); + } + getLength() { + return this.index.getLength(); + } + getChangeRange(oldSnapshot) { + if (oldSnapshot instanceof _LineIndexSnapshot && this.cache === oldSnapshot.cache) { + if (this.version <= oldSnapshot.version) { + return unchangedTextChangeRange; + } else { + return this.cache.getTextChangesBetweenVersions(oldSnapshot.version, this.version); + } + } + } + }; + LineIndex = class _LineIndex { + constructor() { + // set this to true to check each edit for accuracy + this.checkEdits = false; + } + absolutePositionOfStartOfLine(oneBasedLine) { + return this.lineNumberToInfo(oneBasedLine).absolutePosition; + } + positionToLineOffset(position) { + const { oneBasedLine, zeroBasedColumn } = this.root.charOffsetToLineInfo(1, position); + return { line: oneBasedLine, offset: zeroBasedColumn + 1 }; + } + positionToColumnAndLineText(position) { + return this.root.charOffsetToLineInfo(1, position); + } + getLineCount() { + return this.root.lineCount(); + } + lineNumberToInfo(oneBasedLine) { + const lineCount = this.getLineCount(); + if (oneBasedLine <= lineCount) { + const { position, leaf } = this.root.lineNumberToInfo(oneBasedLine, 0); + return { absolutePosition: position, lineText: leaf && leaf.text }; + } else { + return { absolutePosition: this.root.charCount(), lineText: void 0 }; + } + } + load(lines) { + if (lines.length > 0) { + const leaves = []; + for (let i = 0; i < lines.length; i++) { + leaves[i] = new LineLeaf(lines[i]); + } + this.root = _LineIndex.buildTreeFromBottom(leaves); + } else { + this.root = new LineNode(); + } + } + walk(rangeStart, rangeLength, walkFns) { + this.root.walk(rangeStart, rangeLength, walkFns); + } + getText(rangeStart, rangeLength) { + let accum = ""; + if (rangeLength > 0 && rangeStart < this.root.charCount()) { + this.walk(rangeStart, rangeLength, { + goSubtree: true, + done: false, + leaf: (relativeStart, relativeLength, ll) => { + accum = accum.concat(ll.text.substring(relativeStart, relativeStart + relativeLength)); + } + }); + } + return accum; + } + getLength() { + return this.root.charCount(); + } + every(f, rangeStart, rangeEnd) { + if (!rangeEnd) { + rangeEnd = this.root.charCount(); + } + const walkFns = { + goSubtree: true, + done: false, + leaf(relativeStart, relativeLength, ll) { + if (!f(ll, relativeStart, relativeLength)) { + this.done = true; + } + } + }; + this.walk(rangeStart, rangeEnd - rangeStart, walkFns); + return !walkFns.done; + } + edit(pos, deleteLength, newText) { + if (this.root.charCount() === 0) { + Debug.assert(deleteLength === 0); + if (newText !== void 0) { + this.load(_LineIndex.linesFromText(newText).lines); + return this; + } + return void 0; + } else { + let checkText; + if (this.checkEdits) { + const source = this.getText(0, this.root.charCount()); + checkText = source.slice(0, pos) + newText + source.slice(pos + deleteLength); + } + const walker = new EditWalker(); + let suppressTrailingText = false; + if (pos >= this.root.charCount()) { + pos = this.root.charCount() - 1; + const endString = this.getText(pos, 1); + if (newText) { + newText = endString + newText; + } else { + newText = endString; + } + deleteLength = 0; + suppressTrailingText = true; + } else if (deleteLength > 0) { + const e = pos + deleteLength; + const { zeroBasedColumn, lineText } = this.positionToColumnAndLineText(e); + if (zeroBasedColumn === 0) { + deleteLength += lineText.length; + newText = newText ? newText + lineText : lineText; + } + } + this.root.walk(pos, deleteLength, walker); + walker.insertLines(newText, suppressTrailingText); + if (this.checkEdits) { + const updatedText = walker.lineIndex.getText(0, walker.lineIndex.getLength()); + Debug.assert(checkText === updatedText, "buffer edit mismatch"); + } + return walker.lineIndex; + } + } + static buildTreeFromBottom(nodes) { + if (nodes.length < lineCollectionCapacity) { + return new LineNode(nodes); + } + const interiorNodes = new Array(Math.ceil(nodes.length / lineCollectionCapacity)); + let nodeIndex = 0; + for (let i = 0; i < interiorNodes.length; i++) { + const end = Math.min(nodeIndex + lineCollectionCapacity, nodes.length); + interiorNodes[i] = new LineNode(nodes.slice(nodeIndex, end)); + nodeIndex = end; + } + return this.buildTreeFromBottom(interiorNodes); + } + static linesFromText(text) { + const lineMap = computeLineStarts(text); + if (lineMap.length === 0) { + return { lines: [], lineMap }; + } + const lines = new Array(lineMap.length); + const lc = lineMap.length - 1; + for (let lmi = 0; lmi < lc; lmi++) { + lines[lmi] = text.substring(lineMap[lmi], lineMap[lmi + 1]); + } + const endText = text.substring(lineMap[lc]); + if (endText.length > 0) { + lines[lc] = endText; + } else { + lines.pop(); + } + return { lines, lineMap }; + } + }; + LineNode = class _LineNode { + constructor(children = []) { + this.children = children; + this.totalChars = 0; + this.totalLines = 0; + if (children.length) + this.updateCounts(); + } + isLeaf() { + return false; + } + updateCounts() { + this.totalChars = 0; + this.totalLines = 0; + for (const child of this.children) { + this.totalChars += child.charCount(); + this.totalLines += child.lineCount(); + } + } + execWalk(rangeStart, rangeLength, walkFns, childIndex, nodeType) { + if (walkFns.pre) { + walkFns.pre(rangeStart, rangeLength, this.children[childIndex], this, nodeType); + } + if (walkFns.goSubtree) { + this.children[childIndex].walk(rangeStart, rangeLength, walkFns); + if (walkFns.post) { + walkFns.post(rangeStart, rangeLength, this.children[childIndex], this, nodeType); + } + } else { + walkFns.goSubtree = true; + } + return walkFns.done; + } + skipChild(relativeStart, relativeLength, childIndex, walkFns, nodeType) { + if (walkFns.pre && !walkFns.done) { + walkFns.pre(relativeStart, relativeLength, this.children[childIndex], this, nodeType); + walkFns.goSubtree = true; + } + } + walk(rangeStart, rangeLength, walkFns) { + let childIndex = 0; + let childCharCount = this.children[childIndex].charCount(); + let adjustedStart = rangeStart; + while (adjustedStart >= childCharCount) { + this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0 /* PreStart */); + adjustedStart -= childCharCount; + childIndex++; + childCharCount = this.children[childIndex].charCount(); + } + if (adjustedStart + rangeLength <= childCharCount) { + if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2 /* Entire */)) { + return; + } + } else { + if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1 /* Start */)) { + return; + } + let adjustedLength = rangeLength - (childCharCount - adjustedStart); + childIndex++; + const child = this.children[childIndex]; + childCharCount = child.charCount(); + while (adjustedLength > childCharCount) { + if (this.execWalk(0, childCharCount, walkFns, childIndex, 3 /* Mid */)) { + return; + } + adjustedLength -= childCharCount; + childIndex++; + childCharCount = this.children[childIndex].charCount(); + } + if (adjustedLength > 0) { + if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4 /* End */)) { + return; + } + } + } + if (walkFns.pre) { + const clen = this.children.length; + if (childIndex < clen - 1) { + for (let ej = childIndex + 1; ej < clen; ej++) { + this.skipChild(0, 0, ej, walkFns, 5 /* PostEnd */); + } + } + } + } + // Input position is relative to the start of this node. + // Output line number is absolute. + charOffsetToLineInfo(lineNumberAccumulator, relativePosition) { + if (this.children.length === 0) { + return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: void 0 }; + } + for (const child of this.children) { + if (child.charCount() > relativePosition) { + if (child.isLeaf()) { + return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: child.text }; + } else { + return child.charOffsetToLineInfo(lineNumberAccumulator, relativePosition); + } + } else { + relativePosition -= child.charCount(); + lineNumberAccumulator += child.lineCount(); + } + } + const lineCount = this.lineCount(); + if (lineCount === 0) { + return { oneBasedLine: 1, zeroBasedColumn: 0, lineText: void 0 }; + } + const leaf = Debug.checkDefined(this.lineNumberToInfo(lineCount, 0).leaf); + return { oneBasedLine: lineCount, zeroBasedColumn: leaf.charCount(), lineText: void 0 }; + } + /** + * Input line number is relative to the start of this node. + * Output line number is relative to the child. + * positionAccumulator will be an absolute position once relativeLineNumber reaches 0. + */ + lineNumberToInfo(relativeOneBasedLine, positionAccumulator) { + for (const child of this.children) { + const childLineCount = child.lineCount(); + if (childLineCount >= relativeOneBasedLine) { + return child.isLeaf() ? { position: positionAccumulator, leaf: child } : child.lineNumberToInfo(relativeOneBasedLine, positionAccumulator); + } else { + relativeOneBasedLine -= childLineCount; + positionAccumulator += child.charCount(); + } + } + return { position: positionAccumulator, leaf: void 0 }; + } + splitAfter(childIndex) { + let splitNode; + const clen = this.children.length; + childIndex++; + const endLength = childIndex; + if (childIndex < clen) { + splitNode = new _LineNode(); + while (childIndex < clen) { + splitNode.add(this.children[childIndex]); + childIndex++; + } + splitNode.updateCounts(); + } + this.children.length = endLength; + return splitNode; + } + remove(child) { + const childIndex = this.findChildIndex(child); + const clen = this.children.length; + if (childIndex < clen - 1) { + for (let i = childIndex; i < clen - 1; i++) { + this.children[i] = this.children[i + 1]; + } + } + this.children.pop(); + } + findChildIndex(child) { + const childIndex = this.children.indexOf(child); + Debug.assert(childIndex !== -1); + return childIndex; + } + insertAt(child, nodes) { + let childIndex = this.findChildIndex(child); + const clen = this.children.length; + const nodeCount = nodes.length; + if (clen < lineCollectionCapacity && childIndex === clen - 1 && nodeCount === 1) { + this.add(nodes[0]); + this.updateCounts(); + return []; + } else { + const shiftNode = this.splitAfter(childIndex); + let nodeIndex = 0; + childIndex++; + while (childIndex < lineCollectionCapacity && nodeIndex < nodeCount) { + this.children[childIndex] = nodes[nodeIndex]; + childIndex++; + nodeIndex++; + } + let splitNodes = []; + let splitNodeCount = 0; + if (nodeIndex < nodeCount) { + splitNodeCount = Math.ceil((nodeCount - nodeIndex) / lineCollectionCapacity); + splitNodes = new Array(splitNodeCount); + let splitNodeIndex = 0; + for (let i = 0; i < splitNodeCount; i++) { + splitNodes[i] = new _LineNode(); + } + let splitNode = splitNodes[0]; + while (nodeIndex < nodeCount) { + splitNode.add(nodes[nodeIndex]); + nodeIndex++; + if (splitNode.children.length === lineCollectionCapacity) { + splitNodeIndex++; + splitNode = splitNodes[splitNodeIndex]; + } + } + for (let i = splitNodes.length - 1; i >= 0; i--) { + if (splitNodes[i].children.length === 0) { + splitNodes.pop(); + } + } + } + if (shiftNode) { + splitNodes.push(shiftNode); + } + this.updateCounts(); + for (let i = 0; i < splitNodeCount; i++) { + splitNodes[i].updateCounts(); + } + return splitNodes; + } + } + // assume there is room for the item; return true if more room + add(collection) { + this.children.push(collection); + Debug.assert(this.children.length <= lineCollectionCapacity); + } + charCount() { + return this.totalChars; + } + lineCount() { + return this.totalLines; + } + }; + LineLeaf = class { + constructor(text) { + this.text = text; + } + isLeaf() { + return true; + } + walk(rangeStart, rangeLength, walkFns) { + walkFns.leaf(rangeStart, rangeLength, this); + } + charCount() { + return this.text.length; + } + lineCount() { + return 1; + } + }; + } + }); + + // src/server/_namespaces/ts.server.ts + var ts_server_exports3 = {}; + __export(ts_server_exports3, { + ActionInvalidate: () => ActionInvalidate, + ActionPackageInstalled: () => ActionPackageInstalled, + ActionSet: () => ActionSet, + ActionWatchTypingLocations: () => ActionWatchTypingLocations, + Arguments: () => Arguments, + AutoImportProviderProject: () => AutoImportProviderProject, + AuxiliaryProject: () => AuxiliaryProject, + CharRangeSection: () => CharRangeSection, + CloseFileWatcherEvent: () => CloseFileWatcherEvent, + CommandNames: () => CommandNames, + ConfigFileDiagEvent: () => ConfigFileDiagEvent, + ConfiguredProject: () => ConfiguredProject2, + CreateDirectoryWatcherEvent: () => CreateDirectoryWatcherEvent, + CreateFileWatcherEvent: () => CreateFileWatcherEvent, + Errors: () => Errors, + EventBeginInstallTypes: () => EventBeginInstallTypes, + EventEndInstallTypes: () => EventEndInstallTypes, + EventInitializationFailed: () => EventInitializationFailed, + EventTypesRegistry: () => EventTypesRegistry, + ExternalProject: () => ExternalProject2, + GcTimer: () => GcTimer, + InferredProject: () => InferredProject2, + LargeFileReferencedEvent: () => LargeFileReferencedEvent, + LineIndex: () => LineIndex, + LineLeaf: () => LineLeaf, + LineNode: () => LineNode, + LogLevel: () => LogLevel2, + Msg: () => Msg, + OpenFileInfoTelemetryEvent: () => OpenFileInfoTelemetryEvent, + Project: () => Project3, + ProjectInfoTelemetryEvent: () => ProjectInfoTelemetryEvent, + ProjectKind: () => ProjectKind, + ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent, + ProjectLoadingFinishEvent: () => ProjectLoadingFinishEvent, + ProjectLoadingStartEvent: () => ProjectLoadingStartEvent, + ProjectReferenceProjectLoadKind: () => ProjectReferenceProjectLoadKind, + ProjectService: () => ProjectService3, + ProjectsUpdatedInBackgroundEvent: () => ProjectsUpdatedInBackgroundEvent, + ScriptInfo: () => ScriptInfo, + ScriptVersionCache: () => ScriptVersionCache, + Session: () => Session3, + TextStorage: () => TextStorage, + ThrottledOperations: () => ThrottledOperations, + TypingsCache: () => TypingsCache, + allFilesAreJsOrDts: () => allFilesAreJsOrDts, + allRootFilesAreJsOrDts: () => allRootFilesAreJsOrDts, + asNormalizedPath: () => asNormalizedPath, + convertCompilerOptions: () => convertCompilerOptions, + convertFormatOptions: () => convertFormatOptions, + convertScriptKindName: () => convertScriptKindName, + convertTypeAcquisition: () => convertTypeAcquisition, + convertUserPreferences: () => convertUserPreferences, + convertWatchOptions: () => convertWatchOptions, + countEachFileTypes: () => countEachFileTypes, + createInstallTypingsRequest: () => createInstallTypingsRequest, + createModuleSpecifierCache: () => createModuleSpecifierCache, + createNormalizedPathMap: () => createNormalizedPathMap, + createPackageJsonCache: () => createPackageJsonCache, + createSortedArray: () => createSortedArray2, + emptyArray: () => emptyArray2, + findArgument: () => findArgument, + forEachResolvedProjectReferenceProject: () => forEachResolvedProjectReferenceProject, + formatDiagnosticToProtocol: () => formatDiagnosticToProtocol, + formatMessage: () => formatMessage2, + getBaseConfigFileName: () => getBaseConfigFileName, + getLocationInNewDocument: () => getLocationInNewDocument, + hasArgument: () => hasArgument, + hasNoTypeScriptSource: () => hasNoTypeScriptSource, + indent: () => indent2, + isBackgroundProject: () => isBackgroundProject, + isConfigFile: () => isConfigFile, + isConfiguredProject: () => isConfiguredProject, + isDynamicFileName: () => isDynamicFileName, + isExternalProject: () => isExternalProject, + isInferredProject: () => isInferredProject, + isInferredProjectName: () => isInferredProjectName, + makeAutoImportProviderProjectName: () => makeAutoImportProviderProjectName, + makeAuxiliaryProjectName: () => makeAuxiliaryProjectName, + makeInferredProjectName: () => makeInferredProjectName, + maxFileSize: () => maxFileSize, + maxProgramSizeForNonTsFiles: () => maxProgramSizeForNonTsFiles, + normalizedPathToPath: () => normalizedPathToPath, + nowString: () => nowString, + nullCancellationToken: () => nullCancellationToken, + nullTypingsInstaller: () => nullTypingsInstaller, + projectContainsInfoDirectly: () => projectContainsInfoDirectly, + protocol: () => ts_server_protocol_exports, + removeSorted: () => removeSorted, + stringifyIndented: () => stringifyIndented, + toEvent: () => toEvent, + toNormalizedPath: () => toNormalizedPath, + tryConvertScriptKindName: () => tryConvertScriptKindName, + typingsInstaller: () => ts_server_typingsInstaller_exports, + updateProjectIfDirty: () => updateProjectIfDirty + }); + var init_ts_server3 = __esm({ + "src/server/_namespaces/ts.server.ts"() { + "use strict"; + init_ts_server(); + init_ts_server2(); + init_types4(); + init_utilitiesPublic3(); + init_utilities5(); + init_ts_server_protocol(); + init_scriptInfo(); + init_typingsCache(); + init_project(); + init_editorServices(); + init_moduleSpecifierCache(); + init_packageJsonCache(); + init_session(); + init_scriptVersionCache(); + } + }); + + // src/server/_namespaces/ts.ts var ts_exports2 = {}; __export(ts_exports2, { ANONYMOUS: () => ANONYMOUS, @@ -172075,10 +184002,8 @@ ${options.prefix}` : "\n" : options.prefix CompletionInfoFlags: () => CompletionInfoFlags, CompletionTriggerKind: () => CompletionTriggerKind, Completions: () => ts_Completions_exports, - ConfigFileProgramReloadLevel: () => ConfigFileProgramReloadLevel, ContainerFlags: () => ContainerFlags, ContextFlags: () => ContextFlags, - CoreServicesShimHostAdapter: () => CoreServicesShimHostAdapter, Debug: () => Debug, DiagnosticCategory: () => DiagnosticCategory, Diagnostics: () => Diagnostics, @@ -172120,13 +184045,13 @@ ${options.prefix}` : "\n" : options.prefix InternalEmitFlags: () => InternalEmitFlags, InternalSymbolName: () => InternalSymbolName, InvalidatedProjectKind: () => InvalidatedProjectKind, + JSDocParsingMode: () => JSDocParsingMode, JsDoc: () => ts_JsDoc_exports, JsTyping: () => ts_JsTyping_exports, JsxEmit: () => JsxEmit, JsxFlags: () => JsxFlags, JsxReferenceKind: () => JsxReferenceKind, LanguageServiceMode: () => LanguageServiceMode, - LanguageServiceShimHostAdapter: () => LanguageServiceShimHostAdapter, LanguageVariant: () => LanguageVariant, LexicalEnvironmentFlags: () => LexicalEnvironmentFlags, ListFormat: () => ListFormat, @@ -172163,6 +184088,7 @@ ${options.prefix}` : "\n" : options.prefix PragmaKindFlags: () => PragmaKindFlags, PrivateIdentifierKind: () => PrivateIdentifierKind, ProcessLevel: () => ProcessLevel, + ProgramUpdateLevel: () => ProgramUpdateLevel, QuotePreference: () => QuotePreference, RelationComparisonResult: () => RelationComparisonResult, Rename: () => ts_Rename_exports, @@ -172200,7 +184126,6 @@ ${options.prefix}` : "\n" : options.prefix TypeMapKind: () => TypeMapKind, TypePredicateKind: () => TypePredicateKind, TypeReferenceSerializationKind: () => TypeReferenceSerializationKind, - TypeScriptServicesFactory: () => TypeScriptServicesFactory, UnionReduction: () => UnionReduction, UpToDateStatusType: () => UpToDateStatusType, VarianceFlags: () => VarianceFlags, @@ -172447,6 +184372,7 @@ ${options.prefix}` : "\n" : options.prefix createModuleNotFoundChain: () => createModuleNotFoundChain, createModuleResolutionCache: () => createModuleResolutionCache, createModuleResolutionLoader: () => createModuleResolutionLoader, + createModuleResolutionLoaderUsingGlobalCache: () => createModuleResolutionLoaderUsingGlobalCache, createModuleSpecifierResolutionHost: () => createModuleSpecifierResolutionHost, createMultiMap: () => createMultiMap, createNodeConverters: () => createNodeConverters, @@ -172876,6 +184802,7 @@ ${options.prefix}` : "\n" : options.prefix getLeadingCommentRangesOfNode: () => getLeadingCommentRangesOfNode, getLeftmostAccessExpression: () => getLeftmostAccessExpression, getLeftmostExpression: () => getLeftmostExpression, + getLibraryNameFromLibFileName: () => getLibraryNameFromLibFileName, getLineAndCharacterOfPosition: () => getLineAndCharacterOfPosition, getLineInfo: () => getLineInfo, getLineOfLocalPosition: () => getLineOfLocalPosition, @@ -173007,13 +184934,11 @@ ${options.prefix}` : "\n" : options.prefix getRenameLocation: () => getRenameLocation, getReplacementSpanForContextToken: () => getReplacementSpanForContextToken, getResolutionDiagnostic: () => getResolutionDiagnostic, - getResolutionModeOverrideForClause: () => getResolutionModeOverrideForClause, + getResolutionModeOverride: () => getResolutionModeOverride, getResolveJsonModule: () => getResolveJsonModule, getResolvePackageJsonExports: () => getResolvePackageJsonExports, getResolvePackageJsonImports: () => getResolvePackageJsonImports, getResolvedExternalModuleName: () => getResolvedExternalModuleName, - getResolvedModule: () => getResolvedModule, - getResolvedTypeReferenceDirective: () => getResolvedTypeReferenceDirective, getRestIndicatorOfBindingOrAssignmentElement: () => getRestIndicatorOfBindingOrAssignmentElement, getRestParameterElementType: () => getRestParameterElementType, getRightMostAssignedExpression: () => getRightMostAssignedExpression, @@ -173141,6 +185066,7 @@ ${options.prefix}` : "\n" : options.prefix hasPropertyAccessExpressionWithName: () => hasPropertyAccessExpressionWithName, hasQuestionToken: () => hasQuestionToken, hasRecordedExternalHelpers: () => hasRecordedExternalHelpers, + hasResolutionModeOverride: () => hasResolutionModeOverride, hasRestParameter: () => hasRestParameter, hasScopeMarker: () => hasScopeMarker, hasStaticModifier: () => hasStaticModifier, @@ -173214,7 +185140,6 @@ ${options.prefix}` : "\n" : options.prefix isAssertClause: () => isAssertClause, isAssertEntry: () => isAssertEntry, isAssertionExpression: () => isAssertionExpression, - isAssertionKey: () => isAssertionKey, isAssertsKeyword: () => isAssertsKeyword, isAssignmentDeclaration: () => isAssignmentDeclaration, isAssignmentExpression: () => isAssignmentExpression, @@ -173255,6 +185180,7 @@ ${options.prefix}` : "\n" : options.prefix isCallExpression: () => isCallExpression, isCallExpressionTarget: () => isCallExpressionTarget, isCallLikeExpression: () => isCallLikeExpression, + isCallLikeOrFunctionLikeExpression: () => isCallLikeOrFunctionLikeExpression, isCallOrNewExpression: () => isCallOrNewExpression, isCallOrNewExpressionTarget: () => isCallOrNewExpressionTarget, isCallSignatureDeclaration: () => isCallSignatureDeclaration, @@ -173272,6 +185198,7 @@ ${options.prefix}` : "\n" : options.prefix isClassDeclaration: () => isClassDeclaration, isClassElement: () => isClassElement, isClassExpression: () => isClassExpression, + isClassInstanceProperty: () => isClassInstanceProperty, isClassLike: () => isClassLike, isClassMemberModifier: () => isClassMemberModifier, isClassNamedEvaluationHelperBlock: () => isClassNamedEvaluationHelperBlock, @@ -173350,6 +185277,7 @@ ${options.prefix}` : "\n" : options.prefix isExclamationToken: () => isExclamationToken, isExcludedFile: () => isExcludedFile, isExclusivelyTypeOnlyImportOrExport: () => isExclusivelyTypeOnlyImportOrExport, + isExpandoPropertyDeclaration: () => isExpandoPropertyDeclaration, isExportAssignment: () => isExportAssignment, isExportDeclaration: () => isExportDeclaration, isExportModifier: () => isExportModifier, @@ -173421,6 +185349,9 @@ ${options.prefix}` : "\n" : options.prefix isIfStatement: () => isIfStatement, isIgnoredFileFromWildCardWatching: () => isIgnoredFileFromWildCardWatching, isImplicitGlob: () => isImplicitGlob, + isImportAttribute: () => isImportAttribute, + isImportAttributeName: () => isImportAttributeName, + isImportAttributes: () => isImportAttributes, isImportCall: () => isImportCall, isImportClause: () => isImportClause, isImportDeclaration: () => isImportDeclaration, @@ -173434,6 +185365,7 @@ ${options.prefix}` : "\n" : options.prefix isImportTypeNode: () => isImportTypeNode, isImportableFile: () => isImportableFile, isInComment: () => isInComment, + isInCompoundLikeAssignment: () => isInCompoundLikeAssignment, isInExpressionContext: () => isInExpressionContext, isInJSDoc: () => isInJSDoc, isInJSFile: () => isInJSFile, @@ -173457,6 +185389,7 @@ ${options.prefix}` : "\n" : options.prefix isInsideJsxElementOrAttribute: () => isInsideJsxElementOrAttribute, isInsideNodeModules: () => isInsideNodeModules, isInsideTemplateLiteral: () => isInsideTemplateLiteral, + isInstanceOfExpression: () => isInstanceOfExpression, isInstantiatedModule: () => isInstantiatedModule, isInterfaceDeclaration: () => isInterfaceDeclaration, isInternalDeclaration: () => isInternalDeclaration, @@ -173611,7 +185544,6 @@ ${options.prefix}` : "\n" : options.prefix isNamespaceReexportDeclaration: () => isNamespaceReexportDeclaration, isNewExpression: () => isNewExpression, isNewExpressionTarget: () => isNewExpressionTarget, - isNightly: () => isNightly, isNoSubstitutionTemplateLiteral: () => isNoSubstitutionTemplateLiteral, isNode: () => isNode, isNodeArray: () => isNodeArray, @@ -173715,6 +185647,7 @@ ${options.prefix}` : "\n" : options.prefix isReturnStatement: () => isReturnStatement, isReturnStatementWithFixablePromiseHandler: () => isReturnStatementWithFixablePromiseHandler, isRightSideOfAccessExpression: () => isRightSideOfAccessExpression, + isRightSideOfInstanceofExpression: () => isRightSideOfInstanceofExpression, isRightSideOfPropertyAccess: () => isRightSideOfPropertyAccess, isRightSideOfQualifiedName: () => isRightSideOfQualifiedName, isRightSideOfQualifiedNameOrPropertyAccess: () => isRightSideOfQualifiedNameOrPropertyAccess, @@ -173727,6 +185660,7 @@ ${options.prefix}` : "\n" : options.prefix isSetAccessor: () => isSetAccessor, isSetAccessorDeclaration: () => isSetAccessorDeclaration, isShebangTrivia: () => isShebangTrivia, + isShiftOperatorOrHigher: () => isShiftOperatorOrHigher, isShorthandAmbientModuleSymbol: () => isShorthandAmbientModuleSymbol, isShorthandPropertyAssignment: () => isShorthandPropertyAssignment, isSignedNumericLiteral: () => isSignedNumericLiteral, @@ -173965,8 +185899,6 @@ ${options.prefix}` : "\n" : options.prefix outFile: () => outFile, packageIdToPackageName: () => packageIdToPackageName, packageIdToString: () => packageIdToString, - padLeft: () => padLeft, - padRight: () => padRight, paramHelper: () => paramHelper, parameterIsThisKeyword: () => parameterIsThisKeyword, parameterNamePart: () => parameterNamePart, @@ -174040,7 +185972,6 @@ ${options.prefix}` : "\n" : options.prefix readJson: () => readJson, readJsonConfigFile: () => readJsonConfigFile, readJsonOrUndefined: () => readJsonOrUndefined, - realizeDiagnostics: () => realizeDiagnostics, reduceEachLeadingCommentRange: () => reduceEachLeadingCommentRange, reduceEachTrailingCommentRange: () => reduceEachTrailingCommentRange, reduceLeft: () => reduceLeft, @@ -174089,7 +186020,7 @@ ${options.prefix}` : "\n" : options.prefix screenStartingMessageCodes: () => screenStartingMessageCodes, semanticDiagnosticsOptionDeclarations: () => semanticDiagnosticsOptionDeclarations, serializeCompilerOptions: () => serializeCompilerOptions, - server: () => ts_server_exports, + server: () => ts_server_exports3, servicesVersion: () => servicesVersion, setCommentRange: () => setCommentRange, setConfigFileInOptions: () => setConfigFileInOptions, @@ -174110,8 +186041,6 @@ ${options.prefix}` : "\n" : options.prefix setParent: () => setParent, setParentRecursive: () => setParentRecursive, setPrivateIdentifier: () => setPrivateIdentifier, - setResolvedModule: () => setResolvedModule, - setResolvedTypeReferenceDirective: () => setResolvedTypeReferenceDirective, setSnippetElement: () => setSnippetElement, setSourceMapRange: () => setSourceMapRange, setStackTraceLimit: () => setStackTraceLimit, @@ -174173,7 +186102,6 @@ ${options.prefix}` : "\n" : options.prefix startsWithDirectory: () => startsWithDirectory, startsWithUnderscore: () => startsWithUnderscore, startsWithUseStrict: () => startsWithUseStrict, - stringContains: () => stringContains, stringContainsAt: () => stringContainsAt, stringToToken: () => stringToToken, stripQuotes: () => stripQuotes, @@ -174260,9 +186188,6 @@ ${options.prefix}` : "\n" : options.prefix transpile: () => transpile, transpileModule: () => transpileModule, transpileOptionValueCompilerOptions: () => transpileOptionValueCompilerOptions, - trimString: () => trimString, - trimStringEnd: () => trimStringEnd, - trimStringStart: () => trimStringStart, tryAddToSet: () => tryAddToSet, tryAndIgnoreErrors: () => tryAndIgnoreErrors, tryCast: () => tryCast, @@ -174342,24 +186267,2433 @@ ${options.prefix}` : "\n" : options.prefix writeCommentRange: () => writeCommentRange, writeFile: () => writeFile, writeFileEnsuringDirectories: () => writeFileEnsuringDirectories, - zipToModeAwareCache: () => zipToModeAwareCache, zipWith: () => zipWith }); - var init_ts6 = __esm({ - "src/typescript/_namespaces/ts.ts"() { + var init_ts7 = __esm({ + "src/server/_namespaces/ts.ts"() { "use strict"; init_ts2(); init_ts3(); init_ts4(); init_ts5(); + init_ts_server3(); + } + }); + + // src/typescript/_namespaces/ts.server.ts + var ts_server_exports4 = {}; + __export(ts_server_exports4, { + ActionInvalidate: () => ActionInvalidate, + ActionPackageInstalled: () => ActionPackageInstalled, + ActionSet: () => ActionSet, + ActionWatchTypingLocations: () => ActionWatchTypingLocations, + Arguments: () => Arguments, + AutoImportProviderProject: () => AutoImportProviderProject, + AuxiliaryProject: () => AuxiliaryProject, + CharRangeSection: () => CharRangeSection, + CloseFileWatcherEvent: () => CloseFileWatcherEvent, + CommandNames: () => CommandNames, + ConfigFileDiagEvent: () => ConfigFileDiagEvent, + ConfiguredProject: () => ConfiguredProject2, + CreateDirectoryWatcherEvent: () => CreateDirectoryWatcherEvent, + CreateFileWatcherEvent: () => CreateFileWatcherEvent, + Errors: () => Errors, + EventBeginInstallTypes: () => EventBeginInstallTypes, + EventEndInstallTypes: () => EventEndInstallTypes, + EventInitializationFailed: () => EventInitializationFailed, + EventTypesRegistry: () => EventTypesRegistry, + ExternalProject: () => ExternalProject2, + GcTimer: () => GcTimer, + InferredProject: () => InferredProject2, + LargeFileReferencedEvent: () => LargeFileReferencedEvent, + LineIndex: () => LineIndex, + LineLeaf: () => LineLeaf, + LineNode: () => LineNode, + LogLevel: () => LogLevel2, + Msg: () => Msg, + OpenFileInfoTelemetryEvent: () => OpenFileInfoTelemetryEvent, + Project: () => Project3, + ProjectInfoTelemetryEvent: () => ProjectInfoTelemetryEvent, + ProjectKind: () => ProjectKind, + ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent, + ProjectLoadingFinishEvent: () => ProjectLoadingFinishEvent, + ProjectLoadingStartEvent: () => ProjectLoadingStartEvent, + ProjectReferenceProjectLoadKind: () => ProjectReferenceProjectLoadKind, + ProjectService: () => ProjectService3, + ProjectsUpdatedInBackgroundEvent: () => ProjectsUpdatedInBackgroundEvent, + ScriptInfo: () => ScriptInfo, + ScriptVersionCache: () => ScriptVersionCache, + Session: () => Session3, + TextStorage: () => TextStorage, + ThrottledOperations: () => ThrottledOperations, + TypingsCache: () => TypingsCache, + allFilesAreJsOrDts: () => allFilesAreJsOrDts, + allRootFilesAreJsOrDts: () => allRootFilesAreJsOrDts, + asNormalizedPath: () => asNormalizedPath, + convertCompilerOptions: () => convertCompilerOptions, + convertFormatOptions: () => convertFormatOptions, + convertScriptKindName: () => convertScriptKindName, + convertTypeAcquisition: () => convertTypeAcquisition, + convertUserPreferences: () => convertUserPreferences, + convertWatchOptions: () => convertWatchOptions, + countEachFileTypes: () => countEachFileTypes, + createInstallTypingsRequest: () => createInstallTypingsRequest, + createModuleSpecifierCache: () => createModuleSpecifierCache, + createNormalizedPathMap: () => createNormalizedPathMap, + createPackageJsonCache: () => createPackageJsonCache, + createSortedArray: () => createSortedArray2, + emptyArray: () => emptyArray2, + findArgument: () => findArgument, + forEachResolvedProjectReferenceProject: () => forEachResolvedProjectReferenceProject, + formatDiagnosticToProtocol: () => formatDiagnosticToProtocol, + formatMessage: () => formatMessage2, + getBaseConfigFileName: () => getBaseConfigFileName, + getLocationInNewDocument: () => getLocationInNewDocument, + hasArgument: () => hasArgument, + hasNoTypeScriptSource: () => hasNoTypeScriptSource, + indent: () => indent2, + isBackgroundProject: () => isBackgroundProject, + isConfigFile: () => isConfigFile, + isConfiguredProject: () => isConfiguredProject, + isDynamicFileName: () => isDynamicFileName, + isExternalProject: () => isExternalProject, + isInferredProject: () => isInferredProject, + isInferredProjectName: () => isInferredProjectName, + makeAutoImportProviderProjectName: () => makeAutoImportProviderProjectName, + makeAuxiliaryProjectName: () => makeAuxiliaryProjectName, + makeInferredProjectName: () => makeInferredProjectName, + maxFileSize: () => maxFileSize, + maxProgramSizeForNonTsFiles: () => maxProgramSizeForNonTsFiles, + normalizedPathToPath: () => normalizedPathToPath, + nowString: () => nowString, + nullCancellationToken: () => nullCancellationToken, + nullTypingsInstaller: () => nullTypingsInstaller, + projectContainsInfoDirectly: () => projectContainsInfoDirectly, + protocol: () => ts_server_protocol_exports, + removeSorted: () => removeSorted, + stringifyIndented: () => stringifyIndented, + toEvent: () => toEvent, + toNormalizedPath: () => toNormalizedPath, + tryConvertScriptKindName: () => tryConvertScriptKindName, + typingsInstaller: () => ts_server_typingsInstaller_exports, + updateProjectIfDirty: () => updateProjectIfDirty + }); + var init_ts_server4 = __esm({ + "src/typescript/_namespaces/ts.server.ts"() { + "use strict"; + init_ts_server(); + init_ts_server3(); + } + }); + + // src/typescript/_namespaces/ts.ts + var ts_exports3 = {}; + __export(ts_exports3, { + ANONYMOUS: () => ANONYMOUS, + AccessFlags: () => AccessFlags, + AssertionLevel: () => AssertionLevel, + AssignmentDeclarationKind: () => AssignmentDeclarationKind, + AssignmentKind: () => AssignmentKind, + Associativity: () => Associativity, + BreakpointResolver: () => ts_BreakpointResolver_exports, + BuilderFileEmit: () => BuilderFileEmit, + BuilderProgramKind: () => BuilderProgramKind, + BuilderState: () => BuilderState, + BundleFileSectionKind: () => BundleFileSectionKind, + CallHierarchy: () => ts_CallHierarchy_exports, + CharacterCodes: () => CharacterCodes, + CheckFlags: () => CheckFlags, + CheckMode: () => CheckMode, + ClassificationType: () => ClassificationType, + ClassificationTypeNames: () => ClassificationTypeNames, + CommentDirectiveType: () => CommentDirectiveType, + Comparison: () => Comparison, + CompletionInfoFlags: () => CompletionInfoFlags, + CompletionTriggerKind: () => CompletionTriggerKind, + Completions: () => ts_Completions_exports, + ContainerFlags: () => ContainerFlags, + ContextFlags: () => ContextFlags, + Debug: () => Debug, + DiagnosticCategory: () => DiagnosticCategory, + Diagnostics: () => Diagnostics, + DocumentHighlights: () => DocumentHighlights, + ElementFlags: () => ElementFlags, + EmitFlags: () => EmitFlags, + EmitHint: () => EmitHint, + EmitOnly: () => EmitOnly, + EndOfLineState: () => EndOfLineState, + EnumKind: () => EnumKind, + ExitStatus: () => ExitStatus, + ExportKind: () => ExportKind, + Extension: () => Extension, + ExternalEmitHelpers: () => ExternalEmitHelpers, + FileIncludeKind: () => FileIncludeKind, + FilePreprocessingDiagnosticsKind: () => FilePreprocessingDiagnosticsKind, + FileSystemEntryKind: () => FileSystemEntryKind, + FileWatcherEventKind: () => FileWatcherEventKind, + FindAllReferences: () => ts_FindAllReferences_exports, + FlattenLevel: () => FlattenLevel, + FlowFlags: () => FlowFlags, + ForegroundColorEscapeSequences: () => ForegroundColorEscapeSequences, + FunctionFlags: () => FunctionFlags, + GeneratedIdentifierFlags: () => GeneratedIdentifierFlags, + GetLiteralTextFlags: () => GetLiteralTextFlags, + GoToDefinition: () => ts_GoToDefinition_exports, + HighlightSpanKind: () => HighlightSpanKind, + IdentifierNameMap: () => IdentifierNameMap, + IdentifierNameMultiMap: () => IdentifierNameMultiMap, + ImportKind: () => ImportKind, + ImportsNotUsedAsValues: () => ImportsNotUsedAsValues, + IndentStyle: () => IndentStyle, + IndexFlags: () => IndexFlags, + IndexKind: () => IndexKind, + InferenceFlags: () => InferenceFlags, + InferencePriority: () => InferencePriority, + InlayHintKind: () => InlayHintKind, + InlayHints: () => ts_InlayHints_exports, + InternalEmitFlags: () => InternalEmitFlags, + InternalSymbolName: () => InternalSymbolName, + InvalidatedProjectKind: () => InvalidatedProjectKind, + JSDocParsingMode: () => JSDocParsingMode, + JsDoc: () => ts_JsDoc_exports, + JsTyping: () => ts_JsTyping_exports, + JsxEmit: () => JsxEmit, + JsxFlags: () => JsxFlags, + JsxReferenceKind: () => JsxReferenceKind, + LanguageServiceMode: () => LanguageServiceMode, + LanguageVariant: () => LanguageVariant, + LexicalEnvironmentFlags: () => LexicalEnvironmentFlags, + ListFormat: () => ListFormat, + LogLevel: () => LogLevel, + MemberOverrideStatus: () => MemberOverrideStatus, + ModifierFlags: () => ModifierFlags, + ModuleDetectionKind: () => ModuleDetectionKind, + ModuleInstanceState: () => ModuleInstanceState, + ModuleKind: () => ModuleKind, + ModuleResolutionKind: () => ModuleResolutionKind, + ModuleSpecifierEnding: () => ModuleSpecifierEnding, + NavigateTo: () => ts_NavigateTo_exports, + NavigationBar: () => ts_NavigationBar_exports, + NewLineKind: () => NewLineKind, + NodeBuilderFlags: () => NodeBuilderFlags, + NodeCheckFlags: () => NodeCheckFlags, + NodeFactoryFlags: () => NodeFactoryFlags, + NodeFlags: () => NodeFlags, + NodeResolutionFeatures: () => NodeResolutionFeatures, + ObjectFlags: () => ObjectFlags, + OperationCanceledException: () => OperationCanceledException, + OperatorPrecedence: () => OperatorPrecedence, + OrganizeImports: () => ts_OrganizeImports_exports, + OrganizeImportsMode: () => OrganizeImportsMode, + OuterExpressionKinds: () => OuterExpressionKinds, + OutliningElementsCollector: () => ts_OutliningElementsCollector_exports, + OutliningSpanKind: () => OutliningSpanKind, + OutputFileType: () => OutputFileType, + PackageJsonAutoImportPreference: () => PackageJsonAutoImportPreference, + PackageJsonDependencyGroup: () => PackageJsonDependencyGroup, + PatternMatchKind: () => PatternMatchKind, + PollingInterval: () => PollingInterval, + PollingWatchKind: () => PollingWatchKind, + PragmaKindFlags: () => PragmaKindFlags, + PrivateIdentifierKind: () => PrivateIdentifierKind, + ProcessLevel: () => ProcessLevel, + ProgramUpdateLevel: () => ProgramUpdateLevel, + QuotePreference: () => QuotePreference, + RelationComparisonResult: () => RelationComparisonResult, + Rename: () => ts_Rename_exports, + ScriptElementKind: () => ScriptElementKind, + ScriptElementKindModifier: () => ScriptElementKindModifier, + ScriptKind: () => ScriptKind, + ScriptSnapshot: () => ScriptSnapshot, + ScriptTarget: () => ScriptTarget, + SemanticClassificationFormat: () => SemanticClassificationFormat, + SemanticMeaning: () => SemanticMeaning, + SemicolonPreference: () => SemicolonPreference, + SignatureCheckMode: () => SignatureCheckMode, + SignatureFlags: () => SignatureFlags, + SignatureHelp: () => ts_SignatureHelp_exports, + SignatureKind: () => SignatureKind, + SmartSelectionRange: () => ts_SmartSelectionRange_exports, + SnippetKind: () => SnippetKind, + SortKind: () => SortKind, + StructureIsReused: () => StructureIsReused, + SymbolAccessibility: () => SymbolAccessibility, + SymbolDisplay: () => ts_SymbolDisplay_exports, + SymbolDisplayPartKind: () => SymbolDisplayPartKind, + SymbolFlags: () => SymbolFlags, + SymbolFormatFlags: () => SymbolFormatFlags, + SyntaxKind: () => SyntaxKind, + SyntheticSymbolKind: () => SyntheticSymbolKind, + Ternary: () => Ternary, + ThrottledCancellationToken: () => ThrottledCancellationToken, + TokenClass: () => TokenClass, + TokenFlags: () => TokenFlags, + TransformFlags: () => TransformFlags, + TypeFacts: () => TypeFacts, + TypeFlags: () => TypeFlags, + TypeFormatFlags: () => TypeFormatFlags, + TypeMapKind: () => TypeMapKind, + TypePredicateKind: () => TypePredicateKind, + TypeReferenceSerializationKind: () => TypeReferenceSerializationKind, + UnionReduction: () => UnionReduction, + UpToDateStatusType: () => UpToDateStatusType, + VarianceFlags: () => VarianceFlags, + Version: () => Version, + VersionRange: () => VersionRange, + WatchDirectoryFlags: () => WatchDirectoryFlags, + WatchDirectoryKind: () => WatchDirectoryKind, + WatchFileKind: () => WatchFileKind, + WatchLogLevel: () => WatchLogLevel, + WatchType: () => WatchType, + accessPrivateIdentifier: () => accessPrivateIdentifier, + addDisposableResourceHelper: () => addDisposableResourceHelper, + addEmitFlags: () => addEmitFlags, + addEmitHelper: () => addEmitHelper, + addEmitHelpers: () => addEmitHelpers, + addInternalEmitFlags: () => addInternalEmitFlags, + addNodeFactoryPatcher: () => addNodeFactoryPatcher, + addObjectAllocatorPatcher: () => addObjectAllocatorPatcher, + addRange: () => addRange, + addRelatedInfo: () => addRelatedInfo, + addSyntheticLeadingComment: () => addSyntheticLeadingComment, + addSyntheticTrailingComment: () => addSyntheticTrailingComment, + addToSeen: () => addToSeen, + advancedAsyncSuperHelper: () => advancedAsyncSuperHelper, + affectsDeclarationPathOptionDeclarations: () => affectsDeclarationPathOptionDeclarations, + affectsEmitOptionDeclarations: () => affectsEmitOptionDeclarations, + allKeysStartWithDot: () => allKeysStartWithDot, + altDirectorySeparator: () => altDirectorySeparator, + and: () => and, + append: () => append, + appendIfUnique: () => appendIfUnique, + arrayFrom: () => arrayFrom, + arrayIsEqualTo: () => arrayIsEqualTo, + arrayIsHomogeneous: () => arrayIsHomogeneous, + arrayIsSorted: () => arrayIsSorted, + arrayOf: () => arrayOf, + arrayReverseIterator: () => arrayReverseIterator, + arrayToMap: () => arrayToMap, + arrayToMultiMap: () => arrayToMultiMap, + arrayToNumericMap: () => arrayToNumericMap, + arraysEqual: () => arraysEqual, + assertType: () => assertType, + assign: () => assign, + assignHelper: () => assignHelper, + asyncDelegator: () => asyncDelegator, + asyncGeneratorHelper: () => asyncGeneratorHelper, + asyncSuperHelper: () => asyncSuperHelper, + asyncValues: () => asyncValues, + attachFileToDiagnostics: () => attachFileToDiagnostics, + awaitHelper: () => awaitHelper, + awaiterHelper: () => awaiterHelper, + base64decode: () => base64decode, + base64encode: () => base64encode, + binarySearch: () => binarySearch, + binarySearchKey: () => binarySearchKey, + bindSourceFile: () => bindSourceFile, + breakIntoCharacterSpans: () => breakIntoCharacterSpans, + breakIntoWordSpans: () => breakIntoWordSpans, + buildLinkParts: () => buildLinkParts, + buildOpts: () => buildOpts, + buildOverload: () => buildOverload, + bundlerModuleNameResolver: () => bundlerModuleNameResolver, + canBeConvertedToAsync: () => canBeConvertedToAsync, + canHaveDecorators: () => canHaveDecorators, + canHaveExportModifier: () => canHaveExportModifier, + canHaveFlowNode: () => canHaveFlowNode, + canHaveIllegalDecorators: () => canHaveIllegalDecorators, + canHaveIllegalModifiers: () => canHaveIllegalModifiers, + canHaveIllegalType: () => canHaveIllegalType, + canHaveIllegalTypeParameters: () => canHaveIllegalTypeParameters, + canHaveJSDoc: () => canHaveJSDoc, + canHaveLocals: () => canHaveLocals, + canHaveModifiers: () => canHaveModifiers, + canHaveSymbol: () => canHaveSymbol, + canJsonReportNoInputFiles: () => canJsonReportNoInputFiles, + canProduceDiagnostics: () => canProduceDiagnostics, + canUsePropertyAccess: () => canUsePropertyAccess, + canWatchAffectingLocation: () => canWatchAffectingLocation, + canWatchAtTypes: () => canWatchAtTypes, + canWatchDirectoryOrFile: () => canWatchDirectoryOrFile, + cartesianProduct: () => cartesianProduct, + cast: () => cast, + chainBundle: () => chainBundle, + chainDiagnosticMessages: () => chainDiagnosticMessages, + changeAnyExtension: () => changeAnyExtension, + changeCompilerHostLikeToUseCache: () => changeCompilerHostLikeToUseCache, + changeExtension: () => changeExtension, + changesAffectModuleResolution: () => changesAffectModuleResolution, + changesAffectingProgramStructure: () => changesAffectingProgramStructure, + childIsDecorated: () => childIsDecorated, + classElementOrClassElementParameterIsDecorated: () => classElementOrClassElementParameterIsDecorated, + classHasClassThisAssignment: () => classHasClassThisAssignment, + classHasDeclaredOrExplicitlyAssignedName: () => classHasDeclaredOrExplicitlyAssignedName, + classHasExplicitlyAssignedName: () => classHasExplicitlyAssignedName, + classOrConstructorParameterIsDecorated: () => classOrConstructorParameterIsDecorated, + classPrivateFieldGetHelper: () => classPrivateFieldGetHelper, + classPrivateFieldInHelper: () => classPrivateFieldInHelper, + classPrivateFieldSetHelper: () => classPrivateFieldSetHelper, + classicNameResolver: () => classicNameResolver, + classifier: () => ts_classifier_exports, + cleanExtendedConfigCache: () => cleanExtendedConfigCache, + clear: () => clear, + clearMap: () => clearMap, + clearSharedExtendedConfigFileWatcher: () => clearSharedExtendedConfigFileWatcher, + climbPastPropertyAccess: () => climbPastPropertyAccess, + climbPastPropertyOrElementAccess: () => climbPastPropertyOrElementAccess, + clone: () => clone, + cloneCompilerOptions: () => cloneCompilerOptions, + closeFileWatcher: () => closeFileWatcher, + closeFileWatcherOf: () => closeFileWatcherOf, + codefix: () => ts_codefix_exports, + collapseTextChangeRangesAcrossMultipleVersions: () => collapseTextChangeRangesAcrossMultipleVersions, + collectExternalModuleInfo: () => collectExternalModuleInfo, + combine: () => combine, + combinePaths: () => combinePaths, + commentPragmas: () => commentPragmas, + commonOptionsWithBuild: () => commonOptionsWithBuild, + commonPackageFolders: () => commonPackageFolders, + compact: () => compact, + compareBooleans: () => compareBooleans, + compareDataObjects: () => compareDataObjects, + compareDiagnostics: () => compareDiagnostics, + compareDiagnosticsSkipRelatedInformation: () => compareDiagnosticsSkipRelatedInformation, + compareEmitHelpers: () => compareEmitHelpers, + compareNumberOfDirectorySeparators: () => compareNumberOfDirectorySeparators, + comparePaths: () => comparePaths, + comparePathsCaseInsensitive: () => comparePathsCaseInsensitive, + comparePathsCaseSensitive: () => comparePathsCaseSensitive, + comparePatternKeys: () => comparePatternKeys, + compareProperties: () => compareProperties, + compareStringsCaseInsensitive: () => compareStringsCaseInsensitive, + compareStringsCaseInsensitiveEslintCompatible: () => compareStringsCaseInsensitiveEslintCompatible, + compareStringsCaseSensitive: () => compareStringsCaseSensitive, + compareStringsCaseSensitiveUI: () => compareStringsCaseSensitiveUI, + compareTextSpans: () => compareTextSpans, + compareValues: () => compareValues, + compileOnSaveCommandLineOption: () => compileOnSaveCommandLineOption, + compilerOptionsAffectDeclarationPath: () => compilerOptionsAffectDeclarationPath, + compilerOptionsAffectEmit: () => compilerOptionsAffectEmit, + compilerOptionsAffectSemanticDiagnostics: () => compilerOptionsAffectSemanticDiagnostics, + compilerOptionsDidYouMeanDiagnostics: () => compilerOptionsDidYouMeanDiagnostics, + compilerOptionsIndicateEsModules: () => compilerOptionsIndicateEsModules, + compose: () => compose, + computeCommonSourceDirectoryOfFilenames: () => computeCommonSourceDirectoryOfFilenames, + computeLineAndCharacterOfPosition: () => computeLineAndCharacterOfPosition, + computeLineOfPosition: () => computeLineOfPosition, + computeLineStarts: () => computeLineStarts, + computePositionOfLineAndCharacter: () => computePositionOfLineAndCharacter, + computeSignature: () => computeSignature, + computeSignatureWithDiagnostics: () => computeSignatureWithDiagnostics, + computeSuggestionDiagnostics: () => computeSuggestionDiagnostics, + concatenate: () => concatenate, + concatenateDiagnosticMessageChains: () => concatenateDiagnosticMessageChains, + consumesNodeCoreModules: () => consumesNodeCoreModules, + contains: () => contains, + containsIgnoredPath: () => containsIgnoredPath, + containsObjectRestOrSpread: () => containsObjectRestOrSpread, + containsParseError: () => containsParseError, + containsPath: () => containsPath, + convertCompilerOptionsForTelemetry: () => convertCompilerOptionsForTelemetry, + convertCompilerOptionsFromJson: () => convertCompilerOptionsFromJson, + convertJsonOption: () => convertJsonOption, + convertToBase64: () => convertToBase64, + convertToJson: () => convertToJson, + convertToObject: () => convertToObject, + convertToOptionsWithAbsolutePaths: () => convertToOptionsWithAbsolutePaths, + convertToRelativePath: () => convertToRelativePath, + convertToTSConfig: () => convertToTSConfig, + convertTypeAcquisitionFromJson: () => convertTypeAcquisitionFromJson, + copyComments: () => copyComments, + copyEntries: () => copyEntries, + copyLeadingComments: () => copyLeadingComments, + copyProperties: () => copyProperties, + copyTrailingAsLeadingComments: () => copyTrailingAsLeadingComments, + copyTrailingComments: () => copyTrailingComments, + couldStartTrivia: () => couldStartTrivia, + countWhere: () => countWhere, + createAbstractBuilder: () => createAbstractBuilder, + createAccessorPropertyBackingField: () => createAccessorPropertyBackingField, + createAccessorPropertyGetRedirector: () => createAccessorPropertyGetRedirector, + createAccessorPropertySetRedirector: () => createAccessorPropertySetRedirector, + createBaseNodeFactory: () => createBaseNodeFactory, + createBinaryExpressionTrampoline: () => createBinaryExpressionTrampoline, + createBindingHelper: () => createBindingHelper, + createBuildInfo: () => createBuildInfo, + createBuilderProgram: () => createBuilderProgram, + createBuilderProgramUsingProgramBuildInfo: () => createBuilderProgramUsingProgramBuildInfo, + createBuilderStatusReporter: () => createBuilderStatusReporter, + createCacheWithRedirects: () => createCacheWithRedirects, + createCacheableExportInfoMap: () => createCacheableExportInfoMap, + createCachedDirectoryStructureHost: () => createCachedDirectoryStructureHost, + createClassNamedEvaluationHelperBlock: () => createClassNamedEvaluationHelperBlock, + createClassThisAssignmentBlock: () => createClassThisAssignmentBlock, + createClassifier: () => createClassifier, + createCommentDirectivesMap: () => createCommentDirectivesMap, + createCompilerDiagnostic: () => createCompilerDiagnostic, + createCompilerDiagnosticForInvalidCustomType: () => createCompilerDiagnosticForInvalidCustomType, + createCompilerDiagnosticFromMessageChain: () => createCompilerDiagnosticFromMessageChain, + createCompilerHost: () => createCompilerHost, + createCompilerHostFromProgramHost: () => createCompilerHostFromProgramHost, + createCompilerHostWorker: () => createCompilerHostWorker, + createDetachedDiagnostic: () => createDetachedDiagnostic, + createDiagnosticCollection: () => createDiagnosticCollection, + createDiagnosticForFileFromMessageChain: () => createDiagnosticForFileFromMessageChain, + createDiagnosticForNode: () => createDiagnosticForNode, + createDiagnosticForNodeArray: () => createDiagnosticForNodeArray, + createDiagnosticForNodeArrayFromMessageChain: () => createDiagnosticForNodeArrayFromMessageChain, + createDiagnosticForNodeFromMessageChain: () => createDiagnosticForNodeFromMessageChain, + createDiagnosticForNodeInSourceFile: () => createDiagnosticForNodeInSourceFile, + createDiagnosticForRange: () => createDiagnosticForRange, + createDiagnosticMessageChainFromDiagnostic: () => createDiagnosticMessageChainFromDiagnostic, + createDiagnosticReporter: () => createDiagnosticReporter, + createDocumentPositionMapper: () => createDocumentPositionMapper, + createDocumentRegistry: () => createDocumentRegistry, + createDocumentRegistryInternal: () => createDocumentRegistryInternal, + createEmitAndSemanticDiagnosticsBuilderProgram: () => createEmitAndSemanticDiagnosticsBuilderProgram, + createEmitHelperFactory: () => createEmitHelperFactory, + createEmptyExports: () => createEmptyExports, + createExpressionForJsxElement: () => createExpressionForJsxElement, + createExpressionForJsxFragment: () => createExpressionForJsxFragment, + createExpressionForObjectLiteralElementLike: () => createExpressionForObjectLiteralElementLike, + createExpressionForPropertyName: () => createExpressionForPropertyName, + createExpressionFromEntityName: () => createExpressionFromEntityName, + createExternalHelpersImportDeclarationIfNeeded: () => createExternalHelpersImportDeclarationIfNeeded, + createFileDiagnostic: () => createFileDiagnostic, + createFileDiagnosticFromMessageChain: () => createFileDiagnosticFromMessageChain, + createForOfBindingStatement: () => createForOfBindingStatement, + createGetCanonicalFileName: () => createGetCanonicalFileName, + createGetSourceFile: () => createGetSourceFile, + createGetSymbolAccessibilityDiagnosticForNode: () => createGetSymbolAccessibilityDiagnosticForNode, + createGetSymbolAccessibilityDiagnosticForNodeName: () => createGetSymbolAccessibilityDiagnosticForNodeName, + createGetSymbolWalker: () => createGetSymbolWalker, + createIncrementalCompilerHost: () => createIncrementalCompilerHost, + createIncrementalProgram: () => createIncrementalProgram, + createInputFiles: () => createInputFiles, + createInputFilesWithFilePaths: () => createInputFilesWithFilePaths, + createInputFilesWithFileTexts: () => createInputFilesWithFileTexts, + createJsxFactoryExpression: () => createJsxFactoryExpression, + createLanguageService: () => createLanguageService, + createLanguageServiceSourceFile: () => createLanguageServiceSourceFile, + createMemberAccessForPropertyName: () => createMemberAccessForPropertyName, + createModeAwareCache: () => createModeAwareCache, + createModeAwareCacheKey: () => createModeAwareCacheKey, + createModuleNotFoundChain: () => createModuleNotFoundChain, + createModuleResolutionCache: () => createModuleResolutionCache, + createModuleResolutionLoader: () => createModuleResolutionLoader, + createModuleResolutionLoaderUsingGlobalCache: () => createModuleResolutionLoaderUsingGlobalCache, + createModuleSpecifierResolutionHost: () => createModuleSpecifierResolutionHost, + createMultiMap: () => createMultiMap, + createNodeConverters: () => createNodeConverters, + createNodeFactory: () => createNodeFactory, + createOptionNameMap: () => createOptionNameMap, + createOverload: () => createOverload, + createPackageJsonImportFilter: () => createPackageJsonImportFilter, + createPackageJsonInfo: () => createPackageJsonInfo, + createParenthesizerRules: () => createParenthesizerRules, + createPatternMatcher: () => createPatternMatcher, + createPrependNodes: () => createPrependNodes, + createPrinter: () => createPrinter, + createPrinterWithDefaults: () => createPrinterWithDefaults, + createPrinterWithRemoveComments: () => createPrinterWithRemoveComments, + createPrinterWithRemoveCommentsNeverAsciiEscape: () => createPrinterWithRemoveCommentsNeverAsciiEscape, + createPrinterWithRemoveCommentsOmitTrailingSemicolon: () => createPrinterWithRemoveCommentsOmitTrailingSemicolon, + createProgram: () => createProgram, + createProgramHost: () => createProgramHost, + createPropertyNameNodeForIdentifierOrLiteral: () => createPropertyNameNodeForIdentifierOrLiteral, + createQueue: () => createQueue, + createRange: () => createRange, + createRedirectedBuilderProgram: () => createRedirectedBuilderProgram, + createResolutionCache: () => createResolutionCache, + createRuntimeTypeSerializer: () => createRuntimeTypeSerializer, + createScanner: () => createScanner, + createSemanticDiagnosticsBuilderProgram: () => createSemanticDiagnosticsBuilderProgram, + createSet: () => createSet, + createSolutionBuilder: () => createSolutionBuilder, + createSolutionBuilderHost: () => createSolutionBuilderHost, + createSolutionBuilderWithWatch: () => createSolutionBuilderWithWatch, + createSolutionBuilderWithWatchHost: () => createSolutionBuilderWithWatchHost, + createSortedArray: () => createSortedArray, + createSourceFile: () => createSourceFile, + createSourceMapGenerator: () => createSourceMapGenerator, + createSourceMapSource: () => createSourceMapSource, + createSuperAccessVariableStatement: () => createSuperAccessVariableStatement, + createSymbolTable: () => createSymbolTable, + createSymlinkCache: () => createSymlinkCache, + createSystemWatchFunctions: () => createSystemWatchFunctions, + createTextChange: () => createTextChange, + createTextChangeFromStartLength: () => createTextChangeFromStartLength, + createTextChangeRange: () => createTextChangeRange, + createTextRangeFromNode: () => createTextRangeFromNode, + createTextRangeFromSpan: () => createTextRangeFromSpan, + createTextSpan: () => createTextSpan, + createTextSpanFromBounds: () => createTextSpanFromBounds, + createTextSpanFromNode: () => createTextSpanFromNode, + createTextSpanFromRange: () => createTextSpanFromRange, + createTextSpanFromStringLiteralLikeContent: () => createTextSpanFromStringLiteralLikeContent, + createTextWriter: () => createTextWriter, + createTokenRange: () => createTokenRange, + createTypeChecker: () => createTypeChecker, + createTypeReferenceDirectiveResolutionCache: () => createTypeReferenceDirectiveResolutionCache, + createTypeReferenceResolutionLoader: () => createTypeReferenceResolutionLoader, + createUnparsedSourceFile: () => createUnparsedSourceFile, + createWatchCompilerHost: () => createWatchCompilerHost2, + createWatchCompilerHostOfConfigFile: () => createWatchCompilerHostOfConfigFile, + createWatchCompilerHostOfFilesAndCompilerOptions: () => createWatchCompilerHostOfFilesAndCompilerOptions, + createWatchFactory: () => createWatchFactory, + createWatchHost: () => createWatchHost, + createWatchProgram: () => createWatchProgram, + createWatchStatusReporter: () => createWatchStatusReporter, + createWriteFileMeasuringIO: () => createWriteFileMeasuringIO, + declarationNameToString: () => declarationNameToString, + decodeMappings: () => decodeMappings, + decodedTextSpanIntersectsWith: () => decodedTextSpanIntersectsWith, + decorateHelper: () => decorateHelper, + deduplicate: () => deduplicate, + defaultIncludeSpec: () => defaultIncludeSpec, + defaultInitCompilerOptions: () => defaultInitCompilerOptions, + defaultMaximumTruncationLength: () => defaultMaximumTruncationLength, + deno: () => deno_exports, + detectSortCaseSensitivity: () => detectSortCaseSensitivity, + diagnosticCategoryName: () => diagnosticCategoryName, + diagnosticToString: () => diagnosticToString, + directoryProbablyExists: () => directoryProbablyExists, + directorySeparator: () => directorySeparator, + displayPart: () => displayPart, + displayPartsToString: () => displayPartsToString, + disposeEmitNodes: () => disposeEmitNodes, + disposeResourcesHelper: () => disposeResourcesHelper, + documentSpansEqual: () => documentSpansEqual, + dumpTracingLegend: () => dumpTracingLegend, + elementAt: () => elementAt, + elideNodes: () => elideNodes, + emitComments: () => emitComments, + emitDetachedComments: () => emitDetachedComments, + emitFiles: () => emitFiles, + emitFilesAndReportErrors: () => emitFilesAndReportErrors, + emitFilesAndReportErrorsAndGetExitStatus: () => emitFilesAndReportErrorsAndGetExitStatus, + emitModuleKindIsNonNodeESM: () => emitModuleKindIsNonNodeESM, + emitNewLineBeforeLeadingCommentOfPosition: () => emitNewLineBeforeLeadingCommentOfPosition, + emitNewLineBeforeLeadingComments: () => emitNewLineBeforeLeadingComments, + emitNewLineBeforeLeadingCommentsOfPosition: () => emitNewLineBeforeLeadingCommentsOfPosition, + emitSkippedWithNoDiagnostics: () => emitSkippedWithNoDiagnostics, + emitUsingBuildInfo: () => emitUsingBuildInfo, + emptyArray: () => emptyArray, + emptyFileSystemEntries: () => emptyFileSystemEntries, + emptyMap: () => emptyMap, + emptyOptions: () => emptyOptions, + emptySet: () => emptySet, + endsWith: () => endsWith, + ensurePathIsNonModuleName: () => ensurePathIsNonModuleName, + ensureScriptKind: () => ensureScriptKind, + ensureTrailingDirectorySeparator: () => ensureTrailingDirectorySeparator, + entityNameToString: () => entityNameToString, + enumerateInsertsAndDeletes: () => enumerateInsertsAndDeletes, + equalOwnProperties: () => equalOwnProperties, + equateStringsCaseInsensitive: () => equateStringsCaseInsensitive, + equateStringsCaseSensitive: () => equateStringsCaseSensitive, + equateValues: () => equateValues, + esDecorateHelper: () => esDecorateHelper, + escapeJsxAttributeString: () => escapeJsxAttributeString, + escapeLeadingUnderscores: () => escapeLeadingUnderscores, + escapeNonAsciiString: () => escapeNonAsciiString, + escapeSnippetText: () => escapeSnippetText, + escapeString: () => escapeString, + every: () => every, + expandPreOrPostfixIncrementOrDecrementExpression: () => expandPreOrPostfixIncrementOrDecrementExpression, + explainFiles: () => explainFiles, + explainIfFileIsRedirectAndImpliedFormat: () => explainIfFileIsRedirectAndImpliedFormat, + exportAssignmentIsAlias: () => exportAssignmentIsAlias, + exportStarHelper: () => exportStarHelper, + expressionResultIsUnused: () => expressionResultIsUnused, + extend: () => extend, + extendsHelper: () => extendsHelper, + extensionFromPath: () => extensionFromPath, + extensionIsTS: () => extensionIsTS, + extensionsNotSupportingExtensionlessResolution: () => extensionsNotSupportingExtensionlessResolution, + externalHelpersModuleNameText: () => externalHelpersModuleNameText, + factory: () => factory, + fileExtensionIs: () => fileExtensionIs, + fileExtensionIsOneOf: () => fileExtensionIsOneOf, + fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics, + fileShouldUseJavaScriptRequire: () => fileShouldUseJavaScriptRequire, + filter: () => filter, + filterMutate: () => filterMutate, + filterSemanticDiagnostics: () => filterSemanticDiagnostics, + find: () => find, + findAncestor: () => findAncestor, + findBestPatternMatch: () => findBestPatternMatch, + findChildOfKind: () => findChildOfKind, + findComputedPropertyNameCacheAssignment: () => findComputedPropertyNameCacheAssignment, + findConfigFile: () => findConfigFile, + findContainingList: () => findContainingList, + findDiagnosticForNode: () => findDiagnosticForNode, + findFirstNonJsxWhitespaceToken: () => findFirstNonJsxWhitespaceToken, + findIndex: () => findIndex, + findLast: () => findLast, + findLastIndex: () => findLastIndex, + findListItemInfo: () => findListItemInfo, + findMap: () => findMap, + findModifier: () => findModifier, + findNextToken: () => findNextToken, + findPackageJson: () => findPackageJson, + findPackageJsons: () => findPackageJsons, + findPrecedingMatchingToken: () => findPrecedingMatchingToken, + findPrecedingToken: () => findPrecedingToken, + findSuperStatementIndexPath: () => findSuperStatementIndexPath, + findTokenOnLeftOfPosition: () => findTokenOnLeftOfPosition, + findUseStrictPrologue: () => findUseStrictPrologue, + first: () => first, + firstDefined: () => firstDefined, + firstDefinedIterator: () => firstDefinedIterator, + firstIterator: () => firstIterator, + firstOrOnly: () => firstOrOnly, + firstOrUndefined: () => firstOrUndefined, + firstOrUndefinedIterator: () => firstOrUndefinedIterator, + fixupCompilerOptions: () => fixupCompilerOptions, + flatMap: () => flatMap, + flatMapIterator: () => flatMapIterator, + flatMapToMutable: () => flatMapToMutable, + flatten: () => flatten, + flattenCommaList: () => flattenCommaList, + flattenDestructuringAssignment: () => flattenDestructuringAssignment, + flattenDestructuringBinding: () => flattenDestructuringBinding, + flattenDiagnosticMessageText: () => flattenDiagnosticMessageText, + forEach: () => forEach, + forEachAncestor: () => forEachAncestor, + forEachAncestorDirectory: () => forEachAncestorDirectory, + forEachChild: () => forEachChild, + forEachChildRecursively: () => forEachChildRecursively, + forEachEmittedFile: () => forEachEmittedFile, + forEachEnclosingBlockScopeContainer: () => forEachEnclosingBlockScopeContainer, + forEachEntry: () => forEachEntry, + forEachExternalModuleToImportFrom: () => forEachExternalModuleToImportFrom, + forEachImportClauseDeclaration: () => forEachImportClauseDeclaration, + forEachKey: () => forEachKey, + forEachLeadingCommentRange: () => forEachLeadingCommentRange, + forEachNameInAccessChainWalkingLeft: () => forEachNameInAccessChainWalkingLeft, + forEachPropertyAssignment: () => forEachPropertyAssignment, + forEachResolvedProjectReference: () => forEachResolvedProjectReference, + forEachReturnStatement: () => forEachReturnStatement, + forEachRight: () => forEachRight, + forEachTrailingCommentRange: () => forEachTrailingCommentRange, + forEachTsConfigPropArray: () => forEachTsConfigPropArray, + forEachUnique: () => forEachUnique, + forEachYieldExpression: () => forEachYieldExpression, + forSomeAncestorDirectory: () => forSomeAncestorDirectory, + formatColorAndReset: () => formatColorAndReset, + formatDiagnostic: () => formatDiagnostic, + formatDiagnostics: () => formatDiagnostics, + formatDiagnosticsWithColorAndContext: () => formatDiagnosticsWithColorAndContext, + formatGeneratedName: () => formatGeneratedName, + formatGeneratedNamePart: () => formatGeneratedNamePart, + formatLocation: () => formatLocation, + formatMessage: () => formatMessage, + formatStringFromArgs: () => formatStringFromArgs, + formatting: () => ts_formatting_exports, + fullTripleSlashAMDReferencePathRegEx: () => fullTripleSlashAMDReferencePathRegEx, + fullTripleSlashReferencePathRegEx: () => fullTripleSlashReferencePathRegEx, + generateDjb2Hash: () => generateDjb2Hash, + generateTSConfig: () => generateTSConfig, + generatorHelper: () => generatorHelper, + getAdjustedReferenceLocation: () => getAdjustedReferenceLocation, + getAdjustedRenameLocation: () => getAdjustedRenameLocation, + getAliasDeclarationFromName: () => getAliasDeclarationFromName, + getAllAccessorDeclarations: () => getAllAccessorDeclarations, + getAllDecoratorsOfClass: () => getAllDecoratorsOfClass, + getAllDecoratorsOfClassElement: () => getAllDecoratorsOfClassElement, + getAllJSDocTags: () => getAllJSDocTags, + getAllJSDocTagsOfKind: () => getAllJSDocTagsOfKind, + getAllKeys: () => getAllKeys, + getAllProjectOutputs: () => getAllProjectOutputs, + getAllSuperTypeNodes: () => getAllSuperTypeNodes, + getAllUnscopedEmitHelpers: () => getAllUnscopedEmitHelpers, + getAllowJSCompilerOption: () => getAllowJSCompilerOption, + getAllowSyntheticDefaultImports: () => getAllowSyntheticDefaultImports, + getAncestor: () => getAncestor, + getAnyExtensionFromPath: () => getAnyExtensionFromPath, + getAreDeclarationMapsEnabled: () => getAreDeclarationMapsEnabled, + getAssignedExpandoInitializer: () => getAssignedExpandoInitializer, + getAssignedName: () => getAssignedName, + getAssignedNameOfIdentifier: () => getAssignedNameOfIdentifier, + getAssignmentDeclarationKind: () => getAssignmentDeclarationKind, + getAssignmentDeclarationPropertyAccessKind: () => getAssignmentDeclarationPropertyAccessKind, + getAssignmentTargetKind: () => getAssignmentTargetKind, + getAutomaticTypeDirectiveNames: () => getAutomaticTypeDirectiveNames, + getBaseFileName: () => getBaseFileName, + getBinaryOperatorPrecedence: () => getBinaryOperatorPrecedence, + getBuildInfo: () => getBuildInfo, + getBuildInfoFileVersionMap: () => getBuildInfoFileVersionMap, + getBuildInfoText: () => getBuildInfoText, + getBuildOrderFromAnyBuildOrder: () => getBuildOrderFromAnyBuildOrder, + getBuilderCreationParameters: () => getBuilderCreationParameters, + getBuilderFileEmit: () => getBuilderFileEmit, + getCheckFlags: () => getCheckFlags, + getClassExtendsHeritageElement: () => getClassExtendsHeritageElement, + getClassLikeDeclarationOfSymbol: () => getClassLikeDeclarationOfSymbol, + getCombinedLocalAndExportSymbolFlags: () => getCombinedLocalAndExportSymbolFlags, + getCombinedModifierFlags: () => getCombinedModifierFlags, + getCombinedNodeFlags: () => getCombinedNodeFlags, + getCombinedNodeFlagsAlwaysIncludeJSDoc: () => getCombinedNodeFlagsAlwaysIncludeJSDoc, + getCommentRange: () => getCommentRange, + getCommonSourceDirectory: () => getCommonSourceDirectory, + getCommonSourceDirectoryOfConfig: () => getCommonSourceDirectoryOfConfig, + getCompilerOptionValue: () => getCompilerOptionValue, + getCompilerOptionsDiffValue: () => getCompilerOptionsDiffValue, + getConditions: () => getConditions, + getConfigFileParsingDiagnostics: () => getConfigFileParsingDiagnostics, + getConstantValue: () => getConstantValue, + getContainerFlags: () => getContainerFlags, + getContainerNode: () => getContainerNode, + getContainingClass: () => getContainingClass, + getContainingClassExcludingClassDecorators: () => getContainingClassExcludingClassDecorators, + getContainingClassStaticBlock: () => getContainingClassStaticBlock, + getContainingFunction: () => getContainingFunction, + getContainingFunctionDeclaration: () => getContainingFunctionDeclaration, + getContainingFunctionOrClassStaticBlock: () => getContainingFunctionOrClassStaticBlock, + getContainingNodeArray: () => getContainingNodeArray, + getContainingObjectLiteralElement: () => getContainingObjectLiteralElement, + getContextualTypeFromParent: () => getContextualTypeFromParent, + getContextualTypeFromParentOrAncestorTypeNode: () => getContextualTypeFromParentOrAncestorTypeNode, + getCurrentTime: () => getCurrentTime, + getDeclarationDiagnostics: () => getDeclarationDiagnostics, + getDeclarationEmitExtensionForPath: () => getDeclarationEmitExtensionForPath, + getDeclarationEmitOutputFilePath: () => getDeclarationEmitOutputFilePath, + getDeclarationEmitOutputFilePathWorker: () => getDeclarationEmitOutputFilePathWorker, + getDeclarationFromName: () => getDeclarationFromName, + getDeclarationModifierFlagsFromSymbol: () => getDeclarationModifierFlagsFromSymbol, + getDeclarationOfKind: () => getDeclarationOfKind, + getDeclarationsOfKind: () => getDeclarationsOfKind, + getDeclaredExpandoInitializer: () => getDeclaredExpandoInitializer, + getDecorators: () => getDecorators, + getDefaultCompilerOptions: () => getDefaultCompilerOptions2, + getDefaultExportInfoWorker: () => getDefaultExportInfoWorker, + getDefaultFormatCodeSettings: () => getDefaultFormatCodeSettings, + getDefaultLibFileName: () => getDefaultLibFileName, + getDefaultLibFilePath: () => getDefaultLibFilePath, + getDefaultLikeExportInfo: () => getDefaultLikeExportInfo, + getDiagnosticText: () => getDiagnosticText, + getDiagnosticsWithinSpan: () => getDiagnosticsWithinSpan, + getDirectoryPath: () => getDirectoryPath, + getDirectoryToWatchFailedLookupLocation: () => getDirectoryToWatchFailedLookupLocation, + getDirectoryToWatchFailedLookupLocationFromTypeRoot: () => getDirectoryToWatchFailedLookupLocationFromTypeRoot, + getDocumentPositionMapper: () => getDocumentPositionMapper, + getESModuleInterop: () => getESModuleInterop, + getEditsForFileRename: () => getEditsForFileRename, + getEffectiveBaseTypeNode: () => getEffectiveBaseTypeNode, + getEffectiveConstraintOfTypeParameter: () => getEffectiveConstraintOfTypeParameter, + getEffectiveContainerForJSDocTemplateTag: () => getEffectiveContainerForJSDocTemplateTag, + getEffectiveImplementsTypeNodes: () => getEffectiveImplementsTypeNodes, + getEffectiveInitializer: () => getEffectiveInitializer, + getEffectiveJSDocHost: () => getEffectiveJSDocHost, + getEffectiveModifierFlags: () => getEffectiveModifierFlags, + getEffectiveModifierFlagsAlwaysIncludeJSDoc: () => getEffectiveModifierFlagsAlwaysIncludeJSDoc, + getEffectiveModifierFlagsNoCache: () => getEffectiveModifierFlagsNoCache, + getEffectiveReturnTypeNode: () => getEffectiveReturnTypeNode, + getEffectiveSetAccessorTypeAnnotationNode: () => getEffectiveSetAccessorTypeAnnotationNode, + getEffectiveTypeAnnotationNode: () => getEffectiveTypeAnnotationNode, + getEffectiveTypeParameterDeclarations: () => getEffectiveTypeParameterDeclarations, + getEffectiveTypeRoots: () => getEffectiveTypeRoots, + getElementOrPropertyAccessArgumentExpressionOrName: () => getElementOrPropertyAccessArgumentExpressionOrName, + getElementOrPropertyAccessName: () => getElementOrPropertyAccessName, + getElementsOfBindingOrAssignmentPattern: () => getElementsOfBindingOrAssignmentPattern, + getEmitDeclarations: () => getEmitDeclarations, + getEmitFlags: () => getEmitFlags, + getEmitHelpers: () => getEmitHelpers, + getEmitModuleDetectionKind: () => getEmitModuleDetectionKind, + getEmitModuleKind: () => getEmitModuleKind, + getEmitModuleResolutionKind: () => getEmitModuleResolutionKind, + getEmitScriptTarget: () => getEmitScriptTarget, + getEmitStandardClassFields: () => getEmitStandardClassFields, + getEnclosingBlockScopeContainer: () => getEnclosingBlockScopeContainer, + getEnclosingContainer: () => getEnclosingContainer, + getEncodedSemanticClassifications: () => getEncodedSemanticClassifications, + getEncodedSyntacticClassifications: () => getEncodedSyntacticClassifications, + getEndLinePosition: () => getEndLinePosition, + getEntityNameFromTypeNode: () => getEntityNameFromTypeNode, + getEntrypointsFromPackageJsonInfo: () => getEntrypointsFromPackageJsonInfo, + getErrorCountForSummary: () => getErrorCountForSummary, + getErrorSpanForNode: () => getErrorSpanForNode, + getErrorSummaryText: () => getErrorSummaryText, + getEscapedTextOfIdentifierOrLiteral: () => getEscapedTextOfIdentifierOrLiteral, + getEscapedTextOfJsxAttributeName: () => getEscapedTextOfJsxAttributeName, + getEscapedTextOfJsxNamespacedName: () => getEscapedTextOfJsxNamespacedName, + getExpandoInitializer: () => getExpandoInitializer, + getExportAssignmentExpression: () => getExportAssignmentExpression, + getExportInfoMap: () => getExportInfoMap, + getExportNeedsImportStarHelper: () => getExportNeedsImportStarHelper, + getExpressionAssociativity: () => getExpressionAssociativity, + getExpressionPrecedence: () => getExpressionPrecedence, + getExternalHelpersModuleName: () => getExternalHelpersModuleName, + getExternalModuleImportEqualsDeclarationExpression: () => getExternalModuleImportEqualsDeclarationExpression, + getExternalModuleName: () => getExternalModuleName, + getExternalModuleNameFromDeclaration: () => getExternalModuleNameFromDeclaration, + getExternalModuleNameFromPath: () => getExternalModuleNameFromPath, + getExternalModuleNameLiteral: () => getExternalModuleNameLiteral, + getExternalModuleRequireArgument: () => getExternalModuleRequireArgument, + getFallbackOptions: () => getFallbackOptions, + getFileEmitOutput: () => getFileEmitOutput, + getFileMatcherPatterns: () => getFileMatcherPatterns, + getFileNamesFromConfigSpecs: () => getFileNamesFromConfigSpecs, + getFileWatcherEventKind: () => getFileWatcherEventKind, + getFilesInErrorForSummary: () => getFilesInErrorForSummary, + getFirstConstructorWithBody: () => getFirstConstructorWithBody, + getFirstIdentifier: () => getFirstIdentifier, + getFirstNonSpaceCharacterPosition: () => getFirstNonSpaceCharacterPosition, + getFirstProjectOutput: () => getFirstProjectOutput, + getFixableErrorSpanExpression: () => getFixableErrorSpanExpression, + getFormatCodeSettingsForWriting: () => getFormatCodeSettingsForWriting, + getFullWidth: () => getFullWidth, + getFunctionFlags: () => getFunctionFlags, + getHeritageClause: () => getHeritageClause, + getHostSignatureFromJSDoc: () => getHostSignatureFromJSDoc, + getIdentifierAutoGenerate: () => getIdentifierAutoGenerate, + getIdentifierGeneratedImportReference: () => getIdentifierGeneratedImportReference, + getIdentifierTypeArguments: () => getIdentifierTypeArguments, + getImmediatelyInvokedFunctionExpression: () => getImmediatelyInvokedFunctionExpression, + getImpliedNodeFormatForFile: () => getImpliedNodeFormatForFile, + getImpliedNodeFormatForFileWorker: () => getImpliedNodeFormatForFileWorker, + getImportNeedsImportDefaultHelper: () => getImportNeedsImportDefaultHelper, + getImportNeedsImportStarHelper: () => getImportNeedsImportStarHelper, + getIndentSize: () => getIndentSize, + getIndentString: () => getIndentString, + getInferredLibraryNameResolveFrom: () => getInferredLibraryNameResolveFrom, + getInitializedVariables: () => getInitializedVariables, + getInitializerOfBinaryExpression: () => getInitializerOfBinaryExpression, + getInitializerOfBindingOrAssignmentElement: () => getInitializerOfBindingOrAssignmentElement, + getInterfaceBaseTypeNodes: () => getInterfaceBaseTypeNodes, + getInternalEmitFlags: () => getInternalEmitFlags, + getInvokedExpression: () => getInvokedExpression, + getIsolatedModules: () => getIsolatedModules, + getJSDocAugmentsTag: () => getJSDocAugmentsTag, + getJSDocClassTag: () => getJSDocClassTag, + getJSDocCommentRanges: () => getJSDocCommentRanges, + getJSDocCommentsAndTags: () => getJSDocCommentsAndTags, + getJSDocDeprecatedTag: () => getJSDocDeprecatedTag, + getJSDocDeprecatedTagNoCache: () => getJSDocDeprecatedTagNoCache, + getJSDocEnumTag: () => getJSDocEnumTag, + getJSDocHost: () => getJSDocHost, + getJSDocImplementsTags: () => getJSDocImplementsTags, + getJSDocOverrideTagNoCache: () => getJSDocOverrideTagNoCache, + getJSDocParameterTags: () => getJSDocParameterTags, + getJSDocParameterTagsNoCache: () => getJSDocParameterTagsNoCache, + getJSDocPrivateTag: () => getJSDocPrivateTag, + getJSDocPrivateTagNoCache: () => getJSDocPrivateTagNoCache, + getJSDocProtectedTag: () => getJSDocProtectedTag, + getJSDocProtectedTagNoCache: () => getJSDocProtectedTagNoCache, + getJSDocPublicTag: () => getJSDocPublicTag, + getJSDocPublicTagNoCache: () => getJSDocPublicTagNoCache, + getJSDocReadonlyTag: () => getJSDocReadonlyTag, + getJSDocReadonlyTagNoCache: () => getJSDocReadonlyTagNoCache, + getJSDocReturnTag: () => getJSDocReturnTag, + getJSDocReturnType: () => getJSDocReturnType, + getJSDocRoot: () => getJSDocRoot, + getJSDocSatisfiesExpressionType: () => getJSDocSatisfiesExpressionType, + getJSDocSatisfiesTag: () => getJSDocSatisfiesTag, + getJSDocTags: () => getJSDocTags, + getJSDocTagsNoCache: () => getJSDocTagsNoCache, + getJSDocTemplateTag: () => getJSDocTemplateTag, + getJSDocThisTag: () => getJSDocThisTag, + getJSDocType: () => getJSDocType, + getJSDocTypeAliasName: () => getJSDocTypeAliasName, + getJSDocTypeAssertionType: () => getJSDocTypeAssertionType, + getJSDocTypeParameterDeclarations: () => getJSDocTypeParameterDeclarations, + getJSDocTypeParameterTags: () => getJSDocTypeParameterTags, + getJSDocTypeParameterTagsNoCache: () => getJSDocTypeParameterTagsNoCache, + getJSDocTypeTag: () => getJSDocTypeTag, + getJSXImplicitImportBase: () => getJSXImplicitImportBase, + getJSXRuntimeImport: () => getJSXRuntimeImport, + getJSXTransformEnabled: () => getJSXTransformEnabled, + getKeyForCompilerOptions: () => getKeyForCompilerOptions, + getLanguageVariant: () => getLanguageVariant, + getLastChild: () => getLastChild, + getLeadingCommentRanges: () => getLeadingCommentRanges, + getLeadingCommentRangesOfNode: () => getLeadingCommentRangesOfNode, + getLeftmostAccessExpression: () => getLeftmostAccessExpression, + getLeftmostExpression: () => getLeftmostExpression, + getLibraryNameFromLibFileName: () => getLibraryNameFromLibFileName, + getLineAndCharacterOfPosition: () => getLineAndCharacterOfPosition, + getLineInfo: () => getLineInfo, + getLineOfLocalPosition: () => getLineOfLocalPosition, + getLineOfLocalPositionFromLineMap: () => getLineOfLocalPositionFromLineMap, + getLineStartPositionForPosition: () => getLineStartPositionForPosition, + getLineStarts: () => getLineStarts, + getLinesBetweenPositionAndNextNonWhitespaceCharacter: () => getLinesBetweenPositionAndNextNonWhitespaceCharacter, + getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter: () => getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter, + getLinesBetweenPositions: () => getLinesBetweenPositions, + getLinesBetweenRangeEndAndRangeStart: () => getLinesBetweenRangeEndAndRangeStart, + getLinesBetweenRangeEndPositions: () => getLinesBetweenRangeEndPositions, + getLiteralText: () => getLiteralText, + getLocalNameForExternalImport: () => getLocalNameForExternalImport, + getLocalSymbolForExportDefault: () => getLocalSymbolForExportDefault, + getLocaleSpecificMessage: () => getLocaleSpecificMessage, + getLocaleTimeString: () => getLocaleTimeString, + getMappedContextSpan: () => getMappedContextSpan, + getMappedDocumentSpan: () => getMappedDocumentSpan, + getMappedLocation: () => getMappedLocation, + getMatchedFileSpec: () => getMatchedFileSpec, + getMatchedIncludeSpec: () => getMatchedIncludeSpec, + getMeaningFromDeclaration: () => getMeaningFromDeclaration, + getMeaningFromLocation: () => getMeaningFromLocation, + getMembersOfDeclaration: () => getMembersOfDeclaration, + getModeForFileReference: () => getModeForFileReference, + getModeForResolutionAtIndex: () => getModeForResolutionAtIndex, + getModeForUsageLocation: () => getModeForUsageLocation, + getModifiedTime: () => getModifiedTime, + getModifiers: () => getModifiers, + getModuleInstanceState: () => getModuleInstanceState, + getModuleNameStringLiteralAt: () => getModuleNameStringLiteralAt, + getModuleSpecifierEndingPreference: () => getModuleSpecifierEndingPreference, + getModuleSpecifierResolverHost: () => getModuleSpecifierResolverHost, + getNameForExportedSymbol: () => getNameForExportedSymbol, + getNameFromIndexInfo: () => getNameFromIndexInfo, + getNameFromPropertyName: () => getNameFromPropertyName, + getNameOfAccessExpression: () => getNameOfAccessExpression, + getNameOfCompilerOptionValue: () => getNameOfCompilerOptionValue, + getNameOfDeclaration: () => getNameOfDeclaration, + getNameOfExpando: () => getNameOfExpando, + getNameOfJSDocTypedef: () => getNameOfJSDocTypedef, + getNameOrArgument: () => getNameOrArgument, + getNameTable: () => getNameTable, + getNamesForExportedSymbol: () => getNamesForExportedSymbol, + getNamespaceDeclarationNode: () => getNamespaceDeclarationNode, + getNewLineCharacter: () => getNewLineCharacter, + getNewLineKind: () => getNewLineKind, + getNewLineOrDefaultFromHost: () => getNewLineOrDefaultFromHost, + getNewTargetContainer: () => getNewTargetContainer, + getNextJSDocCommentLocation: () => getNextJSDocCommentLocation, + getNodeForGeneratedName: () => getNodeForGeneratedName, + getNodeId: () => getNodeId, + getNodeKind: () => getNodeKind, + getNodeModifiers: () => getNodeModifiers, + getNodeModulePathParts: () => getNodeModulePathParts, + getNonAssignedNameOfDeclaration: () => getNonAssignedNameOfDeclaration, + getNonAssignmentOperatorForCompoundAssignment: () => getNonAssignmentOperatorForCompoundAssignment, + getNonAugmentationDeclaration: () => getNonAugmentationDeclaration, + getNonDecoratorTokenPosOfNode: () => getNonDecoratorTokenPosOfNode, + getNormalizedAbsolutePath: () => getNormalizedAbsolutePath, + getNormalizedAbsolutePathWithoutRoot: () => getNormalizedAbsolutePathWithoutRoot, + getNormalizedPathComponents: () => getNormalizedPathComponents, + getObjectFlags: () => getObjectFlags, + getOperator: () => getOperator, + getOperatorAssociativity: () => getOperatorAssociativity, + getOperatorPrecedence: () => getOperatorPrecedence, + getOptionFromName: () => getOptionFromName, + getOptionsForLibraryResolution: () => getOptionsForLibraryResolution, + getOptionsNameMap: () => getOptionsNameMap, + getOrCreateEmitNode: () => getOrCreateEmitNode, + getOrCreateExternalHelpersModuleNameIfNeeded: () => getOrCreateExternalHelpersModuleNameIfNeeded, + getOrUpdate: () => getOrUpdate, + getOriginalNode: () => getOriginalNode, + getOriginalNodeId: () => getOriginalNodeId, + getOriginalSourceFile: () => getOriginalSourceFile, + getOutputDeclarationFileName: () => getOutputDeclarationFileName, + getOutputExtension: () => getOutputExtension, + getOutputFileNames: () => getOutputFileNames, + getOutputPathsFor: () => getOutputPathsFor, + getOutputPathsForBundle: () => getOutputPathsForBundle, + getOwnEmitOutputFilePath: () => getOwnEmitOutputFilePath, + getOwnKeys: () => getOwnKeys, + getOwnValues: () => getOwnValues, + getPackageJsonInfo: () => getPackageJsonInfo, + getPackageJsonTypesVersionsPaths: () => getPackageJsonTypesVersionsPaths, + getPackageJsonsVisibleToFile: () => getPackageJsonsVisibleToFile, + getPackageNameFromTypesPackageName: () => getPackageNameFromTypesPackageName, + getPackageScopeForPath: () => getPackageScopeForPath, + getParameterSymbolFromJSDoc: () => getParameterSymbolFromJSDoc, + getParameterTypeNode: () => getParameterTypeNode, + getParentNodeInSpan: () => getParentNodeInSpan, + getParseTreeNode: () => getParseTreeNode, + getParsedCommandLineOfConfigFile: () => getParsedCommandLineOfConfigFile, + getPathComponents: () => getPathComponents, + getPathComponentsRelativeTo: () => getPathComponentsRelativeTo, + getPathFromPathComponents: () => getPathFromPathComponents, + getPathUpdater: () => getPathUpdater, + getPathsBasePath: () => getPathsBasePath, + getPatternFromSpec: () => getPatternFromSpec, + getPendingEmitKind: () => getPendingEmitKind, + getPositionOfLineAndCharacter: () => getPositionOfLineAndCharacter, + getPossibleGenericSignatures: () => getPossibleGenericSignatures, + getPossibleOriginalInputExtensionForExtension: () => getPossibleOriginalInputExtensionForExtension, + getPossibleTypeArgumentsInfo: () => getPossibleTypeArgumentsInfo, + getPreEmitDiagnostics: () => getPreEmitDiagnostics, + getPrecedingNonSpaceCharacterPosition: () => getPrecedingNonSpaceCharacterPosition, + getPrivateIdentifier: () => getPrivateIdentifier, + getProperties: () => getProperties, + getProperty: () => getProperty, + getPropertyArrayElementValue: () => getPropertyArrayElementValue, + getPropertyAssignmentAliasLikeExpression: () => getPropertyAssignmentAliasLikeExpression, + getPropertyNameForPropertyNameNode: () => getPropertyNameForPropertyNameNode, + getPropertyNameForUniqueESSymbol: () => getPropertyNameForUniqueESSymbol, + getPropertyNameFromType: () => getPropertyNameFromType, + getPropertyNameOfBindingOrAssignmentElement: () => getPropertyNameOfBindingOrAssignmentElement, + getPropertySymbolFromBindingElement: () => getPropertySymbolFromBindingElement, + getPropertySymbolsFromContextualType: () => getPropertySymbolsFromContextualType, + getQuoteFromPreference: () => getQuoteFromPreference, + getQuotePreference: () => getQuotePreference, + getRangesWhere: () => getRangesWhere, + getRefactorContextSpan: () => getRefactorContextSpan, + getReferencedFileLocation: () => getReferencedFileLocation, + getRegexFromPattern: () => getRegexFromPattern, + getRegularExpressionForWildcard: () => getRegularExpressionForWildcard, + getRegularExpressionsForWildcards: () => getRegularExpressionsForWildcards, + getRelativePathFromDirectory: () => getRelativePathFromDirectory, + getRelativePathFromFile: () => getRelativePathFromFile, + getRelativePathToDirectoryOrUrl: () => getRelativePathToDirectoryOrUrl, + getRenameLocation: () => getRenameLocation, + getReplacementSpanForContextToken: () => getReplacementSpanForContextToken, + getResolutionDiagnostic: () => getResolutionDiagnostic, + getResolutionModeOverride: () => getResolutionModeOverride, + getResolveJsonModule: () => getResolveJsonModule, + getResolvePackageJsonExports: () => getResolvePackageJsonExports, + getResolvePackageJsonImports: () => getResolvePackageJsonImports, + getResolvedExternalModuleName: () => getResolvedExternalModuleName, + getRestIndicatorOfBindingOrAssignmentElement: () => getRestIndicatorOfBindingOrAssignmentElement, + getRestParameterElementType: () => getRestParameterElementType, + getRightMostAssignedExpression: () => getRightMostAssignedExpression, + getRootDeclaration: () => getRootDeclaration, + getRootDirectoryOfResolutionCache: () => getRootDirectoryOfResolutionCache, + getRootLength: () => getRootLength, + getRootPathSplitLength: () => getRootPathSplitLength, + getScriptKind: () => getScriptKind, + getScriptKindFromFileName: () => getScriptKindFromFileName, + getScriptTargetFeatures: () => getScriptTargetFeatures, + getSelectedEffectiveModifierFlags: () => getSelectedEffectiveModifierFlags, + getSelectedSyntacticModifierFlags: () => getSelectedSyntacticModifierFlags, + getSemanticClassifications: () => getSemanticClassifications, + getSemanticJsxChildren: () => getSemanticJsxChildren, + getSetAccessorTypeAnnotationNode: () => getSetAccessorTypeAnnotationNode, + getSetAccessorValueParameter: () => getSetAccessorValueParameter, + getSetExternalModuleIndicator: () => getSetExternalModuleIndicator, + getShebang: () => getShebang, + getSingleInitializerOfVariableStatementOrPropertyDeclaration: () => getSingleInitializerOfVariableStatementOrPropertyDeclaration, + getSingleVariableOfVariableStatement: () => getSingleVariableOfVariableStatement, + getSnapshotText: () => getSnapshotText, + getSnippetElement: () => getSnippetElement, + getSourceFileOfModule: () => getSourceFileOfModule, + getSourceFileOfNode: () => getSourceFileOfNode, + getSourceFilePathInNewDir: () => getSourceFilePathInNewDir, + getSourceFilePathInNewDirWorker: () => getSourceFilePathInNewDirWorker, + getSourceFileVersionAsHashFromText: () => getSourceFileVersionAsHashFromText, + getSourceFilesToEmit: () => getSourceFilesToEmit, + getSourceMapRange: () => getSourceMapRange, + getSourceMapper: () => getSourceMapper, + getSourceTextOfNodeFromSourceFile: () => getSourceTextOfNodeFromSourceFile, + getSpanOfTokenAtPosition: () => getSpanOfTokenAtPosition, + getSpellingSuggestion: () => getSpellingSuggestion, + getStartPositionOfLine: () => getStartPositionOfLine, + getStartPositionOfRange: () => getStartPositionOfRange, + getStartsOnNewLine: () => getStartsOnNewLine, + getStaticPropertiesAndClassStaticBlock: () => getStaticPropertiesAndClassStaticBlock, + getStrictOptionValue: () => getStrictOptionValue, + getStringComparer: () => getStringComparer, + getSuperCallFromStatement: () => getSuperCallFromStatement, + getSuperContainer: () => getSuperContainer, + getSupportedCodeFixes: () => getSupportedCodeFixes, + getSupportedExtensions: () => getSupportedExtensions, + getSupportedExtensionsWithJsonIfResolveJsonModule: () => getSupportedExtensionsWithJsonIfResolveJsonModule, + getSwitchedType: () => getSwitchedType, + getSymbolId: () => getSymbolId, + getSymbolNameForPrivateIdentifier: () => getSymbolNameForPrivateIdentifier, + getSymbolTarget: () => getSymbolTarget, + getSyntacticClassifications: () => getSyntacticClassifications, + getSyntacticModifierFlags: () => getSyntacticModifierFlags, + getSyntacticModifierFlagsNoCache: () => getSyntacticModifierFlagsNoCache, + getSynthesizedDeepClone: () => getSynthesizedDeepClone, + getSynthesizedDeepCloneWithReplacements: () => getSynthesizedDeepCloneWithReplacements, + getSynthesizedDeepClones: () => getSynthesizedDeepClones, + getSynthesizedDeepClonesWithReplacements: () => getSynthesizedDeepClonesWithReplacements, + getSyntheticLeadingComments: () => getSyntheticLeadingComments, + getSyntheticTrailingComments: () => getSyntheticTrailingComments, + getTargetLabel: () => getTargetLabel, + getTargetOfBindingOrAssignmentElement: () => getTargetOfBindingOrAssignmentElement, + getTemporaryModuleResolutionState: () => getTemporaryModuleResolutionState, + getTextOfConstantValue: () => getTextOfConstantValue, + getTextOfIdentifierOrLiteral: () => getTextOfIdentifierOrLiteral, + getTextOfJSDocComment: () => getTextOfJSDocComment, + getTextOfJsxAttributeName: () => getTextOfJsxAttributeName, + getTextOfJsxNamespacedName: () => getTextOfJsxNamespacedName, + getTextOfNode: () => getTextOfNode, + getTextOfNodeFromSourceText: () => getTextOfNodeFromSourceText, + getTextOfPropertyName: () => getTextOfPropertyName, + getThisContainer: () => getThisContainer, + getThisParameter: () => getThisParameter, + getTokenAtPosition: () => getTokenAtPosition, + getTokenPosOfNode: () => getTokenPosOfNode, + getTokenSourceMapRange: () => getTokenSourceMapRange, + getTouchingPropertyName: () => getTouchingPropertyName, + getTouchingToken: () => getTouchingToken, + getTrailingCommentRanges: () => getTrailingCommentRanges, + getTrailingSemicolonDeferringWriter: () => getTrailingSemicolonDeferringWriter, + getTransformFlagsSubtreeExclusions: () => getTransformFlagsSubtreeExclusions, + getTransformers: () => getTransformers, + getTsBuildInfoEmitOutputFilePath: () => getTsBuildInfoEmitOutputFilePath, + getTsConfigObjectLiteralExpression: () => getTsConfigObjectLiteralExpression, + getTsConfigPropArrayElementValue: () => getTsConfigPropArrayElementValue, + getTypeAnnotationNode: () => getTypeAnnotationNode, + getTypeArgumentOrTypeParameterList: () => getTypeArgumentOrTypeParameterList, + getTypeKeywordOfTypeOnlyImport: () => getTypeKeywordOfTypeOnlyImport, + getTypeNode: () => getTypeNode, + getTypeNodeIfAccessible: () => getTypeNodeIfAccessible, + getTypeParameterFromJsDoc: () => getTypeParameterFromJsDoc, + getTypeParameterOwner: () => getTypeParameterOwner, + getTypesPackageName: () => getTypesPackageName, + getUILocale: () => getUILocale, + getUniqueName: () => getUniqueName, + getUniqueSymbolId: () => getUniqueSymbolId, + getUseDefineForClassFields: () => getUseDefineForClassFields, + getWatchErrorSummaryDiagnosticMessage: () => getWatchErrorSummaryDiagnosticMessage, + getWatchFactory: () => getWatchFactory, + group: () => group, + groupBy: () => groupBy, + guessIndentation: () => guessIndentation, + handleNoEmitOptions: () => handleNoEmitOptions, + hasAbstractModifier: () => hasAbstractModifier, + hasAccessorModifier: () => hasAccessorModifier, + hasAmbientModifier: () => hasAmbientModifier, + hasChangesInResolutions: () => hasChangesInResolutions, + hasChildOfKind: () => hasChildOfKind, + hasContextSensitiveParameters: () => hasContextSensitiveParameters, + hasDecorators: () => hasDecorators, + hasDocComment: () => hasDocComment, + hasDynamicName: () => hasDynamicName, + hasEffectiveModifier: () => hasEffectiveModifier, + hasEffectiveModifiers: () => hasEffectiveModifiers, + hasEffectiveReadonlyModifier: () => hasEffectiveReadonlyModifier, + hasExtension: () => hasExtension, + hasIndexSignature: () => hasIndexSignature, + hasInitializer: () => hasInitializer, + hasInvalidEscape: () => hasInvalidEscape, + hasJSDocNodes: () => hasJSDocNodes, + hasJSDocParameterTags: () => hasJSDocParameterTags, + hasJSFileExtension: () => hasJSFileExtension, + hasJsonModuleEmitEnabled: () => hasJsonModuleEmitEnabled, + hasOnlyExpressionInitializer: () => hasOnlyExpressionInitializer, + hasOverrideModifier: () => hasOverrideModifier, + hasPossibleExternalModuleReference: () => hasPossibleExternalModuleReference, + hasProperty: () => hasProperty, + hasPropertyAccessExpressionWithName: () => hasPropertyAccessExpressionWithName, + hasQuestionToken: () => hasQuestionToken, + hasRecordedExternalHelpers: () => hasRecordedExternalHelpers, + hasResolutionModeOverride: () => hasResolutionModeOverride, + hasRestParameter: () => hasRestParameter, + hasScopeMarker: () => hasScopeMarker, + hasStaticModifier: () => hasStaticModifier, + hasSyntacticModifier: () => hasSyntacticModifier, + hasSyntacticModifiers: () => hasSyntacticModifiers, + hasTSFileExtension: () => hasTSFileExtension, + hasTabstop: () => hasTabstop, + hasTrailingDirectorySeparator: () => hasTrailingDirectorySeparator, + hasType: () => hasType, + hasTypeArguments: () => hasTypeArguments, + hasZeroOrOneAsteriskCharacter: () => hasZeroOrOneAsteriskCharacter, + helperString: () => helperString, + hostGetCanonicalFileName: () => hostGetCanonicalFileName, + hostUsesCaseSensitiveFileNames: () => hostUsesCaseSensitiveFileNames, + idText: () => idText, + identifierIsThisKeyword: () => identifierIsThisKeyword, + identifierToKeywordKind: () => identifierToKeywordKind, + identity: () => identity, + identitySourceMapConsumer: () => identitySourceMapConsumer, + ignoreSourceNewlines: () => ignoreSourceNewlines, + ignoredPaths: () => ignoredPaths, + importDefaultHelper: () => importDefaultHelper, + importFromModuleSpecifier: () => importFromModuleSpecifier, + importNameElisionDisabled: () => importNameElisionDisabled, + importStarHelper: () => importStarHelper, + indexOfAnyCharCode: () => indexOfAnyCharCode, + indexOfNode: () => indexOfNode, + indicesOf: () => indicesOf, + inferredTypesContainingFile: () => inferredTypesContainingFile, + injectClassNamedEvaluationHelperBlockIfMissing: () => injectClassNamedEvaluationHelperBlockIfMissing, + injectClassThisAssignmentIfMissing: () => injectClassThisAssignmentIfMissing, + insertImports: () => insertImports, + insertLeadingStatement: () => insertLeadingStatement, + insertSorted: () => insertSorted, + insertStatementAfterCustomPrologue: () => insertStatementAfterCustomPrologue, + insertStatementAfterStandardPrologue: () => insertStatementAfterStandardPrologue, + insertStatementsAfterCustomPrologue: () => insertStatementsAfterCustomPrologue, + insertStatementsAfterStandardPrologue: () => insertStatementsAfterStandardPrologue, + intersperse: () => intersperse, + intrinsicTagNameToString: () => intrinsicTagNameToString, + introducesArgumentsExoticObject: () => introducesArgumentsExoticObject, + inverseJsxOptionMap: () => inverseJsxOptionMap, + isAbstractConstructorSymbol: () => isAbstractConstructorSymbol, + isAbstractModifier: () => isAbstractModifier, + isAccessExpression: () => isAccessExpression, + isAccessibilityModifier: () => isAccessibilityModifier, + isAccessor: () => isAccessor, + isAccessorModifier: () => isAccessorModifier, + isAliasSymbolDeclaration: () => isAliasSymbolDeclaration, + isAliasableExpression: () => isAliasableExpression, + isAmbientModule: () => isAmbientModule, + isAmbientPropertyDeclaration: () => isAmbientPropertyDeclaration, + isAnonymousFunctionDefinition: () => isAnonymousFunctionDefinition, + isAnyDirectorySeparator: () => isAnyDirectorySeparator, + isAnyImportOrBareOrAccessedRequire: () => isAnyImportOrBareOrAccessedRequire, + isAnyImportOrReExport: () => isAnyImportOrReExport, + isAnyImportSyntax: () => isAnyImportSyntax, + isAnySupportedFileExtension: () => isAnySupportedFileExtension, + isApplicableVersionedTypesKey: () => isApplicableVersionedTypesKey, + isArgumentExpressionOfElementAccess: () => isArgumentExpressionOfElementAccess, + isArray: () => isArray, + isArrayBindingElement: () => isArrayBindingElement, + isArrayBindingOrAssignmentElement: () => isArrayBindingOrAssignmentElement, + isArrayBindingOrAssignmentPattern: () => isArrayBindingOrAssignmentPattern, + isArrayBindingPattern: () => isArrayBindingPattern, + isArrayLiteralExpression: () => isArrayLiteralExpression, + isArrayLiteralOrObjectLiteralDestructuringPattern: () => isArrayLiteralOrObjectLiteralDestructuringPattern, + isArrayTypeNode: () => isArrayTypeNode, + isArrowFunction: () => isArrowFunction, + isAsExpression: () => isAsExpression, + isAssertClause: () => isAssertClause, + isAssertEntry: () => isAssertEntry, + isAssertionExpression: () => isAssertionExpression, + isAssertsKeyword: () => isAssertsKeyword, + isAssignmentDeclaration: () => isAssignmentDeclaration, + isAssignmentExpression: () => isAssignmentExpression, + isAssignmentOperator: () => isAssignmentOperator, + isAssignmentPattern: () => isAssignmentPattern, + isAssignmentTarget: () => isAssignmentTarget, + isAsteriskToken: () => isAsteriskToken, + isAsyncFunction: () => isAsyncFunction, + isAsyncModifier: () => isAsyncModifier, + isAutoAccessorPropertyDeclaration: () => isAutoAccessorPropertyDeclaration, + isAwaitExpression: () => isAwaitExpression, + isAwaitKeyword: () => isAwaitKeyword, + isBigIntLiteral: () => isBigIntLiteral, + isBinaryExpression: () => isBinaryExpression, + isBinaryOperatorToken: () => isBinaryOperatorToken, + isBindableObjectDefinePropertyCall: () => isBindableObjectDefinePropertyCall, + isBindableStaticAccessExpression: () => isBindableStaticAccessExpression, + isBindableStaticElementAccessExpression: () => isBindableStaticElementAccessExpression, + isBindableStaticNameExpression: () => isBindableStaticNameExpression, + isBindingElement: () => isBindingElement, + isBindingElementOfBareOrAccessedRequire: () => isBindingElementOfBareOrAccessedRequire, + isBindingName: () => isBindingName, + isBindingOrAssignmentElement: () => isBindingOrAssignmentElement, + isBindingOrAssignmentPattern: () => isBindingOrAssignmentPattern, + isBindingPattern: () => isBindingPattern, + isBlock: () => isBlock, + isBlockOrCatchScoped: () => isBlockOrCatchScoped, + isBlockScope: () => isBlockScope, + isBlockScopedContainerTopLevel: () => isBlockScopedContainerTopLevel, + isBooleanLiteral: () => isBooleanLiteral, + isBreakOrContinueStatement: () => isBreakOrContinueStatement, + isBreakStatement: () => isBreakStatement, + isBuildInfoFile: () => isBuildInfoFile, + isBuilderProgram: () => isBuilderProgram2, + isBundle: () => isBundle, + isBundleFileTextLike: () => isBundleFileTextLike, + isCallChain: () => isCallChain, + isCallExpression: () => isCallExpression, + isCallExpressionTarget: () => isCallExpressionTarget, + isCallLikeExpression: () => isCallLikeExpression, + isCallLikeOrFunctionLikeExpression: () => isCallLikeOrFunctionLikeExpression, + isCallOrNewExpression: () => isCallOrNewExpression, + isCallOrNewExpressionTarget: () => isCallOrNewExpressionTarget, + isCallSignatureDeclaration: () => isCallSignatureDeclaration, + isCallToHelper: () => isCallToHelper, + isCaseBlock: () => isCaseBlock, + isCaseClause: () => isCaseClause, + isCaseKeyword: () => isCaseKeyword, + isCaseOrDefaultClause: () => isCaseOrDefaultClause, + isCatchClause: () => isCatchClause, + isCatchClauseVariableDeclaration: () => isCatchClauseVariableDeclaration, + isCatchClauseVariableDeclarationOrBindingElement: () => isCatchClauseVariableDeclarationOrBindingElement, + isCheckJsEnabledForFile: () => isCheckJsEnabledForFile, + isChildOfNodeWithKind: () => isChildOfNodeWithKind, + isCircularBuildOrder: () => isCircularBuildOrder, + isClassDeclaration: () => isClassDeclaration, + isClassElement: () => isClassElement, + isClassExpression: () => isClassExpression, + isClassInstanceProperty: () => isClassInstanceProperty, + isClassLike: () => isClassLike, + isClassMemberModifier: () => isClassMemberModifier, + isClassNamedEvaluationHelperBlock: () => isClassNamedEvaluationHelperBlock, + isClassOrTypeElement: () => isClassOrTypeElement, + isClassStaticBlockDeclaration: () => isClassStaticBlockDeclaration, + isClassThisAssignmentBlock: () => isClassThisAssignmentBlock, + isCollapsedRange: () => isCollapsedRange, + isColonToken: () => isColonToken, + isCommaExpression: () => isCommaExpression, + isCommaListExpression: () => isCommaListExpression, + isCommaSequence: () => isCommaSequence, + isCommaToken: () => isCommaToken, + isComment: () => isComment, + isCommonJsExportPropertyAssignment: () => isCommonJsExportPropertyAssignment, + isCommonJsExportedExpression: () => isCommonJsExportedExpression, + isCompoundAssignment: () => isCompoundAssignment, + isComputedNonLiteralName: () => isComputedNonLiteralName, + isComputedPropertyName: () => isComputedPropertyName, + isConciseBody: () => isConciseBody, + isConditionalExpression: () => isConditionalExpression, + isConditionalTypeNode: () => isConditionalTypeNode, + isConstTypeReference: () => isConstTypeReference, + isConstructSignatureDeclaration: () => isConstructSignatureDeclaration, + isConstructorDeclaration: () => isConstructorDeclaration, + isConstructorTypeNode: () => isConstructorTypeNode, + isContextualKeyword: () => isContextualKeyword, + isContinueStatement: () => isContinueStatement, + isCustomPrologue: () => isCustomPrologue, + isDebuggerStatement: () => isDebuggerStatement, + isDeclaration: () => isDeclaration, + isDeclarationBindingElement: () => isDeclarationBindingElement, + isDeclarationFileName: () => isDeclarationFileName, + isDeclarationName: () => isDeclarationName, + isDeclarationNameOfEnumOrNamespace: () => isDeclarationNameOfEnumOrNamespace, + isDeclarationReadonly: () => isDeclarationReadonly, + isDeclarationStatement: () => isDeclarationStatement, + isDeclarationWithTypeParameterChildren: () => isDeclarationWithTypeParameterChildren, + isDeclarationWithTypeParameters: () => isDeclarationWithTypeParameters, + isDecorator: () => isDecorator, + isDecoratorTarget: () => isDecoratorTarget, + isDefaultClause: () => isDefaultClause, + isDefaultImport: () => isDefaultImport, + isDefaultModifier: () => isDefaultModifier, + isDefaultedExpandoInitializer: () => isDefaultedExpandoInitializer, + isDeleteExpression: () => isDeleteExpression, + isDeleteTarget: () => isDeleteTarget, + isDeprecatedDeclaration: () => isDeprecatedDeclaration, + isDestructuringAssignment: () => isDestructuringAssignment, + isDiagnosticWithLocation: () => isDiagnosticWithLocation, + isDiskPathRoot: () => isDiskPathRoot, + isDoStatement: () => isDoStatement, + isDocumentRegistryEntry: () => isDocumentRegistryEntry, + isDotDotDotToken: () => isDotDotDotToken, + isDottedName: () => isDottedName, + isDynamicName: () => isDynamicName, + isESSymbolIdentifier: () => isESSymbolIdentifier, + isEffectiveExternalModule: () => isEffectiveExternalModule, + isEffectiveModuleDeclaration: () => isEffectiveModuleDeclaration, + isEffectiveStrictModeSourceFile: () => isEffectiveStrictModeSourceFile, + isElementAccessChain: () => isElementAccessChain, + isElementAccessExpression: () => isElementAccessExpression, + isEmittedFileOfProgram: () => isEmittedFileOfProgram, + isEmptyArrayLiteral: () => isEmptyArrayLiteral, + isEmptyBindingElement: () => isEmptyBindingElement, + isEmptyBindingPattern: () => isEmptyBindingPattern, + isEmptyObjectLiteral: () => isEmptyObjectLiteral, + isEmptyStatement: () => isEmptyStatement, + isEmptyStringLiteral: () => isEmptyStringLiteral, + isEntityName: () => isEntityName, + isEntityNameExpression: () => isEntityNameExpression, + isEnumConst: () => isEnumConst, + isEnumDeclaration: () => isEnumDeclaration, + isEnumMember: () => isEnumMember, + isEqualityOperatorKind: () => isEqualityOperatorKind, + isEqualsGreaterThanToken: () => isEqualsGreaterThanToken, + isExclamationToken: () => isExclamationToken, + isExcludedFile: () => isExcludedFile, + isExclusivelyTypeOnlyImportOrExport: () => isExclusivelyTypeOnlyImportOrExport, + isExpandoPropertyDeclaration: () => isExpandoPropertyDeclaration, + isExportAssignment: () => isExportAssignment, + isExportDeclaration: () => isExportDeclaration, + isExportModifier: () => isExportModifier, + isExportName: () => isExportName, + isExportNamespaceAsDefaultDeclaration: () => isExportNamespaceAsDefaultDeclaration, + isExportOrDefaultModifier: () => isExportOrDefaultModifier, + isExportSpecifier: () => isExportSpecifier, + isExportsIdentifier: () => isExportsIdentifier, + isExportsOrModuleExportsOrAlias: () => isExportsOrModuleExportsOrAlias, + isExpression: () => isExpression, + isExpressionNode: () => isExpressionNode, + isExpressionOfExternalModuleImportEqualsDeclaration: () => isExpressionOfExternalModuleImportEqualsDeclaration, + isExpressionOfOptionalChainRoot: () => isExpressionOfOptionalChainRoot, + isExpressionStatement: () => isExpressionStatement, + isExpressionWithTypeArguments: () => isExpressionWithTypeArguments, + isExpressionWithTypeArgumentsInClassExtendsClause: () => isExpressionWithTypeArgumentsInClassExtendsClause, + isExternalModule: () => isExternalModule, + isExternalModuleAugmentation: () => isExternalModuleAugmentation, + isExternalModuleImportEqualsDeclaration: () => isExternalModuleImportEqualsDeclaration, + isExternalModuleIndicator: () => isExternalModuleIndicator, + isExternalModuleNameRelative: () => isExternalModuleNameRelative, + isExternalModuleReference: () => isExternalModuleReference, + isExternalModuleSymbol: () => isExternalModuleSymbol, + isExternalOrCommonJsModule: () => isExternalOrCommonJsModule, + isFileLevelReservedGeneratedIdentifier: () => isFileLevelReservedGeneratedIdentifier, + isFileLevelUniqueName: () => isFileLevelUniqueName, + isFileProbablyExternalModule: () => isFileProbablyExternalModule, + isFirstDeclarationOfSymbolParameter: () => isFirstDeclarationOfSymbolParameter, + isFixablePromiseHandler: () => isFixablePromiseHandler, + isForInOrOfStatement: () => isForInOrOfStatement, + isForInStatement: () => isForInStatement, + isForInitializer: () => isForInitializer, + isForOfStatement: () => isForOfStatement, + isForStatement: () => isForStatement, + isFunctionBlock: () => isFunctionBlock, + isFunctionBody: () => isFunctionBody, + isFunctionDeclaration: () => isFunctionDeclaration, + isFunctionExpression: () => isFunctionExpression, + isFunctionExpressionOrArrowFunction: () => isFunctionExpressionOrArrowFunction, + isFunctionLike: () => isFunctionLike, + isFunctionLikeDeclaration: () => isFunctionLikeDeclaration, + isFunctionLikeKind: () => isFunctionLikeKind, + isFunctionLikeOrClassStaticBlockDeclaration: () => isFunctionLikeOrClassStaticBlockDeclaration, + isFunctionOrConstructorTypeNode: () => isFunctionOrConstructorTypeNode, + isFunctionOrModuleBlock: () => isFunctionOrModuleBlock, + isFunctionSymbol: () => isFunctionSymbol, + isFunctionTypeNode: () => isFunctionTypeNode, + isFutureReservedKeyword: () => isFutureReservedKeyword, + isGeneratedIdentifier: () => isGeneratedIdentifier, + isGeneratedPrivateIdentifier: () => isGeneratedPrivateIdentifier, + isGetAccessor: () => isGetAccessor, + isGetAccessorDeclaration: () => isGetAccessorDeclaration, + isGetOrSetAccessorDeclaration: () => isGetOrSetAccessorDeclaration, + isGlobalDeclaration: () => isGlobalDeclaration, + isGlobalScopeAugmentation: () => isGlobalScopeAugmentation, + isGrammarError: () => isGrammarError, + isHeritageClause: () => isHeritageClause, + isHoistedFunction: () => isHoistedFunction, + isHoistedVariableStatement: () => isHoistedVariableStatement, + isIdentifier: () => isIdentifier, + isIdentifierANonContextualKeyword: () => isIdentifierANonContextualKeyword, + isIdentifierName: () => isIdentifierName, + isIdentifierOrThisTypeNode: () => isIdentifierOrThisTypeNode, + isIdentifierPart: () => isIdentifierPart, + isIdentifierStart: () => isIdentifierStart, + isIdentifierText: () => isIdentifierText, + isIdentifierTypePredicate: () => isIdentifierTypePredicate, + isIdentifierTypeReference: () => isIdentifierTypeReference, + isIfStatement: () => isIfStatement, + isIgnoredFileFromWildCardWatching: () => isIgnoredFileFromWildCardWatching, + isImplicitGlob: () => isImplicitGlob, + isImportAttribute: () => isImportAttribute, + isImportAttributeName: () => isImportAttributeName, + isImportAttributes: () => isImportAttributes, + isImportCall: () => isImportCall, + isImportClause: () => isImportClause, + isImportDeclaration: () => isImportDeclaration, + isImportEqualsDeclaration: () => isImportEqualsDeclaration, + isImportKeyword: () => isImportKeyword, + isImportMeta: () => isImportMeta, + isImportOrExportSpecifier: () => isImportOrExportSpecifier, + isImportOrExportSpecifierName: () => isImportOrExportSpecifierName, + isImportSpecifier: () => isImportSpecifier, + isImportTypeAssertionContainer: () => isImportTypeAssertionContainer, + isImportTypeNode: () => isImportTypeNode, + isImportableFile: () => isImportableFile, + isInComment: () => isInComment, + isInCompoundLikeAssignment: () => isInCompoundLikeAssignment, + isInExpressionContext: () => isInExpressionContext, + isInJSDoc: () => isInJSDoc, + isInJSFile: () => isInJSFile, + isInJSXText: () => isInJSXText, + isInJsonFile: () => isInJsonFile, + isInNonReferenceComment: () => isInNonReferenceComment, + isInReferenceComment: () => isInReferenceComment, + isInRightSideOfInternalImportEqualsDeclaration: () => isInRightSideOfInternalImportEqualsDeclaration, + isInString: () => isInString, + isInTemplateString: () => isInTemplateString, + isInTopLevelContext: () => isInTopLevelContext, + isInTypeQuery: () => isInTypeQuery, + isIncrementalCompilation: () => isIncrementalCompilation, + isIndexSignatureDeclaration: () => isIndexSignatureDeclaration, + isIndexedAccessTypeNode: () => isIndexedAccessTypeNode, + isInferTypeNode: () => isInferTypeNode, + isInfinityOrNaNString: () => isInfinityOrNaNString, + isInitializedProperty: () => isInitializedProperty, + isInitializedVariable: () => isInitializedVariable, + isInsideJsxElement: () => isInsideJsxElement, + isInsideJsxElementOrAttribute: () => isInsideJsxElementOrAttribute, + isInsideNodeModules: () => isInsideNodeModules, + isInsideTemplateLiteral: () => isInsideTemplateLiteral, + isInstanceOfExpression: () => isInstanceOfExpression, + isInstantiatedModule: () => isInstantiatedModule, + isInterfaceDeclaration: () => isInterfaceDeclaration, + isInternalDeclaration: () => isInternalDeclaration, + isInternalModuleImportEqualsDeclaration: () => isInternalModuleImportEqualsDeclaration, + isInternalName: () => isInternalName, + isIntersectionTypeNode: () => isIntersectionTypeNode, + isIntrinsicJsxName: () => isIntrinsicJsxName, + isIterationStatement: () => isIterationStatement, + isJSDoc: () => isJSDoc, + isJSDocAllType: () => isJSDocAllType, + isJSDocAugmentsTag: () => isJSDocAugmentsTag, + isJSDocAuthorTag: () => isJSDocAuthorTag, + isJSDocCallbackTag: () => isJSDocCallbackTag, + isJSDocClassTag: () => isJSDocClassTag, + isJSDocCommentContainingNode: () => isJSDocCommentContainingNode, + isJSDocConstructSignature: () => isJSDocConstructSignature, + isJSDocDeprecatedTag: () => isJSDocDeprecatedTag, + isJSDocEnumTag: () => isJSDocEnumTag, + isJSDocFunctionType: () => isJSDocFunctionType, + isJSDocImplementsTag: () => isJSDocImplementsTag, + isJSDocIndexSignature: () => isJSDocIndexSignature, + isJSDocLikeText: () => isJSDocLikeText, + isJSDocLink: () => isJSDocLink, + isJSDocLinkCode: () => isJSDocLinkCode, + isJSDocLinkLike: () => isJSDocLinkLike, + isJSDocLinkPlain: () => isJSDocLinkPlain, + isJSDocMemberName: () => isJSDocMemberName, + isJSDocNameReference: () => isJSDocNameReference, + isJSDocNamepathType: () => isJSDocNamepathType, + isJSDocNamespaceBody: () => isJSDocNamespaceBody, + isJSDocNode: () => isJSDocNode, + isJSDocNonNullableType: () => isJSDocNonNullableType, + isJSDocNullableType: () => isJSDocNullableType, + isJSDocOptionalParameter: () => isJSDocOptionalParameter, + isJSDocOptionalType: () => isJSDocOptionalType, + isJSDocOverloadTag: () => isJSDocOverloadTag, + isJSDocOverrideTag: () => isJSDocOverrideTag, + isJSDocParameterTag: () => isJSDocParameterTag, + isJSDocPrivateTag: () => isJSDocPrivateTag, + isJSDocPropertyLikeTag: () => isJSDocPropertyLikeTag, + isJSDocPropertyTag: () => isJSDocPropertyTag, + isJSDocProtectedTag: () => isJSDocProtectedTag, + isJSDocPublicTag: () => isJSDocPublicTag, + isJSDocReadonlyTag: () => isJSDocReadonlyTag, + isJSDocReturnTag: () => isJSDocReturnTag, + isJSDocSatisfiesExpression: () => isJSDocSatisfiesExpression, + isJSDocSatisfiesTag: () => isJSDocSatisfiesTag, + isJSDocSeeTag: () => isJSDocSeeTag, + isJSDocSignature: () => isJSDocSignature, + isJSDocTag: () => isJSDocTag, + isJSDocTemplateTag: () => isJSDocTemplateTag, + isJSDocThisTag: () => isJSDocThisTag, + isJSDocThrowsTag: () => isJSDocThrowsTag, + isJSDocTypeAlias: () => isJSDocTypeAlias, + isJSDocTypeAssertion: () => isJSDocTypeAssertion, + isJSDocTypeExpression: () => isJSDocTypeExpression, + isJSDocTypeLiteral: () => isJSDocTypeLiteral, + isJSDocTypeTag: () => isJSDocTypeTag, + isJSDocTypedefTag: () => isJSDocTypedefTag, + isJSDocUnknownTag: () => isJSDocUnknownTag, + isJSDocUnknownType: () => isJSDocUnknownType, + isJSDocVariadicType: () => isJSDocVariadicType, + isJSXTagName: () => isJSXTagName, + isJsonEqual: () => isJsonEqual, + isJsonSourceFile: () => isJsonSourceFile, + isJsxAttribute: () => isJsxAttribute, + isJsxAttributeLike: () => isJsxAttributeLike, + isJsxAttributeName: () => isJsxAttributeName, + isJsxAttributes: () => isJsxAttributes, + isJsxChild: () => isJsxChild, + isJsxClosingElement: () => isJsxClosingElement, + isJsxClosingFragment: () => isJsxClosingFragment, + isJsxElement: () => isJsxElement, + isJsxExpression: () => isJsxExpression, + isJsxFragment: () => isJsxFragment, + isJsxNamespacedName: () => isJsxNamespacedName, + isJsxOpeningElement: () => isJsxOpeningElement, + isJsxOpeningFragment: () => isJsxOpeningFragment, + isJsxOpeningLikeElement: () => isJsxOpeningLikeElement, + isJsxOpeningLikeElementTagName: () => isJsxOpeningLikeElementTagName, + isJsxSelfClosingElement: () => isJsxSelfClosingElement, + isJsxSpreadAttribute: () => isJsxSpreadAttribute, + isJsxTagNameExpression: () => isJsxTagNameExpression, + isJsxText: () => isJsxText, + isJumpStatementTarget: () => isJumpStatementTarget, + isKeyword: () => isKeyword, + isKeywordOrPunctuation: () => isKeywordOrPunctuation, + isKnownSymbol: () => isKnownSymbol, + isLabelName: () => isLabelName, + isLabelOfLabeledStatement: () => isLabelOfLabeledStatement, + isLabeledStatement: () => isLabeledStatement, + isLateVisibilityPaintedStatement: () => isLateVisibilityPaintedStatement, + isLeftHandSideExpression: () => isLeftHandSideExpression, + isLeftHandSideOfAssignment: () => isLeftHandSideOfAssignment, + isLet: () => isLet, + isLineBreak: () => isLineBreak, + isLiteralComputedPropertyDeclarationName: () => isLiteralComputedPropertyDeclarationName, + isLiteralExpression: () => isLiteralExpression, + isLiteralExpressionOfObject: () => isLiteralExpressionOfObject, + isLiteralImportTypeNode: () => isLiteralImportTypeNode, + isLiteralKind: () => isLiteralKind, + isLiteralLikeAccess: () => isLiteralLikeAccess, + isLiteralLikeElementAccess: () => isLiteralLikeElementAccess, + isLiteralNameOfPropertyDeclarationOrIndexAccess: () => isLiteralNameOfPropertyDeclarationOrIndexAccess, + isLiteralTypeLikeExpression: () => isLiteralTypeLikeExpression, + isLiteralTypeLiteral: () => isLiteralTypeLiteral, + isLiteralTypeNode: () => isLiteralTypeNode, + isLocalName: () => isLocalName, + isLogicalOperator: () => isLogicalOperator, + isLogicalOrCoalescingAssignmentExpression: () => isLogicalOrCoalescingAssignmentExpression, + isLogicalOrCoalescingAssignmentOperator: () => isLogicalOrCoalescingAssignmentOperator, + isLogicalOrCoalescingBinaryExpression: () => isLogicalOrCoalescingBinaryExpression, + isLogicalOrCoalescingBinaryOperator: () => isLogicalOrCoalescingBinaryOperator, + isMappedTypeNode: () => isMappedTypeNode, + isMemberName: () => isMemberName, + isMetaProperty: () => isMetaProperty, + isMethodDeclaration: () => isMethodDeclaration, + isMethodOrAccessor: () => isMethodOrAccessor, + isMethodSignature: () => isMethodSignature, + isMinusToken: () => isMinusToken, + isMissingDeclaration: () => isMissingDeclaration, + isModifier: () => isModifier, + isModifierKind: () => isModifierKind, + isModifierLike: () => isModifierLike, + isModuleAugmentationExternal: () => isModuleAugmentationExternal, + isModuleBlock: () => isModuleBlock, + isModuleBody: () => isModuleBody, + isModuleDeclaration: () => isModuleDeclaration, + isModuleExportsAccessExpression: () => isModuleExportsAccessExpression, + isModuleIdentifier: () => isModuleIdentifier, + isModuleName: () => isModuleName, + isModuleOrEnumDeclaration: () => isModuleOrEnumDeclaration, + isModuleReference: () => isModuleReference, + isModuleSpecifierLike: () => isModuleSpecifierLike, + isModuleWithStringLiteralName: () => isModuleWithStringLiteralName, + isNameOfFunctionDeclaration: () => isNameOfFunctionDeclaration, + isNameOfModuleDeclaration: () => isNameOfModuleDeclaration, + isNamedClassElement: () => isNamedClassElement, + isNamedDeclaration: () => isNamedDeclaration, + isNamedEvaluation: () => isNamedEvaluation, + isNamedEvaluationSource: () => isNamedEvaluationSource, + isNamedExportBindings: () => isNamedExportBindings, + isNamedExports: () => isNamedExports, + isNamedImportBindings: () => isNamedImportBindings, + isNamedImports: () => isNamedImports, + isNamedImportsOrExports: () => isNamedImportsOrExports, + isNamedTupleMember: () => isNamedTupleMember, + isNamespaceBody: () => isNamespaceBody, + isNamespaceExport: () => isNamespaceExport, + isNamespaceExportDeclaration: () => isNamespaceExportDeclaration, + isNamespaceImport: () => isNamespaceImport, + isNamespaceReexportDeclaration: () => isNamespaceReexportDeclaration, + isNewExpression: () => isNewExpression, + isNewExpressionTarget: () => isNewExpressionTarget, + isNoSubstitutionTemplateLiteral: () => isNoSubstitutionTemplateLiteral, + isNode: () => isNode, + isNodeArray: () => isNodeArray, + isNodeArrayMultiLine: () => isNodeArrayMultiLine, + isNodeDescendantOf: () => isNodeDescendantOf, + isNodeKind: () => isNodeKind, + isNodeLikeSystem: () => isNodeLikeSystem, + isNodeModulesDirectory: () => isNodeModulesDirectory, + isNodeWithPossibleHoistedDeclaration: () => isNodeWithPossibleHoistedDeclaration, + isNonContextualKeyword: () => isNonContextualKeyword, + isNonExportDefaultModifier: () => isNonExportDefaultModifier, + isNonGlobalAmbientModule: () => isNonGlobalAmbientModule, + isNonGlobalDeclaration: () => isNonGlobalDeclaration, + isNonNullAccess: () => isNonNullAccess, + isNonNullChain: () => isNonNullChain, + isNonNullExpression: () => isNonNullExpression, + isNonStaticMethodOrAccessorWithPrivateName: () => isNonStaticMethodOrAccessorWithPrivateName, + isNotEmittedOrPartiallyEmittedNode: () => isNotEmittedOrPartiallyEmittedNode, + isNotEmittedStatement: () => isNotEmittedStatement, + isNullishCoalesce: () => isNullishCoalesce, + isNumber: () => isNumber, + isNumericLiteral: () => isNumericLiteral, + isNumericLiteralName: () => isNumericLiteralName, + isObjectBindingElementWithoutPropertyName: () => isObjectBindingElementWithoutPropertyName, + isObjectBindingOrAssignmentElement: () => isObjectBindingOrAssignmentElement, + isObjectBindingOrAssignmentPattern: () => isObjectBindingOrAssignmentPattern, + isObjectBindingPattern: () => isObjectBindingPattern, + isObjectLiteralElement: () => isObjectLiteralElement, + isObjectLiteralElementLike: () => isObjectLiteralElementLike, + isObjectLiteralExpression: () => isObjectLiteralExpression, + isObjectLiteralMethod: () => isObjectLiteralMethod, + isObjectLiteralOrClassExpressionMethodOrAccessor: () => isObjectLiteralOrClassExpressionMethodOrAccessor, + isObjectTypeDeclaration: () => isObjectTypeDeclaration, + isOctalDigit: () => isOctalDigit, + isOmittedExpression: () => isOmittedExpression, + isOptionalChain: () => isOptionalChain, + isOptionalChainRoot: () => isOptionalChainRoot, + isOptionalDeclaration: () => isOptionalDeclaration, + isOptionalJSDocPropertyLikeTag: () => isOptionalJSDocPropertyLikeTag, + isOptionalTypeNode: () => isOptionalTypeNode, + isOuterExpression: () => isOuterExpression, + isOutermostOptionalChain: () => isOutermostOptionalChain, + isOverrideModifier: () => isOverrideModifier, + isPackedArrayLiteral: () => isPackedArrayLiteral, + isParameter: () => isParameter, + isParameterDeclaration: () => isParameterDeclaration, + isParameterOrCatchClauseVariable: () => isParameterOrCatchClauseVariable, + isParameterPropertyDeclaration: () => isParameterPropertyDeclaration, + isParameterPropertyModifier: () => isParameterPropertyModifier, + isParenthesizedExpression: () => isParenthesizedExpression, + isParenthesizedTypeNode: () => isParenthesizedTypeNode, + isParseTreeNode: () => isParseTreeNode, + isPartOfTypeNode: () => isPartOfTypeNode, + isPartOfTypeQuery: () => isPartOfTypeQuery, + isPartiallyEmittedExpression: () => isPartiallyEmittedExpression, + isPatternMatch: () => isPatternMatch, + isPinnedComment: () => isPinnedComment, + isPlainJsFile: () => isPlainJsFile, + isPlusToken: () => isPlusToken, + isPossiblyTypeArgumentPosition: () => isPossiblyTypeArgumentPosition, + isPostfixUnaryExpression: () => isPostfixUnaryExpression, + isPrefixUnaryExpression: () => isPrefixUnaryExpression, + isPrivateIdentifier: () => isPrivateIdentifier, + isPrivateIdentifierClassElementDeclaration: () => isPrivateIdentifierClassElementDeclaration, + isPrivateIdentifierPropertyAccessExpression: () => isPrivateIdentifierPropertyAccessExpression, + isPrivateIdentifierSymbol: () => isPrivateIdentifierSymbol, + isProgramBundleEmitBuildInfo: () => isProgramBundleEmitBuildInfo, + isProgramUptoDate: () => isProgramUptoDate, + isPrologueDirective: () => isPrologueDirective, + isPropertyAccessChain: () => isPropertyAccessChain, + isPropertyAccessEntityNameExpression: () => isPropertyAccessEntityNameExpression, + isPropertyAccessExpression: () => isPropertyAccessExpression, + isPropertyAccessOrQualifiedName: () => isPropertyAccessOrQualifiedName, + isPropertyAccessOrQualifiedNameOrImportTypeNode: () => isPropertyAccessOrQualifiedNameOrImportTypeNode, + isPropertyAssignment: () => isPropertyAssignment, + isPropertyDeclaration: () => isPropertyDeclaration, + isPropertyName: () => isPropertyName, + isPropertyNameLiteral: () => isPropertyNameLiteral, + isPropertySignature: () => isPropertySignature, + isProtoSetter: () => isProtoSetter, + isPrototypeAccess: () => isPrototypeAccess, + isPrototypePropertyAssignment: () => isPrototypePropertyAssignment, + isPunctuation: () => isPunctuation, + isPushOrUnshiftIdentifier: () => isPushOrUnshiftIdentifier, + isQualifiedName: () => isQualifiedName, + isQuestionDotToken: () => isQuestionDotToken, + isQuestionOrExclamationToken: () => isQuestionOrExclamationToken, + isQuestionOrPlusOrMinusToken: () => isQuestionOrPlusOrMinusToken, + isQuestionToken: () => isQuestionToken, + isRawSourceMap: () => isRawSourceMap, + isReadonlyKeyword: () => isReadonlyKeyword, + isReadonlyKeywordOrPlusOrMinusToken: () => isReadonlyKeywordOrPlusOrMinusToken, + isRecognizedTripleSlashComment: () => isRecognizedTripleSlashComment, + isReferenceFileLocation: () => isReferenceFileLocation, + isReferencedFile: () => isReferencedFile, + isRegularExpressionLiteral: () => isRegularExpressionLiteral, + isRequireCall: () => isRequireCall, + isRequireVariableStatement: () => isRequireVariableStatement, + isRestParameter: () => isRestParameter, + isRestTypeNode: () => isRestTypeNode, + isReturnStatement: () => isReturnStatement, + isReturnStatementWithFixablePromiseHandler: () => isReturnStatementWithFixablePromiseHandler, + isRightSideOfAccessExpression: () => isRightSideOfAccessExpression, + isRightSideOfInstanceofExpression: () => isRightSideOfInstanceofExpression, + isRightSideOfPropertyAccess: () => isRightSideOfPropertyAccess, + isRightSideOfQualifiedName: () => isRightSideOfQualifiedName, + isRightSideOfQualifiedNameOrPropertyAccess: () => isRightSideOfQualifiedNameOrPropertyAccess, + isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName: () => isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName, + isRootedDiskPath: () => isRootedDiskPath, + isSameEntityName: () => isSameEntityName, + isSatisfiesExpression: () => isSatisfiesExpression, + isScopeMarker: () => isScopeMarker, + isSemicolonClassElement: () => isSemicolonClassElement, + isSetAccessor: () => isSetAccessor, + isSetAccessorDeclaration: () => isSetAccessorDeclaration, + isShebangTrivia: () => isShebangTrivia, + isShiftOperatorOrHigher: () => isShiftOperatorOrHigher, + isShorthandAmbientModuleSymbol: () => isShorthandAmbientModuleSymbol, + isShorthandPropertyAssignment: () => isShorthandPropertyAssignment, + isSignedNumericLiteral: () => isSignedNumericLiteral, + isSimpleCopiableExpression: () => isSimpleCopiableExpression, + isSimpleInlineableExpression: () => isSimpleInlineableExpression, + isSingleOrDoubleQuote: () => isSingleOrDoubleQuote, + isSourceFile: () => isSourceFile, + isSourceFileFromLibrary: () => isSourceFileFromLibrary, + isSourceFileJS: () => isSourceFileJS, + isSourceFileNotJS: () => isSourceFileNotJS, + isSourceFileNotJson: () => isSourceFileNotJson, + isSourceMapping: () => isSourceMapping, + isSpecialPropertyDeclaration: () => isSpecialPropertyDeclaration, + isSpreadAssignment: () => isSpreadAssignment, + isSpreadElement: () => isSpreadElement, + isStatement: () => isStatement, + isStatementButNotDeclaration: () => isStatementButNotDeclaration, + isStatementOrBlock: () => isStatementOrBlock, + isStatementWithLocals: () => isStatementWithLocals, + isStatic: () => isStatic, + isStaticModifier: () => isStaticModifier, + isString: () => isString, + isStringAKeyword: () => isStringAKeyword, + isStringANonContextualKeyword: () => isStringANonContextualKeyword, + isStringAndEmptyAnonymousObjectIntersection: () => isStringAndEmptyAnonymousObjectIntersection, + isStringDoubleQuoted: () => isStringDoubleQuoted, + isStringLiteral: () => isStringLiteral, + isStringLiteralLike: () => isStringLiteralLike, + isStringLiteralOrJsxExpression: () => isStringLiteralOrJsxExpression, + isStringLiteralOrTemplate: () => isStringLiteralOrTemplate, + isStringOrNumericLiteralLike: () => isStringOrNumericLiteralLike, + isStringOrRegularExpressionOrTemplateLiteral: () => isStringOrRegularExpressionOrTemplateLiteral, + isStringTextContainingNode: () => isStringTextContainingNode, + isSuperCall: () => isSuperCall, + isSuperKeyword: () => isSuperKeyword, + isSuperOrSuperProperty: () => isSuperOrSuperProperty, + isSuperProperty: () => isSuperProperty, + isSupportedSourceFileName: () => isSupportedSourceFileName, + isSwitchStatement: () => isSwitchStatement, + isSyntaxList: () => isSyntaxList, + isSyntheticExpression: () => isSyntheticExpression, + isSyntheticReference: () => isSyntheticReference, + isTagName: () => isTagName, + isTaggedTemplateExpression: () => isTaggedTemplateExpression, + isTaggedTemplateTag: () => isTaggedTemplateTag, + isTemplateExpression: () => isTemplateExpression, + isTemplateHead: () => isTemplateHead, + isTemplateLiteral: () => isTemplateLiteral, + isTemplateLiteralKind: () => isTemplateLiteralKind, + isTemplateLiteralToken: () => isTemplateLiteralToken, + isTemplateLiteralTypeNode: () => isTemplateLiteralTypeNode, + isTemplateLiteralTypeSpan: () => isTemplateLiteralTypeSpan, + isTemplateMiddle: () => isTemplateMiddle, + isTemplateMiddleOrTemplateTail: () => isTemplateMiddleOrTemplateTail, + isTemplateSpan: () => isTemplateSpan, + isTemplateTail: () => isTemplateTail, + isTextWhiteSpaceLike: () => isTextWhiteSpaceLike, + isThis: () => isThis, + isThisContainerOrFunctionBlock: () => isThisContainerOrFunctionBlock, + isThisIdentifier: () => isThisIdentifier, + isThisInTypeQuery: () => isThisInTypeQuery, + isThisInitializedDeclaration: () => isThisInitializedDeclaration, + isThisInitializedObjectBindingExpression: () => isThisInitializedObjectBindingExpression, + isThisProperty: () => isThisProperty, + isThisTypeNode: () => isThisTypeNode, + isThisTypeParameter: () => isThisTypeParameter, + isThisTypePredicate: () => isThisTypePredicate, + isThrowStatement: () => isThrowStatement, + isToken: () => isToken, + isTokenKind: () => isTokenKind, + isTraceEnabled: () => isTraceEnabled, + isTransientSymbol: () => isTransientSymbol, + isTrivia: () => isTrivia, + isTryStatement: () => isTryStatement, + isTupleTypeNode: () => isTupleTypeNode, + isTypeAlias: () => isTypeAlias, + isTypeAliasDeclaration: () => isTypeAliasDeclaration, + isTypeAssertionExpression: () => isTypeAssertionExpression, + isTypeDeclaration: () => isTypeDeclaration, + isTypeElement: () => isTypeElement, + isTypeKeyword: () => isTypeKeyword, + isTypeKeywordToken: () => isTypeKeywordToken, + isTypeKeywordTokenOrIdentifier: () => isTypeKeywordTokenOrIdentifier, + isTypeLiteralNode: () => isTypeLiteralNode, + isTypeNode: () => isTypeNode, + isTypeNodeKind: () => isTypeNodeKind, + isTypeOfExpression: () => isTypeOfExpression, + isTypeOnlyExportDeclaration: () => isTypeOnlyExportDeclaration, + isTypeOnlyImportDeclaration: () => isTypeOnlyImportDeclaration, + isTypeOnlyImportOrExportDeclaration: () => isTypeOnlyImportOrExportDeclaration, + isTypeOperatorNode: () => isTypeOperatorNode, + isTypeParameterDeclaration: () => isTypeParameterDeclaration, + isTypePredicateNode: () => isTypePredicateNode, + isTypeQueryNode: () => isTypeQueryNode, + isTypeReferenceNode: () => isTypeReferenceNode, + isTypeReferenceType: () => isTypeReferenceType, + isTypeUsableAsPropertyName: () => isTypeUsableAsPropertyName, + isUMDExportSymbol: () => isUMDExportSymbol, + isUnaryExpression: () => isUnaryExpression, + isUnaryExpressionWithWrite: () => isUnaryExpressionWithWrite, + isUnicodeIdentifierStart: () => isUnicodeIdentifierStart, + isUnionTypeNode: () => isUnionTypeNode, + isUnparsedNode: () => isUnparsedNode, + isUnparsedPrepend: () => isUnparsedPrepend, + isUnparsedSource: () => isUnparsedSource, + isUnparsedTextLike: () => isUnparsedTextLike, + isUrl: () => isUrl, + isValidBigIntString: () => isValidBigIntString, + isValidESSymbolDeclaration: () => isValidESSymbolDeclaration, + isValidTypeOnlyAliasUseSite: () => isValidTypeOnlyAliasUseSite, + isValueSignatureDeclaration: () => isValueSignatureDeclaration, + isVarAwaitUsing: () => isVarAwaitUsing, + isVarConst: () => isVarConst, + isVarUsing: () => isVarUsing, + isVariableDeclaration: () => isVariableDeclaration, + isVariableDeclarationInVariableStatement: () => isVariableDeclarationInVariableStatement, + isVariableDeclarationInitializedToBareOrAccessedRequire: () => isVariableDeclarationInitializedToBareOrAccessedRequire, + isVariableDeclarationInitializedToRequire: () => isVariableDeclarationInitializedToRequire, + isVariableDeclarationList: () => isVariableDeclarationList, + isVariableLike: () => isVariableLike, + isVariableLikeOrAccessor: () => isVariableLikeOrAccessor, + isVariableStatement: () => isVariableStatement, + isVoidExpression: () => isVoidExpression, + isWatchSet: () => isWatchSet, + isWhileStatement: () => isWhileStatement, + isWhiteSpaceLike: () => isWhiteSpaceLike, + isWhiteSpaceSingleLine: () => isWhiteSpaceSingleLine, + isWithStatement: () => isWithStatement, + isWriteAccess: () => isWriteAccess, + isWriteOnlyAccess: () => isWriteOnlyAccess, + isYieldExpression: () => isYieldExpression, + jsxModeNeedsExplicitImport: () => jsxModeNeedsExplicitImport, + keywordPart: () => keywordPart, + last: () => last, + lastOrUndefined: () => lastOrUndefined, + length: () => length, + libMap: () => libMap, + libs: () => libs, + lineBreakPart: () => lineBreakPart, + linkNamePart: () => linkNamePart, + linkPart: () => linkPart, + linkTextPart: () => linkTextPart, + listFiles: () => listFiles, + loadModuleFromGlobalCache: () => loadModuleFromGlobalCache, + loadWithModeAwareCache: () => loadWithModeAwareCache, + makeIdentifierFromModuleName: () => makeIdentifierFromModuleName, + makeImport: () => makeImport, + makeImportIfNecessary: () => makeImportIfNecessary, + makeStringLiteral: () => makeStringLiteral, + mangleScopedPackageName: () => mangleScopedPackageName, + map: () => map, + mapAllOrFail: () => mapAllOrFail, + mapDefined: () => mapDefined, + mapDefinedEntries: () => mapDefinedEntries, + mapDefinedIterator: () => mapDefinedIterator, + mapEntries: () => mapEntries, + mapIterator: () => mapIterator, + mapOneOrMany: () => mapOneOrMany, + mapToDisplayParts: () => mapToDisplayParts, + matchFiles: () => matchFiles, + matchPatternOrExact: () => matchPatternOrExact, + matchedText: () => matchedText, + matchesExclude: () => matchesExclude, + maybeBind: () => maybeBind, + maybeSetLocalizedDiagnosticMessages: () => maybeSetLocalizedDiagnosticMessages, + memoize: () => memoize, + memoizeCached: () => memoizeCached, + memoizeOne: () => memoizeOne, + memoizeWeak: () => memoizeWeak, + metadataHelper: () => metadataHelper, + min: () => min, + minAndMax: () => minAndMax, + missingFileModifiedTime: () => missingFileModifiedTime, + modifierToFlag: () => modifierToFlag, + modifiersToFlags: () => modifiersToFlags, + moduleOptionDeclaration: () => moduleOptionDeclaration, + moduleResolutionIsEqualTo: () => moduleResolutionIsEqualTo, + moduleResolutionNameAndModeGetter: () => moduleResolutionNameAndModeGetter, + moduleResolutionOptionDeclarations: () => moduleResolutionOptionDeclarations, + moduleResolutionSupportsPackageJsonExportsAndImports: () => moduleResolutionSupportsPackageJsonExportsAndImports, + moduleResolutionUsesNodeModules: () => moduleResolutionUsesNodeModules, + moduleSpecifiers: () => ts_moduleSpecifiers_exports, + moveEmitHelpers: () => moveEmitHelpers, + moveRangeEnd: () => moveRangeEnd, + moveRangePastDecorators: () => moveRangePastDecorators, + moveRangePastModifiers: () => moveRangePastModifiers, + moveRangePos: () => moveRangePos, + moveSyntheticComments: () => moveSyntheticComments, + mutateMap: () => mutateMap, + mutateMapSkippingNewValues: () => mutateMapSkippingNewValues, + needsParentheses: () => needsParentheses, + needsScopeMarker: () => needsScopeMarker, + newCaseClauseTracker: () => newCaseClauseTracker, + newPrivateEnvironment: () => newPrivateEnvironment, + noEmitNotification: () => noEmitNotification, + noEmitSubstitution: () => noEmitSubstitution, + noTransformers: () => noTransformers, + noTruncationMaximumTruncationLength: () => noTruncationMaximumTruncationLength, + nodeCanBeDecorated: () => nodeCanBeDecorated, + nodeHasName: () => nodeHasName, + nodeIsDecorated: () => nodeIsDecorated, + nodeIsMissing: () => nodeIsMissing, + nodeIsPresent: () => nodeIsPresent, + nodeIsSynthesized: () => nodeIsSynthesized, + nodeModuleNameResolver: () => nodeModuleNameResolver, + nodeModulesPathPart: () => nodeModulesPathPart, + nodeNextJsonConfigResolver: () => nodeNextJsonConfigResolver, + nodeOrChildIsDecorated: () => nodeOrChildIsDecorated, + nodeOverlapsWithStartEnd: () => nodeOverlapsWithStartEnd, + nodePosToString: () => nodePosToString, + nodeSeenTracker: () => nodeSeenTracker, + nodeStartsNewLexicalEnvironment: () => nodeStartsNewLexicalEnvironment, + nodeToDisplayParts: () => nodeToDisplayParts, + noop: () => noop, + noopFileWatcher: () => noopFileWatcher, + normalizePath: () => normalizePath, + normalizeSlashes: () => normalizeSlashes, + not: () => not, + notImplemented: () => notImplemented, + notImplementedResolver: () => notImplementedResolver, + nullNodeConverters: () => nullNodeConverters, + nullParenthesizerRules: () => nullParenthesizerRules, + nullTransformationContext: () => nullTransformationContext, + objectAllocator: () => objectAllocator, + operatorPart: () => operatorPart, + optionDeclarations: () => optionDeclarations, + optionMapToObject: () => optionMapToObject, + optionsAffectingProgramStructure: () => optionsAffectingProgramStructure, + optionsForBuild: () => optionsForBuild, + optionsForWatch: () => optionsForWatch, + optionsHaveChanges: () => optionsHaveChanges, + optionsHaveModuleResolutionChanges: () => optionsHaveModuleResolutionChanges, + or: () => or, + orderedRemoveItem: () => orderedRemoveItem, + orderedRemoveItemAt: () => orderedRemoveItemAt, + outFile: () => outFile, + packageIdToPackageName: () => packageIdToPackageName, + packageIdToString: () => packageIdToString, + paramHelper: () => paramHelper, + parameterIsThisKeyword: () => parameterIsThisKeyword, + parameterNamePart: () => parameterNamePart, + parseBaseNodeFactory: () => parseBaseNodeFactory, + parseBigInt: () => parseBigInt, + parseBuildCommand: () => parseBuildCommand, + parseCommandLine: () => parseCommandLine, + parseCommandLineWorker: () => parseCommandLineWorker, + parseConfigFileTextToJson: () => parseConfigFileTextToJson, + parseConfigFileWithSystem: () => parseConfigFileWithSystem, + parseConfigHostFromCompilerHostLike: () => parseConfigHostFromCompilerHostLike, + parseCustomTypeOption: () => parseCustomTypeOption, + parseIsolatedEntityName: () => parseIsolatedEntityName, + parseIsolatedJSDocComment: () => parseIsolatedJSDocComment, + parseJSDocTypeExpressionForTests: () => parseJSDocTypeExpressionForTests, + parseJsonConfigFileContent: () => parseJsonConfigFileContent, + parseJsonSourceFileConfigFileContent: () => parseJsonSourceFileConfigFileContent, + parseJsonText: () => parseJsonText, + parseListTypeOption: () => parseListTypeOption, + parseNodeFactory: () => parseNodeFactory, + parseNodeModuleFromPath: () => parseNodeModuleFromPath, + parsePackageName: () => parsePackageName, + parsePseudoBigInt: () => parsePseudoBigInt, + parseValidBigInt: () => parseValidBigInt, + patchWriteFileEnsuringDirectory: () => patchWriteFileEnsuringDirectory, + pathContainsNodeModules: () => pathContainsNodeModules, + pathIsAbsolute: () => pathIsAbsolute, + pathIsBareSpecifier: () => pathIsBareSpecifier, + pathIsRelative: () => pathIsRelative, + patternText: () => patternText, + perfLogger: () => perfLogger, + performIncrementalCompilation: () => performIncrementalCompilation, + performance: () => ts_performance_exports, + plainJSErrors: () => plainJSErrors, + positionBelongsToNode: () => positionBelongsToNode, + positionIsASICandidate: () => positionIsASICandidate, + positionIsSynthesized: () => positionIsSynthesized, + positionsAreOnSameLine: () => positionsAreOnSameLine, + preProcessFile: () => preProcessFile, + probablyUsesSemicolons: () => probablyUsesSemicolons, + processCommentPragmas: () => processCommentPragmas, + processPragmasIntoFields: () => processPragmasIntoFields, + processTaggedTemplateExpression: () => processTaggedTemplateExpression, + programContainsEsModules: () => programContainsEsModules, + programContainsModules: () => programContainsModules, + projectReferenceIsEqualTo: () => projectReferenceIsEqualTo, + propKeyHelper: () => propKeyHelper, + propertyNamePart: () => propertyNamePart, + pseudoBigIntToString: () => pseudoBigIntToString, + punctuationPart: () => punctuationPart, + pushIfUnique: () => pushIfUnique, + quote: () => quote, + quotePreferenceFromString: () => quotePreferenceFromString, + rangeContainsPosition: () => rangeContainsPosition, + rangeContainsPositionExclusive: () => rangeContainsPositionExclusive, + rangeContainsRange: () => rangeContainsRange, + rangeContainsRangeExclusive: () => rangeContainsRangeExclusive, + rangeContainsStartEnd: () => rangeContainsStartEnd, + rangeEndIsOnSameLineAsRangeStart: () => rangeEndIsOnSameLineAsRangeStart, + rangeEndPositionsAreOnSameLine: () => rangeEndPositionsAreOnSameLine, + rangeEquals: () => rangeEquals, + rangeIsOnSingleLine: () => rangeIsOnSingleLine, + rangeOfNode: () => rangeOfNode, + rangeOfTypeParameters: () => rangeOfTypeParameters, + rangeOverlapsWithStartEnd: () => rangeOverlapsWithStartEnd, + rangeStartIsOnSameLineAsRangeEnd: () => rangeStartIsOnSameLineAsRangeEnd, + rangeStartPositionsAreOnSameLine: () => rangeStartPositionsAreOnSameLine, + readBuilderProgram: () => readBuilderProgram, + readConfigFile: () => readConfigFile, + readHelper: () => readHelper, + readJson: () => readJson, + readJsonConfigFile: () => readJsonConfigFile, + readJsonOrUndefined: () => readJsonOrUndefined, + reduceEachLeadingCommentRange: () => reduceEachLeadingCommentRange, + reduceEachTrailingCommentRange: () => reduceEachTrailingCommentRange, + reduceLeft: () => reduceLeft, + reduceLeftIterator: () => reduceLeftIterator, + reducePathComponents: () => reducePathComponents, + refactor: () => ts_refactor_exports, + regExpEscape: () => regExpEscape, + relativeComplement: () => relativeComplement, + removeAllComments: () => removeAllComments, + removeEmitHelper: () => removeEmitHelper, + removeExtension: () => removeExtension, + removeFileExtension: () => removeFileExtension, + removeIgnoredPath: () => removeIgnoredPath, + removeMinAndVersionNumbers: () => removeMinAndVersionNumbers, + removeOptionality: () => removeOptionality, + removePrefix: () => removePrefix, + removeSuffix: () => removeSuffix, + removeTrailingDirectorySeparator: () => removeTrailingDirectorySeparator, + repeatString: () => repeatString, + replaceElement: () => replaceElement, + resolutionExtensionIsTSOrJson: () => resolutionExtensionIsTSOrJson, + resolveConfigFileProjectName: () => resolveConfigFileProjectName, + resolveJSModule: () => resolveJSModule, + resolveLibrary: () => resolveLibrary, + resolveModuleName: () => resolveModuleName, + resolveModuleNameFromCache: () => resolveModuleNameFromCache, + resolvePackageNameToPackageJson: () => resolvePackageNameToPackageJson, + resolvePath: () => resolvePath, + resolveProjectReferencePath: () => resolveProjectReferencePath, + resolveTripleslashReference: () => resolveTripleslashReference, + resolveTypeReferenceDirective: () => resolveTypeReferenceDirective, + resolvingEmptyArray: () => resolvingEmptyArray, + restHelper: () => restHelper, + returnFalse: () => returnFalse, + returnNoopFileWatcher: () => returnNoopFileWatcher, + returnTrue: () => returnTrue, + returnUndefined: () => returnUndefined, + returnsPromise: () => returnsPromise, + runInitializersHelper: () => runInitializersHelper, + sameFlatMap: () => sameFlatMap, + sameMap: () => sameMap, + sameMapping: () => sameMapping, + scanShebangTrivia: () => scanShebangTrivia, + scanTokenAtPosition: () => scanTokenAtPosition, + scanner: () => scanner, + screenStartingMessageCodes: () => screenStartingMessageCodes, + semanticDiagnosticsOptionDeclarations: () => semanticDiagnosticsOptionDeclarations, + serializeCompilerOptions: () => serializeCompilerOptions, + server: () => ts_server_exports4, + servicesVersion: () => servicesVersion, + setCommentRange: () => setCommentRange, + setConfigFileInOptions: () => setConfigFileInOptions, + setConstantValue: () => setConstantValue, + setEachParent: () => setEachParent, + setEmitFlags: () => setEmitFlags, + setFunctionNameHelper: () => setFunctionNameHelper, + setGetSourceFileAsHashVersioned: () => setGetSourceFileAsHashVersioned, + setIdentifierAutoGenerate: () => setIdentifierAutoGenerate, + setIdentifierGeneratedImportReference: () => setIdentifierGeneratedImportReference, + setIdentifierTypeArguments: () => setIdentifierTypeArguments, + setInternalEmitFlags: () => setInternalEmitFlags, + setLocalizedDiagnosticMessages: () => setLocalizedDiagnosticMessages, + setModuleDefaultHelper: () => setModuleDefaultHelper, + setNodeFlags: () => setNodeFlags, + setObjectAllocator: () => setObjectAllocator, + setOriginalNode: () => setOriginalNode, + setParent: () => setParent, + setParentRecursive: () => setParentRecursive, + setPrivateIdentifier: () => setPrivateIdentifier, + setSnippetElement: () => setSnippetElement, + setSourceMapRange: () => setSourceMapRange, + setStackTraceLimit: () => setStackTraceLimit, + setStartsOnNewLine: () => setStartsOnNewLine, + setSyntheticLeadingComments: () => setSyntheticLeadingComments, + setSyntheticTrailingComments: () => setSyntheticTrailingComments, + setSys: () => setSys, + setSysLog: () => setSysLog, + setTextRange: () => setTextRange, + setTextRangeEnd: () => setTextRangeEnd, + setTextRangePos: () => setTextRangePos, + setTextRangePosEnd: () => setTextRangePosEnd, + setTextRangePosWidth: () => setTextRangePosWidth, + setTokenSourceMapRange: () => setTokenSourceMapRange, + setTypeNode: () => setTypeNode, + setUILocale: () => setUILocale, + setValueDeclaration: () => setValueDeclaration, + shouldAllowImportingTsExtension: () => shouldAllowImportingTsExtension, + shouldPreserveConstEnums: () => shouldPreserveConstEnums, + shouldResolveJsRequire: () => shouldResolveJsRequire, + shouldUseUriStyleNodeCoreModules: () => shouldUseUriStyleNodeCoreModules, + showModuleSpecifier: () => showModuleSpecifier, + signatureHasLiteralTypes: () => signatureHasLiteralTypes, + signatureHasRestParameter: () => signatureHasRestParameter, + signatureToDisplayParts: () => signatureToDisplayParts, + single: () => single, + singleElementArray: () => singleElementArray, + singleIterator: () => singleIterator, + singleOrMany: () => singleOrMany, + singleOrUndefined: () => singleOrUndefined, + skipAlias: () => skipAlias, + skipAssertions: () => skipAssertions, + skipConstraint: () => skipConstraint, + skipOuterExpressions: () => skipOuterExpressions, + skipParentheses: () => skipParentheses, + skipPartiallyEmittedExpressions: () => skipPartiallyEmittedExpressions, + skipTrivia: () => skipTrivia, + skipTypeChecking: () => skipTypeChecking, + skipTypeParentheses: () => skipTypeParentheses, + skipWhile: () => skipWhile, + sliceAfter: () => sliceAfter, + some: () => some, + sort: () => sort, + sortAndDeduplicate: () => sortAndDeduplicate, + sortAndDeduplicateDiagnostics: () => sortAndDeduplicateDiagnostics, + sourceFileAffectingCompilerOptions: () => sourceFileAffectingCompilerOptions, + sourceFileMayBeEmitted: () => sourceFileMayBeEmitted, + sourceMapCommentRegExp: () => sourceMapCommentRegExp, + sourceMapCommentRegExpDontCareLineStart: () => sourceMapCommentRegExpDontCareLineStart, + spacePart: () => spacePart, + spanMap: () => spanMap, + spreadArrayHelper: () => spreadArrayHelper, + stableSort: () => stableSort, + startEndContainsRange: () => startEndContainsRange, + startEndOverlapsWithStartEnd: () => startEndOverlapsWithStartEnd, + startOnNewLine: () => startOnNewLine, + startTracing: () => startTracing, + startsWith: () => startsWith, + startsWithDirectory: () => startsWithDirectory, + startsWithUnderscore: () => startsWithUnderscore, + startsWithUseStrict: () => startsWithUseStrict, + stringContainsAt: () => stringContainsAt, + stringToToken: () => stringToToken, + stripQuotes: () => stripQuotes, + supportedDeclarationExtensions: () => supportedDeclarationExtensions, + supportedJSExtensions: () => supportedJSExtensions, + supportedJSExtensionsFlat: () => supportedJSExtensionsFlat, + supportedLocaleDirectories: () => supportedLocaleDirectories, + supportedTSExtensions: () => supportedTSExtensions, + supportedTSExtensionsFlat: () => supportedTSExtensionsFlat, + supportedTSImplementationExtensions: () => supportedTSImplementationExtensions, + suppressLeadingAndTrailingTrivia: () => suppressLeadingAndTrailingTrivia, + suppressLeadingTrivia: () => suppressLeadingTrivia, + suppressTrailingTrivia: () => suppressTrailingTrivia, + symbolEscapedNameNoDefault: () => symbolEscapedNameNoDefault, + symbolName: () => symbolName, + symbolNameNoDefault: () => symbolNameNoDefault, + symbolPart: () => symbolPart, + symbolToDisplayParts: () => symbolToDisplayParts, + syntaxMayBeASICandidate: () => syntaxMayBeASICandidate, + syntaxRequiresTrailingSemicolonOrASI: () => syntaxRequiresTrailingSemicolonOrASI, + sys: () => sys, + sysLog: () => sysLog, + tagNamesAreEquivalent: () => tagNamesAreEquivalent, + takeWhile: () => takeWhile, + targetOptionDeclaration: () => targetOptionDeclaration, + templateObjectHelper: () => templateObjectHelper, + testFormatSettings: () => testFormatSettings, + textChangeRangeIsUnchanged: () => textChangeRangeIsUnchanged, + textChangeRangeNewSpan: () => textChangeRangeNewSpan, + textChanges: () => ts_textChanges_exports, + textOrKeywordPart: () => textOrKeywordPart, + textPart: () => textPart, + textRangeContainsPositionInclusive: () => textRangeContainsPositionInclusive, + textSpanContainsPosition: () => textSpanContainsPosition, + textSpanContainsTextSpan: () => textSpanContainsTextSpan, + textSpanEnd: () => textSpanEnd, + textSpanIntersection: () => textSpanIntersection, + textSpanIntersectsWith: () => textSpanIntersectsWith, + textSpanIntersectsWithPosition: () => textSpanIntersectsWithPosition, + textSpanIntersectsWithTextSpan: () => textSpanIntersectsWithTextSpan, + textSpanIsEmpty: () => textSpanIsEmpty, + textSpanOverlap: () => textSpanOverlap, + textSpanOverlapsWith: () => textSpanOverlapsWith, + textSpansEqual: () => textSpansEqual, + textToKeywordObj: () => textToKeywordObj, + timestamp: () => timestamp, + toArray: () => toArray, + toBuilderFileEmit: () => toBuilderFileEmit, + toBuilderStateFileInfoForMultiEmit: () => toBuilderStateFileInfoForMultiEmit, + toEditorSettings: () => toEditorSettings, + toFileNameLowerCase: () => toFileNameLowerCase, + toLowerCase: () => toLowerCase, + toPath: () => toPath, + toProgramEmitPending: () => toProgramEmitPending, + tokenIsIdentifierOrKeyword: () => tokenIsIdentifierOrKeyword, + tokenIsIdentifierOrKeywordOrGreaterThan: () => tokenIsIdentifierOrKeywordOrGreaterThan, + tokenToString: () => tokenToString, + trace: () => trace, + tracing: () => tracing, + tracingEnabled: () => tracingEnabled, + transform: () => transform, + transformClassFields: () => transformClassFields, + transformDeclarations: () => transformDeclarations, + transformECMAScriptModule: () => transformECMAScriptModule, + transformES2015: () => transformES2015, + transformES2016: () => transformES2016, + transformES2017: () => transformES2017, + transformES2018: () => transformES2018, + transformES2019: () => transformES2019, + transformES2020: () => transformES2020, + transformES2021: () => transformES2021, + transformES5: () => transformES5, + transformESDecorators: () => transformESDecorators, + transformESNext: () => transformESNext, + transformGenerators: () => transformGenerators, + transformJsx: () => transformJsx, + transformLegacyDecorators: () => transformLegacyDecorators, + transformModule: () => transformModule, + transformNamedEvaluation: () => transformNamedEvaluation, + transformNodeModule: () => transformNodeModule, + transformNodes: () => transformNodes, + transformSystemModule: () => transformSystemModule, + transformTypeScript: () => transformTypeScript, + transpile: () => transpile, + transpileModule: () => transpileModule, + transpileOptionValueCompilerOptions: () => transpileOptionValueCompilerOptions, + tryAddToSet: () => tryAddToSet, + tryAndIgnoreErrors: () => tryAndIgnoreErrors, + tryCast: () => tryCast, + tryDirectoryExists: () => tryDirectoryExists, + tryExtractTSExtension: () => tryExtractTSExtension, + tryFileExists: () => tryFileExists, + tryGetClassExtendingExpressionWithTypeArguments: () => tryGetClassExtendingExpressionWithTypeArguments, + tryGetClassImplementingOrExtendingExpressionWithTypeArguments: () => tryGetClassImplementingOrExtendingExpressionWithTypeArguments, + tryGetDirectories: () => tryGetDirectories, + tryGetExtensionFromPath: () => tryGetExtensionFromPath2, + tryGetImportFromModuleSpecifier: () => tryGetImportFromModuleSpecifier, + tryGetJSDocSatisfiesTypeNode: () => tryGetJSDocSatisfiesTypeNode, + tryGetModuleNameFromFile: () => tryGetModuleNameFromFile, + tryGetModuleSpecifierFromDeclaration: () => tryGetModuleSpecifierFromDeclaration, + tryGetNativePerformanceHooks: () => tryGetNativePerformanceHooks, + tryGetPropertyAccessOrIdentifierToString: () => tryGetPropertyAccessOrIdentifierToString, + tryGetPropertyNameOfBindingOrAssignmentElement: () => tryGetPropertyNameOfBindingOrAssignmentElement, + tryGetSourceMappingURL: () => tryGetSourceMappingURL, + tryGetTextOfPropertyName: () => tryGetTextOfPropertyName, + tryIOAndConsumeErrors: () => tryIOAndConsumeErrors, + tryParsePattern: () => tryParsePattern, + tryParsePatterns: () => tryParsePatterns, + tryParseRawSourceMap: () => tryParseRawSourceMap, + tryReadDirectory: () => tryReadDirectory, + tryReadFile: () => tryReadFile, + tryRemoveDirectoryPrefix: () => tryRemoveDirectoryPrefix, + tryRemoveExtension: () => tryRemoveExtension, + tryRemovePrefix: () => tryRemovePrefix, + tryRemoveSuffix: () => tryRemoveSuffix, + typeAcquisitionDeclarations: () => typeAcquisitionDeclarations, + typeAliasNamePart: () => typeAliasNamePart, + typeDirectiveIsEqualTo: () => typeDirectiveIsEqualTo, + typeKeywords: () => typeKeywords, + typeParameterNamePart: () => typeParameterNamePart, + typeReferenceResolutionNameAndModeGetter: () => typeReferenceResolutionNameAndModeGetter, + typeToDisplayParts: () => typeToDisplayParts, + unchangedPollThresholds: () => unchangedPollThresholds, + unchangedTextChangeRange: () => unchangedTextChangeRange, + unescapeLeadingUnderscores: () => unescapeLeadingUnderscores, + unmangleScopedPackageName: () => unmangleScopedPackageName, + unorderedRemoveItem: () => unorderedRemoveItem, + unorderedRemoveItemAt: () => unorderedRemoveItemAt, + unreachableCodeIsError: () => unreachableCodeIsError, + unusedLabelIsError: () => unusedLabelIsError, + unwrapInnermostStatementOfLabel: () => unwrapInnermostStatementOfLabel, + updateErrorForNoInputFiles: () => updateErrorForNoInputFiles, + updateLanguageServiceSourceFile: () => updateLanguageServiceSourceFile, + updateMissingFilePathsWatch: () => updateMissingFilePathsWatch, + updatePackageJsonWatch: () => updatePackageJsonWatch, + updateResolutionField: () => updateResolutionField, + updateSharedExtendedConfigFileWatcher: () => updateSharedExtendedConfigFileWatcher, + updateSourceFile: () => updateSourceFile, + updateWatchingWildcardDirectories: () => updateWatchingWildcardDirectories, + usesExtensionsOnImports: () => usesExtensionsOnImports, + usingSingleLineStringWriter: () => usingSingleLineStringWriter, + utf16EncodeAsString: () => utf16EncodeAsString, + validateLocaleAndSetLanguage: () => validateLocaleAndSetLanguage, + valuesHelper: () => valuesHelper, + version: () => version, + versionMajorMinor: () => versionMajorMinor, + visitArray: () => visitArray, + visitCommaListElements: () => visitCommaListElements, + visitEachChild: () => visitEachChild, + visitFunctionBody: () => visitFunctionBody, + visitIterationBody: () => visitIterationBody, + visitLexicalEnvironment: () => visitLexicalEnvironment, + visitNode: () => visitNode, + visitNodes: () => visitNodes2, + visitParameterList: () => visitParameterList, + walkUpBindingElementsAndPatterns: () => walkUpBindingElementsAndPatterns, + walkUpLexicalEnvironments: () => walkUpLexicalEnvironments, + walkUpOuterExpressions: () => walkUpOuterExpressions, + walkUpParenthesizedExpressions: () => walkUpParenthesizedExpressions, + walkUpParenthesizedTypes: () => walkUpParenthesizedTypes, + walkUpParenthesizedTypesAndGetParentAndChild: () => walkUpParenthesizedTypesAndGetParentAndChild, + whitespaceOrMapCommentRegExp: () => whitespaceOrMapCommentRegExp, + writeCommentRange: () => writeCommentRange, + writeFile: () => writeFile, + writeFileEnsuringDirectories: () => writeFileEnsuringDirectories, + zipWith: () => zipWith + }); + var init_ts8 = __esm({ + "src/typescript/_namespaces/ts.ts"() { + "use strict"; + init_ts2(); + init_ts3(); + init_ts4(); + init_ts7(); + init_ts_server4(); } }); // src/typescript/typescript.ts var require_typescript = __commonJS({ "src/typescript/typescript.ts"(exports, module2) { - init_ts6(); - init_ts6(); + init_ts8(); + init_ts8(); if (typeof console !== "undefined") { Debug.loggingHost = { log(level, s) { @@ -174376,7 +188710,7 @@ ${options.prefix}` : "\n" : options.prefix } }; } - module2.exports = ts_exports2; + module2.exports = ts_exports3; } }); return require_typescript(); diff --git a/cli/tsc/99_main_compiler.js b/cli/tsc/99_main_compiler.js index 3f67ccb241..8f76425c15 100644 --- a/cli/tsc/99_main_compiler.js +++ b/cli/tsc/99_main_compiler.js @@ -226,6 +226,8 @@ delete Object.prototype.__proto__; impliedNodeFormat: isCjsCache.has(fileName) ? ts.ModuleKind.CommonJS : ts.ModuleKind.ESNext, + // in the lsp we want to be able to show documentation + jsDocParsingMode: ts.JSDocParsingMode.ParseAll, }, version, true, @@ -537,11 +539,12 @@ delete Object.prototype.__proto__; _onError, _shouldCreateNewSourceFile, ) { - const createOptions = getCreateSourceFileOptions(languageVersion); if (logDebug) { debug( `host.getSourceFile("${specifier}", ${ - ts.ScriptTarget[createOptions.languageVersion] + ts.ScriptTarget[ + getCreateSourceFileOptions(languageVersion).languageVersion + ] })`, ); } @@ -568,10 +571,12 @@ delete Object.prototype.__proto__; specifier, data, { - ...createOptions, + ...getCreateSourceFileOptions(languageVersion), impliedNodeFormat: isCjsCache.has(specifier) ? ts.ModuleKind.CommonJS : ts.ModuleKind.ESNext, + // no need to parse docs for `deno check` + jsDocParsingMode: ts.JSDocParsingMode.ParseForTypeErrors, }, false, scriptKind, diff --git a/cli/tsc/dts/lib.decorators.d.ts b/cli/tsc/dts/lib.decorators.d.ts index 11a8ca6de6..5ac09b8257 100644 --- a/cli/tsc/dts/lib.decorators.d.ts +++ b/cli/tsc/dts/lib.decorators.d.ts @@ -24,21 +24,18 @@ type ClassMemberDecoratorContext = | ClassGetterDecoratorContext | ClassSetterDecoratorContext | ClassFieldDecoratorContext - | ClassAccessorDecoratorContext - ; + | ClassAccessorDecoratorContext; /** * The decorator context types provided to any decorator. */ type DecoratorContext = | ClassDecoratorContext - | ClassMemberDecoratorContext - ; + | ClassMemberDecoratorContext; type DecoratorMetadataObject = Record & object; -type DecoratorMetadata = - typeof globalThis extends { Symbol: { readonly metadata: symbol } } ? DecoratorMetadataObject : DecoratorMetadataObject | undefined; +type DecoratorMetadata = typeof globalThis extends { Symbol: { readonly metadata: symbol; }; } ? DecoratorMetadataObject : DecoratorMetadataObject | undefined; /** * Context provided to a class decorator. diff --git a/cli/tsc/dts/lib.dom.d.ts b/cli/tsc/dts/lib.dom.d.ts index 38c75781d6..59b1b6bb79 100644 --- a/cli/tsc/dts/lib.dom.d.ts +++ b/cli/tsc/dts/lib.dom.d.ts @@ -1436,6 +1436,7 @@ interface RTCInboundRtpStreamStats extends RTCReceivedRtpStreamStats { keyFramesDecoded?: number; kind: string; lastPacketReceivedTimestamp?: DOMHighResTimeStamp; + mid?: string; nackCount?: number; packetsDiscarded?: number; pliCount?: number; @@ -1450,6 +1451,7 @@ interface RTCInboundRtpStreamStats extends RTCReceivedRtpStreamStats { totalSamplesDuration?: number; totalSamplesReceived?: number; totalSquaredInterFrameDelay?: number; + trackIdentifier: string; } interface RTCLocalSessionDescriptionInit { @@ -8209,7 +8211,7 @@ interface EventTarget { */ addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: AddEventListenerOptions | boolean): void; /** - * Dispatches a synthetic event to event target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) */ @@ -21844,7 +21846,9 @@ interface SubtleCrypto { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) */ exportKey(format: "jwk", key: CryptoKey): Promise; exportKey(format: Exclude, key: CryptoKey): Promise; + exportKey(format: KeyFormat, key: CryptoKey): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey(algorithm: "Ed25519", extractable: boolean, keyUsages: ReadonlyArray<"sign" | "verify">): Promise; generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: ReadonlyArray): Promise; generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: ReadonlyArray): Promise; generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): Promise; @@ -27428,7 +27432,7 @@ declare function scrollTo(x: number, y: number): void; declare function stop(): void; declare function toString(): string; /** - * Dispatches a synthetic event to event target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) */ diff --git a/cli/tsc/dts/lib.es2015.collection.d.ts b/cli/tsc/dts/lib.es2015.collection.d.ts index f94c48543e..abeb66b929 100644 --- a/cli/tsc/dts/lib.es2015.collection.d.ts +++ b/cli/tsc/dts/lib.es2015.collection.d.ts @@ -17,7 +17,6 @@ and limitations under the License. /// interface Map { - clear(): void; /** * @returns true if an element in the Map existed and has been removed, or false if the element does not exist. @@ -47,7 +46,7 @@ interface Map { } interface MapConstructor { - new(): Map; + new (): Map; new (entries?: readonly (readonly [K, V])[] | null): Map; readonly prototype: Map; } diff --git a/cli/tsc/dts/lib.es2015.core.d.ts b/cli/tsc/dts/lib.es2015.core.d.ts index ecd2e029ef..ab37bc49fd 100644 --- a/cli/tsc/dts/lib.es2015.core.d.ts +++ b/cli/tsc/dts/lib.es2015.core.d.ts @@ -553,5 +553,5 @@ interface StringConstructor { * @param template A well-formed template string call site representation. * @param substitutions A set of substitution values. */ - raw(template: { raw: readonly string[] | ArrayLike}, ...substitutions: any[]): string; + raw(template: { raw: readonly string[] | ArrayLike; }, ...substitutions: any[]): string; } diff --git a/cli/tsc/dts/lib.es2015.iterable.d.ts b/cli/tsc/dts/lib.es2015.iterable.d.ts index 7aa2601f4d..3ad043c679 100644 --- a/cli/tsc/dts/lib.es2015.iterable.d.ts +++ b/cli/tsc/dts/lib.es2015.iterable.d.ts @@ -155,11 +155,11 @@ interface ReadonlyMap { } interface MapConstructor { - new(): Map; + new (): Map; new (iterable?: Iterable | null): Map; } -interface WeakMap { } +interface WeakMap {} interface WeakMapConstructor { new (iterable: Iterable): WeakMap; @@ -207,13 +207,13 @@ interface SetConstructor { new (iterable?: Iterable | null): Set; } -interface WeakSet { } +interface WeakSet {} interface WeakSetConstructor { new (iterable: Iterable): WeakSet; } -interface Promise { } +interface Promise {} interface PromiseConstructor { /** @@ -315,7 +315,6 @@ interface Uint8ClampedArray { interface Uint8ClampedArrayConstructor { new (elements: Iterable): Uint8ClampedArray; - /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. diff --git a/cli/tsc/dts/lib.es2015.promise.d.ts b/cli/tsc/dts/lib.es2015.promise.d.ts index cd2adb675b..43b1bd24a8 100644 --- a/cli/tsc/dts/lib.es2015.promise.d.ts +++ b/cli/tsc/dts/lib.es2015.promise.d.ts @@ -36,7 +36,7 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - all(values: T): Promise<{ -readonly [P in keyof T]: Awaited }>; + all(values: T): Promise<{ -readonly [P in keyof T]: Awaited; }>; // see: lib.es2015.iterable.d.ts // all(values: Iterable>): Promise[]>; diff --git a/cli/tsc/dts/lib.es2015.symbol.d.ts b/cli/tsc/dts/lib.es2015.symbol.d.ts index 4b529a5353..aab10e94c0 100644 --- a/cli/tsc/dts/lib.es2015.symbol.d.ts +++ b/cli/tsc/dts/lib.es2015.symbol.d.ts @@ -43,4 +43,4 @@ interface SymbolConstructor { keyFor(sym: symbol): string | undefined; } -declare var Symbol: SymbolConstructor; \ No newline at end of file +declare var Symbol: SymbolConstructor; diff --git a/cli/tsc/dts/lib.es2016.array.include.d.ts b/cli/tsc/dts/lib.es2016.array.include.d.ts index 8acbe4aeb3..3aa5a044e0 100644 --- a/cli/tsc/dts/lib.es2016.array.include.d.ts +++ b/cli/tsc/dts/lib.es2016.array.include.d.ts @@ -113,4 +113,4 @@ interface Float64Array { * @param fromIndex The position in this array at which to begin searching for searchElement. */ includes(searchElement: number, fromIndex?: number): boolean; -} \ No newline at end of file +} diff --git a/cli/tsc/dts/lib.es2016.d.ts b/cli/tsc/dts/lib.es2016.d.ts index 795703948b..5ba3f865f1 100644 --- a/cli/tsc/dts/lib.es2016.d.ts +++ b/cli/tsc/dts/lib.es2016.d.ts @@ -17,4 +17,4 @@ and limitations under the License. /// /// -/// \ No newline at end of file +/// diff --git a/cli/tsc/dts/lib.es2016.full.d.ts b/cli/tsc/dts/lib.es2016.full.d.ts index d50bde9dd0..d05b4a295b 100644 --- a/cli/tsc/dts/lib.es2016.full.d.ts +++ b/cli/tsc/dts/lib.es2016.full.d.ts @@ -20,4 +20,4 @@ and limitations under the License. /// /// /// -/// \ No newline at end of file +/// diff --git a/cli/tsc/dts/lib.es2017.full.d.ts b/cli/tsc/dts/lib.es2017.full.d.ts index 07a98db084..bebe4bf0b9 100644 --- a/cli/tsc/dts/lib.es2017.full.d.ts +++ b/cli/tsc/dts/lib.es2017.full.d.ts @@ -20,4 +20,4 @@ and limitations under the License. /// /// /// -/// \ No newline at end of file +/// diff --git a/cli/tsc/dts/lib.es2017.intl.d.ts b/cli/tsc/dts/lib.es2017.intl.d.ts index 628d7f5339..02a4bf4f47 100644 --- a/cli/tsc/dts/lib.es2017.intl.d.ts +++ b/cli/tsc/dts/lib.es2017.intl.d.ts @@ -17,19 +17,18 @@ and limitations under the License. /// declare namespace Intl { - interface DateTimeFormatPartTypesRegistry { - day: any - dayPeriod: any - era: any - hour: any - literal: any - minute: any - month: any - second: any - timeZoneName: any - weekday: any - year: any + day: any; + dayPeriod: any; + era: any; + hour: any; + literal: any; + minute: any; + month: any; + second: any; + timeZoneName: any; + weekday: any; + year: any; } type DateTimeFormatPartTypes = keyof DateTimeFormatPartTypesRegistry; diff --git a/cli/tsc/dts/lib.es2017.object.d.ts b/cli/tsc/dts/lib.es2017.object.d.ts index fd7dd4d926..af9ef2f987 100644 --- a/cli/tsc/dts/lib.es2017.object.d.ts +++ b/cli/tsc/dts/lib.es2017.object.d.ts @@ -21,7 +21,7 @@ interface ObjectConstructor { * Returns an array of values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - values(o: { [s: string]: T } | ArrayLike): T[]; + values(o: { [s: string]: T; } | ArrayLike): T[]; /** * Returns an array of values of the enumerable properties of an object @@ -33,7 +33,7 @@ interface ObjectConstructor { * Returns an array of key/values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - entries(o: { [s: string]: T } | ArrayLike): [string, T][]; + entries(o: { [s: string]: T; } | ArrayLike): [string, T][]; /** * Returns an array of key/values of the enumerable properties of an object @@ -45,5 +45,5 @@ interface ObjectConstructor { * Returns an object containing all own property descriptors of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - getOwnPropertyDescriptors(o: T): {[P in keyof T]: TypedPropertyDescriptor} & { [x: string]: PropertyDescriptor }; + getOwnPropertyDescriptors(o: T): { [P in keyof T]: TypedPropertyDescriptor; } & { [x: string]: PropertyDescriptor; }; } diff --git a/cli/tsc/dts/lib.es2018.asynciterable.d.ts b/cli/tsc/dts/lib.es2018.asynciterable.d.ts index 6d2e226def..f3de8021d7 100644 --- a/cli/tsc/dts/lib.es2018.asynciterable.d.ts +++ b/cli/tsc/dts/lib.es2018.asynciterable.d.ts @@ -40,4 +40,4 @@ interface AsyncIterable { interface AsyncIterableIterator extends AsyncIterator { [Symbol.asyncIterator](): AsyncIterableIterator; -} \ No newline at end of file +} diff --git a/cli/tsc/dts/lib.es2018.full.d.ts b/cli/tsc/dts/lib.es2018.full.d.ts index 7bc5e011c5..35ed44f0e3 100644 --- a/cli/tsc/dts/lib.es2018.full.d.ts +++ b/cli/tsc/dts/lib.es2018.full.d.ts @@ -20,4 +20,4 @@ and limitations under the License. /// /// /// -/// \ No newline at end of file +/// diff --git a/cli/tsc/dts/lib.es2018.intl.d.ts b/cli/tsc/dts/lib.es2018.intl.d.ts index 56eb922899..da34dae586 100644 --- a/cli/tsc/dts/lib.es2018.intl.d.ts +++ b/cli/tsc/dts/lib.es2018.intl.d.ts @@ -17,7 +17,6 @@ and limitations under the License. /// declare namespace Intl { - // http://cldr.unicode.org/index/cldr-spec/plural-rules#TOC-Determining-Plural-Categories type LDMLPluralRule = "zero" | "one" | "two" | "few" | "many" | "other"; type PluralRuleType = "cardinal" | "ordinal"; @@ -52,7 +51,7 @@ declare namespace Intl { new (locales?: string | string[], options?: PluralRulesOptions): PluralRules; (locales?: string | string[], options?: PluralRulesOptions): PluralRules; - supportedLocalesOf(locales: string | string[], options?: { localeMatcher?: "lookup" | "best fit" }): string[]; + supportedLocalesOf(locales: string | string[], options?: { localeMatcher?: "lookup" | "best fit"; }): string[]; }; // We can only have one definition for 'type' in TypeScript, and so you can learn where the keys come from here: diff --git a/cli/tsc/dts/lib.es2018.promise.d.ts b/cli/tsc/dts/lib.es2018.promise.d.ts index e5044b766a..746340a761 100644 --- a/cli/tsc/dts/lib.es2018.promise.d.ts +++ b/cli/tsc/dts/lib.es2018.promise.d.ts @@ -26,5 +26,5 @@ interface Promise { * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). * @returns A Promise for the completion of the callback. */ - finally(onfinally?: (() => void) | undefined | null): Promise + finally(onfinally?: (() => void) | undefined | null): Promise; } diff --git a/cli/tsc/dts/lib.es2018.regexp.d.ts b/cli/tsc/dts/lib.es2018.regexp.d.ts index 9464390a97..5816848726 100644 --- a/cli/tsc/dts/lib.es2018.regexp.d.ts +++ b/cli/tsc/dts/lib.es2018.regexp.d.ts @@ -18,14 +18,14 @@ and limitations under the License. interface RegExpMatchArray { groups?: { - [key: string]: string - } + [key: string]: string; + }; } interface RegExpExecArray { groups?: { - [key: string]: string - } + [key: string]: string; + }; } interface RegExp { @@ -34,4 +34,4 @@ interface RegExp { * Default is false. Read-only. */ readonly dotAll: boolean; -} \ No newline at end of file +} diff --git a/cli/tsc/dts/lib.es2019.array.d.ts b/cli/tsc/dts/lib.es2019.array.d.ts index a293248d8c..36e9562032 100644 --- a/cli/tsc/dts/lib.es2019.array.d.ts +++ b/cli/tsc/dts/lib.es2019.array.d.ts @@ -17,14 +17,12 @@ and limitations under the License. /// type FlatArray = { - "done": Arr, - "recur": Arr extends ReadonlyArray - ? FlatArray - : Arr + done: Arr; + recur: Arr extends ReadonlyArray ? FlatArray + : Arr; }[Depth extends -1 ? "done" : "recur"]; interface ReadonlyArray { - /** * Calls a defined callback function on each element of an array. Then, flattens the result into * a new array. @@ -35,11 +33,10 @@ interface ReadonlyArray { * @param thisArg An object to which the this keyword can refer in the callback function. If * thisArg is omitted, undefined is used as the this value. */ - flatMap ( + flatMap( callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray, - thisArg?: This - ): U[] - + thisArg?: This, + ): U[]; /** * Returns a new array with all sub-array elements concatenated into it recursively up to the @@ -49,12 +46,11 @@ interface ReadonlyArray { */ flat( this: A, - depth?: D - ): FlatArray[] - } + depth?: D, + ): FlatArray[]; +} interface Array { - /** * Calls a defined callback function on each element of an array. Then, flattens the result into * a new array. @@ -65,10 +61,10 @@ interface Array { * @param thisArg An object to which the this keyword can refer in the callback function. If * thisArg is omitted, undefined is used as the this value. */ - flatMap ( + flatMap( callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray, - thisArg?: This - ): U[] + thisArg?: This, + ): U[]; /** * Returns a new array with all sub-array elements concatenated into it recursively up to the @@ -78,6 +74,6 @@ interface Array { */ flat( this: A, - depth?: D - ): FlatArray[] + depth?: D, + ): FlatArray[]; } diff --git a/cli/tsc/dts/lib.es2019.intl.d.ts b/cli/tsc/dts/lib.es2019.intl.d.ts index 1018481898..04e77c126d 100644 --- a/cli/tsc/dts/lib.es2019.intl.d.ts +++ b/cli/tsc/dts/lib.es2019.intl.d.ts @@ -18,6 +18,6 @@ and limitations under the License. declare namespace Intl { interface DateTimeFormatPartTypesRegistry { - unknown: any + unknown: any; } } diff --git a/cli/tsc/dts/lib.es2019.object.d.ts b/cli/tsc/dts/lib.es2019.object.d.ts index fdfab8ecbe..afb10bbe12 100644 --- a/cli/tsc/dts/lib.es2019.object.d.ts +++ b/cli/tsc/dts/lib.es2019.object.d.ts @@ -23,7 +23,7 @@ interface ObjectConstructor { * Returns an object created by key-value entries for properties and methods * @param entries An iterable object that contains key-value entries for properties and methods. */ - fromEntries(entries: Iterable): { [k: string]: T }; + fromEntries(entries: Iterable): { [k: string]: T; }; /** * Returns an object created by key-value entries for properties and methods diff --git a/cli/tsc/dts/lib.es2020.bigint.d.ts b/cli/tsc/dts/lib.es2020.bigint.d.ts index 73df22e21e..d6b04d7a95 100644 --- a/cli/tsc/dts/lib.es2020.bigint.d.ts +++ b/cli/tsc/dts/lib.es2020.bigint.d.ts @@ -389,9 +389,9 @@ interface BigInt64Array { interface BigInt64ArrayConstructor { readonly prototype: BigInt64Array; - new(length?: number): BigInt64Array; - new(array: Iterable): BigInt64Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigInt64Array; + new (length?: number): BigInt64Array; + new (array: Iterable): BigInt64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigInt64Array; /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; @@ -661,9 +661,9 @@ interface BigUint64Array { interface BigUint64ArrayConstructor { readonly prototype: BigUint64Array; - new(length?: number): BigUint64Array; - new(array: Iterable): BigUint64Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigUint64Array; + new (length?: number): BigUint64Array; + new (array: Iterable): BigUint64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigUint64Array; /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; @@ -720,7 +720,7 @@ interface DataView { setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void; } -declare namespace Intl{ +declare namespace Intl { interface NumberFormat { format(value: number | bigint): string; resolvedOptions(): ResolvedNumberFormatOptions; diff --git a/cli/tsc/dts/lib.es2020.date.d.ts b/cli/tsc/dts/lib.es2020.date.d.ts index 1e0470aa69..48abe00712 100644 --- a/cli/tsc/dts/lib.es2020.date.d.ts +++ b/cli/tsc/dts/lib.es2020.date.d.ts @@ -39,4 +39,4 @@ interface Date { * @param options An object that contains one or more properties that specify comparison options. */ toLocaleTimeString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string; -} \ No newline at end of file +} diff --git a/cli/tsc/dts/lib.es2020.intl.d.ts b/cli/tsc/dts/lib.es2020.intl.d.ts index 71093d30f1..8f356b4899 100644 --- a/cli/tsc/dts/lib.es2020.intl.d.ts +++ b/cli/tsc/dts/lib.es2020.intl.d.ts @@ -18,7 +18,6 @@ and limitations under the License. /// declare namespace Intl { - /** * [Unicode BCP 47 Locale Identifiers](https://unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers) definition. * @@ -58,7 +57,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts). */ - type RelativeTimeFormatUnitSingular = + type RelativeTimeFormatUnitSingular = | "year" | "quarter" | "month" @@ -140,14 +139,14 @@ declare namespace Intl { */ type RelativeTimeFormatPart = | { - type: "literal"; - value: string; - } + type: "literal"; + value: string; + } | { - type: Exclude; - value: string; - unit: RelativeTimeFormatUnitSingular; - }; + type: Exclude; + value: string; + unit: RelativeTimeFormatUnitSingular; + }; interface RelativeTimeFormat { /** @@ -218,7 +217,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat). */ - new( + new ( locales?: UnicodeBCP47LocaleIdentifier | UnicodeBCP47LocaleIdentifier[], options?: RelativeTimeFormatOptions, ): RelativeTimeFormat; @@ -410,7 +409,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/DisplayNames). */ - new(locales: LocalesArgument, options: DisplayNamesOptions): DisplayNames; + new (locales: LocalesArgument, options: DisplayNamesOptions): DisplayNames; /** * Returns an array containing those of the provided locales that are supported in display names without having to fall back to the runtime's default locale. @@ -425,7 +424,6 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/supportedLocalesOf). */ - supportedLocalesOf(locales?: LocalesArgument, options?: { localeMatcher?: RelativeTimeFormatLocaleMatcher }): BCP47LanguageTag[]; + supportedLocalesOf(locales?: LocalesArgument, options?: { localeMatcher?: RelativeTimeFormatLocaleMatcher; }): BCP47LanguageTag[]; }; - } diff --git a/cli/tsc/dts/lib.es2020.promise.d.ts b/cli/tsc/dts/lib.es2020.promise.d.ts index 1a05d75c00..2ce3dfb022 100644 --- a/cli/tsc/dts/lib.es2020.promise.d.ts +++ b/cli/tsc/dts/lib.es2020.promise.d.ts @@ -35,7 +35,7 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - allSettled(values: T): Promise<{ -readonly [P in keyof T]: PromiseSettledResult> }>; + allSettled(values: T): Promise<{ -readonly [P in keyof T]: PromiseSettledResult>; }>; /** * Creates a Promise that is resolved with an array of results when all diff --git a/cli/tsc/dts/lib.es2021.intl.d.ts b/cli/tsc/dts/lib.es2021.intl.d.ts index ac9ffdb7e7..b464d55d66 100644 --- a/cli/tsc/dts/lib.es2021.intl.d.ts +++ b/cli/tsc/dts/lib.es2021.intl.d.ts @@ -17,10 +17,9 @@ and limitations under the License. /// declare namespace Intl { - interface DateTimeFormatPartTypesRegistry { - fractionalSecond: any - } + fractionalSecond: any; + } interface DateTimeFormatOptions { formatMatcher?: "basic" | "best fit" | "best fit" | undefined; @@ -31,7 +30,7 @@ declare namespace Intl { } interface DateTimeRangeFormatPart extends DateTimeFormatPart { - source: "startRange" | "endRange" | "shared" + source: "startRange" | "endRange" | "shared"; } interface DateTimeFormat { @@ -114,7 +113,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts). */ - formatToParts(list: Iterable): { type: "element" | "literal", value: string; }[]; + formatToParts(list: Iterable): { type: "element" | "literal"; value: string; }[]; /** * Returns a new object with properties reflecting the locale and style @@ -144,7 +143,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat). */ - new(locales?: BCP47LanguageTag | BCP47LanguageTag[], options?: ListFormatOptions): ListFormat; + new (locales?: BCP47LanguageTag | BCP47LanguageTag[], options?: ListFormatOptions): ListFormat; /** * Returns an array containing those of the provided locales that are diff --git a/cli/tsc/dts/lib.es2021.promise.d.ts b/cli/tsc/dts/lib.es2021.promise.d.ts index a81e3e5e1f..5ec1f5f7b8 100644 --- a/cli/tsc/dts/lib.es2021.promise.d.ts +++ b/cli/tsc/dts/lib.es2021.promise.d.ts @@ -17,11 +17,11 @@ and limitations under the License. /// interface AggregateError extends Error { - errors: any[] + errors: any[]; } interface AggregateErrorConstructor { - new(errors: Iterable, message?: string): AggregateError; + new (errors: Iterable, message?: string): AggregateError; (errors: Iterable, message?: string): AggregateError; readonly prototype: AggregateError; } @@ -44,7 +44,7 @@ interface PromiseConstructor { * @param values An array or iterable of Promises. * @returns A new Promise. */ - any(values: Iterable>): Promise> + any(values: Iterable>): Promise>; /** * Creates a Promise that can be resolved or rejected using provided functions. diff --git a/cli/tsc/dts/lib.es2021.weakref.d.ts b/cli/tsc/dts/lib.es2021.weakref.d.ts index 3a8be269a7..986af60d49 100644 --- a/cli/tsc/dts/lib.es2021.weakref.d.ts +++ b/cli/tsc/dts/lib.es2021.weakref.d.ts @@ -35,7 +35,7 @@ interface WeakRefConstructor { * In es2023 the value can be either a symbol or an object, in previous versions only object is permissible. * @param target The target value for the WeakRef instance. */ - new(target: T): WeakRef; + new (target: T): WeakRef; } declare var WeakRef: WeakRefConstructor; @@ -70,7 +70,7 @@ interface FinalizationRegistryConstructor { * Creates a finalization registry with an associated cleanup callback * @param cleanupCallback The callback to call after a value in the registry has been reclaimed. */ - new(cleanupCallback: (heldValue: T) => void): FinalizationRegistry; + new (cleanupCallback: (heldValue: T) => void): FinalizationRegistry; } declare var FinalizationRegistry: FinalizationRegistryConstructor; diff --git a/cli/tsc/dts/lib.es2022.error.d.ts b/cli/tsc/dts/lib.es2022.error.d.ts index 1888f3079f..782c485e7c 100644 --- a/cli/tsc/dts/lib.es2022.error.d.ts +++ b/cli/tsc/dts/lib.es2022.error.d.ts @@ -63,11 +63,11 @@ interface AggregateErrorConstructor { new ( errors: Iterable, message?: string, - options?: ErrorOptions + options?: ErrorOptions, ): AggregateError; ( errors: Iterable, message?: string, - options?: ErrorOptions + options?: ErrorOptions, ): AggregateError; } diff --git a/cli/tsc/dts/lib.es2022.intl.d.ts b/cli/tsc/dts/lib.es2022.intl.d.ts index 18423719f0..c41f999f11 100644 --- a/cli/tsc/dts/lib.es2022.intl.d.ts +++ b/cli/tsc/dts/lib.es2022.intl.d.ts @@ -17,7 +17,6 @@ and limitations under the License. /// declare namespace Intl { - /** * An object with some or all properties of the `Intl.Segmenter` constructor `options` parameter. * @@ -90,7 +89,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter). */ - new(locales?: BCP47LanguageTag | BCP47LanguageTag[], options?: SegmenterOptions): Segmenter; + new (locales?: BCP47LanguageTag | BCP47LanguageTag[], options?: SegmenterOptions): Segmenter; /** * Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. diff --git a/cli/tsc/dts/lib.es2022.sharedmemory.d.ts b/cli/tsc/dts/lib.es2022.sharedmemory.d.ts index 5126a4b58e..ea67b0081b 100644 --- a/cli/tsc/dts/lib.es2022.sharedmemory.d.ts +++ b/cli/tsc/dts/lib.es2022.sharedmemory.d.ts @@ -25,7 +25,7 @@ interface Atomics { * @param value The expected value to test. * @param [timeout] The expected value to test. */ - waitAsync(typedArray: Int32Array, index: number, value: number, timeout?: number): { async: false, value: "not-equal" | "timed-out" } | { async: true, value: Promise<"ok" | "timed-out"> }; + waitAsync(typedArray: Int32Array, index: number, value: number, timeout?: number): { async: false; value: "not-equal" | "timed-out"; } | { async: true; value: Promise<"ok" | "timed-out">; }; /** * A non-blocking, asynchronous version of wait which is usable on the main thread. @@ -35,5 +35,5 @@ interface Atomics { * @param value The expected value to test. * @param [timeout] The expected value to test. */ - waitAsync(typedArray: BigInt64Array, index: number, value: bigint, timeout?: number): { async: false, value: "not-equal" | "timed-out" } | { async: true, value: Promise<"ok" | "timed-out"> }; + waitAsync(typedArray: BigInt64Array, index: number, value: bigint, timeout?: number): { async: false; value: "not-equal" | "timed-out"; } | { async: true; value: Promise<"ok" | "timed-out">; }; } diff --git a/cli/tsc/dts/lib.es2023.array.d.ts b/cli/tsc/dts/lib.es2023.array.d.ts index d8d5cc9cb6..bd4db2ceb9 100644 --- a/cli/tsc/dts/lib.es2023.array.d.ts +++ b/cli/tsc/dts/lib.es2023.array.d.ts @@ -97,11 +97,11 @@ interface ReadonlyArray { */ findLast( predicate: (value: T, index: number, array: readonly T[]) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: (value: T, index: number, array: readonly T[]) => unknown, - thisArg?: any + thisArg?: any, ): T | undefined; /** @@ -115,7 +115,7 @@ interface ReadonlyArray { */ findLastIndex( predicate: (value: T, index: number, array: readonly T[]) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -177,13 +177,13 @@ interface Int8Array { predicate: ( value: number, index: number, - array: Int8Array + array: Int8Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: (value: number, index: number, array: Int8Array) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -197,7 +197,7 @@ interface Int8Array { */ findLastIndex( predicate: (value: number, index: number, array: Int8Array) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -209,7 +209,7 @@ interface Int8Array { * Copies and sorts the array. * @param compareFn Function used to determine the order of the elements. It is expected to return * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. + * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts * const myNums = Uint8Array.from([11, 2, 22, 1]); * myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22] @@ -241,13 +241,13 @@ interface Uint8Array { predicate: ( value: number, index: number, - array: Uint8Array + array: Uint8Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: (value: number, index: number, array: Uint8Array) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -261,7 +261,7 @@ interface Uint8Array { */ findLastIndex( predicate: (value: number, index: number, array: Uint8Array) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -273,7 +273,7 @@ interface Uint8Array { * Copies and sorts the array. * @param compareFn Function used to determine the order of the elements. It is expected to return * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. + * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts * const myNums = Uint8Array.from([11, 2, 22, 1]); * myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22] @@ -305,17 +305,17 @@ interface Uint8ClampedArray { predicate: ( value: number, index: number, - array: Uint8ClampedArray + array: Uint8ClampedArray, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: number, index: number, - array: Uint8ClampedArray + array: Uint8ClampedArray, ) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -331,9 +331,9 @@ interface Uint8ClampedArray { predicate: ( value: number, index: number, - array: Uint8ClampedArray + array: Uint8ClampedArray, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -345,7 +345,7 @@ interface Uint8ClampedArray { * Copies and sorts the array. * @param compareFn Function used to determine the order of the elements. It is expected to return * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. + * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts * const myNums = Uint8ClampedArray.from([11, 2, 22, 1]); * myNums.toSorted((a, b) => a - b) // Uint8ClampedArray(4) [1, 2, 11, 22] @@ -377,13 +377,13 @@ interface Int16Array { predicate: ( value: number, index: number, - array: Int16Array + array: Int16Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: (value: number, index: number, array: Int16Array) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -397,7 +397,7 @@ interface Int16Array { */ findLastIndex( predicate: (value: number, index: number, array: Int16Array) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -409,7 +409,7 @@ interface Int16Array { * Copies and sorts the array. * @param compareFn Function used to determine the order of the elements. It is expected to return * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. + * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts * const myNums = Int16Array.from([11, 2, -22, 1]); * myNums.toSorted((a, b) => a - b) // Int16Array(4) [-22, 1, 2, 11] @@ -441,17 +441,17 @@ interface Uint16Array { predicate: ( value: number, index: number, - array: Uint16Array + array: Uint16Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: number, index: number, - array: Uint16Array + array: Uint16Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -467,9 +467,9 @@ interface Uint16Array { predicate: ( value: number, index: number, - array: Uint16Array + array: Uint16Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -481,7 +481,7 @@ interface Uint16Array { * Copies and sorts the array. * @param compareFn Function used to determine the order of the elements. It is expected to return * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. + * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts * const myNums = Uint16Array.from([11, 2, 22, 1]); * myNums.toSorted((a, b) => a - b) // Uint16Array(4) [1, 2, 11, 22] @@ -513,13 +513,13 @@ interface Int32Array { predicate: ( value: number, index: number, - array: Int32Array + array: Int32Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: (value: number, index: number, array: Int32Array) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -533,7 +533,7 @@ interface Int32Array { */ findLastIndex( predicate: (value: number, index: number, array: Int32Array) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -545,7 +545,7 @@ interface Int32Array { * Copies and sorts the array. * @param compareFn Function used to determine the order of the elements. It is expected to return * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. + * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts * const myNums = Int32Array.from([11, 2, -22, 1]); * myNums.toSorted((a, b) => a - b) // Int32Array(4) [-22, 1, 2, 11] @@ -577,17 +577,17 @@ interface Uint32Array { predicate: ( value: number, index: number, - array: Uint32Array + array: Uint32Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: number, index: number, - array: Uint32Array + array: Uint32Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -603,9 +603,9 @@ interface Uint32Array { predicate: ( value: number, index: number, - array: Uint32Array + array: Uint32Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -617,7 +617,7 @@ interface Uint32Array { * Copies and sorts the array. * @param compareFn Function used to determine the order of the elements. It is expected to return * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. + * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts * const myNums = Uint32Array.from([11, 2, 22, 1]); * myNums.toSorted((a, b) => a - b) // Uint32Array(4) [1, 2, 11, 22] @@ -649,17 +649,17 @@ interface Float32Array { predicate: ( value: number, index: number, - array: Float32Array + array: Float32Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: number, index: number, - array: Float32Array + array: Float32Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -675,9 +675,9 @@ interface Float32Array { predicate: ( value: number, index: number, - array: Float32Array + array: Float32Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -689,7 +689,7 @@ interface Float32Array { * Copies and sorts the array. * @param compareFn Function used to determine the order of the elements. It is expected to return * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. + * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts * const myNums = Float32Array.from([11.25, 2, -22.5, 1]); * myNums.toSorted((a, b) => a - b) // Float32Array(4) [-22.5, 1, 2, 11.5] @@ -721,17 +721,17 @@ interface Float64Array { predicate: ( value: number, index: number, - array: Float64Array + array: Float64Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: number, index: number, - array: Float64Array + array: Float64Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -747,9 +747,9 @@ interface Float64Array { predicate: ( value: number, index: number, - array: Float64Array + array: Float64Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -761,7 +761,7 @@ interface Float64Array { * Copies and sorts the array. * @param compareFn Function used to determine the order of the elements. It is expected to return * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. + * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts * const myNums = Float64Array.from([11.25, 2, -22.5, 1]); * myNums.toSorted((a, b) => a - b) // Float64Array(4) [-22.5, 1, 2, 11.5] @@ -793,17 +793,17 @@ interface BigInt64Array { predicate: ( value: bigint, index: number, - array: BigInt64Array + array: BigInt64Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: bigint, index: number, - array: BigInt64Array + array: BigInt64Array, ) => unknown, - thisArg?: any + thisArg?: any, ): bigint | undefined; /** @@ -819,9 +819,9 @@ interface BigInt64Array { predicate: ( value: bigint, index: number, - array: BigInt64Array + array: BigInt64Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -833,7 +833,7 @@ interface BigInt64Array { * Copies and sorts the array. * @param compareFn Function used to determine the order of the elements. It is expected to return * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. + * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts * const myNums = BigInt64Array.from([11n, 2n, -22n, 1n]); * myNums.toSorted((a, b) => Number(a - b)) // BigInt64Array(4) [-22n, 1n, 2n, 11n] @@ -865,17 +865,17 @@ interface BigUint64Array { predicate: ( value: bigint, index: number, - array: BigUint64Array + array: BigUint64Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: bigint, index: number, - array: BigUint64Array + array: BigUint64Array, ) => unknown, - thisArg?: any + thisArg?: any, ): bigint | undefined; /** @@ -891,9 +891,9 @@ interface BigUint64Array { predicate: ( value: bigint, index: number, - array: BigUint64Array + array: BigUint64Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -905,7 +905,7 @@ interface BigUint64Array { * Copies and sorts the array. * @param compareFn Function used to determine the order of the elements. It is expected to return * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. + * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts * const myNums = BigUint64Array.from([11n, 2n, 22n, 1n]); * myNums.toSorted((a, b) => Number(a - b)) // BigUint64Array(4) [1n, 2n, 11n, 22n] diff --git a/cli/tsc/dts/lib.es5.d.ts b/cli/tsc/dts/lib.es5.d.ts index fcb22a4b88..55ce47cade 100644 --- a/cli/tsc/dts/lib.es5.d.ts +++ b/cli/tsc/dts/lib.es5.d.ts @@ -153,7 +153,7 @@ interface Object { } interface ObjectConstructor { - new(value?: any): Object; + new (value?: any): Object; (): any; (value: any): any; @@ -225,7 +225,7 @@ interface ObjectConstructor { * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. * @param o Object on which to lock the attributes. */ - freeze(o: T): Readonly; + freeze(o: T): Readonly; /** * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. @@ -311,7 +311,7 @@ interface FunctionConstructor { * Creates a new function. * @param args A list of arguments the function accepts. */ - new(...args: string[]): Function; + new (...args: string[]): Function; (...args: string[]): Function; readonly prototype: Function; } @@ -532,7 +532,7 @@ interface String { } interface StringConstructor { - new(value?: any): String; + new (value?: any): String; (value?: any): string; readonly prototype: String; fromCharCode(...codes: number[]): string; @@ -549,7 +549,7 @@ interface Boolean { } interface BooleanConstructor { - new(value?: any): Boolean; + new (value?: any): Boolean; (value?: T): boolean; readonly prototype: Boolean; } @@ -586,7 +586,7 @@ interface Number { } interface NumberConstructor { - new(value?: any): Number; + new (value?: any): Number; (value?: any): number; readonly prototype: Number; @@ -638,8 +638,8 @@ interface ImportMeta { * augmented via interface merging. */ interface ImportCallOptions { - assert?: ImportAssertions; - with?: ImportAssertions; + /** @deprecated*/ assert?: ImportAssertions; + with?: ImportAttributes; } /** @@ -649,6 +649,13 @@ interface ImportAssertions { [key: string]: string; } +/** + * The type for the `with` property of the optional second argument to `import()`. + */ +interface ImportAttributes { + [key: string]: string; +} + interface Math { /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ readonly E: number; @@ -915,8 +922,8 @@ interface Date { } interface DateConstructor { - new(): Date; - new(value: number | string): Date; + new (): Date; + new (value: number | string): Date; /** * Creates a new Date. * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. @@ -927,7 +934,7 @@ interface DateConstructor { * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds. * @param ms A number from 0 to 999 that specifies the milliseconds. */ - new(year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + new (year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; (): string; readonly prototype: Date; /** @@ -1015,49 +1022,49 @@ interface RegExp { } interface RegExpConstructor { - new(pattern: RegExp | string): RegExp; - new(pattern: string, flags?: string): RegExp; + new (pattern: RegExp | string): RegExp; + new (pattern: string, flags?: string): RegExp; (pattern: RegExp | string): RegExp; (pattern: string, flags?: string): RegExp; - readonly prototype: RegExp; + readonly "prototype": RegExp; // Non-standard extensions /** @deprecated A legacy feature for browser compatibility */ - $1: string; + "$1": string; /** @deprecated A legacy feature for browser compatibility */ - $2: string; + "$2": string; /** @deprecated A legacy feature for browser compatibility */ - $3: string; + "$3": string; /** @deprecated A legacy feature for browser compatibility */ - $4: string; + "$4": string; /** @deprecated A legacy feature for browser compatibility */ - $5: string; + "$5": string; /** @deprecated A legacy feature for browser compatibility */ - $6: string; + "$6": string; /** @deprecated A legacy feature for browser compatibility */ - $7: string; + "$7": string; /** @deprecated A legacy feature for browser compatibility */ - $8: string; + "$8": string; /** @deprecated A legacy feature for browser compatibility */ - $9: string; + "$9": string; /** @deprecated A legacy feature for browser compatibility */ - input: string; + "input": string; /** @deprecated A legacy feature for browser compatibility */ - $_: string; + "$_": string; /** @deprecated A legacy feature for browser compatibility */ - lastMatch: string; + "lastMatch": string; /** @deprecated A legacy feature for browser compatibility */ "$&": string; /** @deprecated A legacy feature for browser compatibility */ - lastParen: string; + "lastParen": string; /** @deprecated A legacy feature for browser compatibility */ "$+": string; /** @deprecated A legacy feature for browser compatibility */ - leftContext: string; + "leftContext": string; /** @deprecated A legacy feature for browser compatibility */ "$`": string; /** @deprecated A legacy feature for browser compatibility */ - rightContext: string; + "rightContext": string; /** @deprecated A legacy feature for browser compatibility */ "$'": string; } @@ -1071,7 +1078,7 @@ interface Error { } interface ErrorConstructor { - new(message?: string): Error; + new (message?: string): Error; (message?: string): Error; readonly prototype: Error; } @@ -1082,7 +1089,7 @@ interface EvalError extends Error { } interface EvalErrorConstructor extends ErrorConstructor { - new(message?: string): EvalError; + new (message?: string): EvalError; (message?: string): EvalError; readonly prototype: EvalError; } @@ -1093,7 +1100,7 @@ interface RangeError extends Error { } interface RangeErrorConstructor extends ErrorConstructor { - new(message?: string): RangeError; + new (message?: string): RangeError; (message?: string): RangeError; readonly prototype: RangeError; } @@ -1104,7 +1111,7 @@ interface ReferenceError extends Error { } interface ReferenceErrorConstructor extends ErrorConstructor { - new(message?: string): ReferenceError; + new (message?: string): ReferenceError; (message?: string): ReferenceError; readonly prototype: ReferenceError; } @@ -1115,7 +1122,7 @@ interface SyntaxError extends Error { } interface SyntaxErrorConstructor extends ErrorConstructor { - new(message?: string): SyntaxError; + new (message?: string): SyntaxError; (message?: string): SyntaxError; readonly prototype: SyntaxError; } @@ -1126,7 +1133,7 @@ interface TypeError extends Error { } interface TypeErrorConstructor extends ErrorConstructor { - new(message?: string): TypeError; + new (message?: string): TypeError; (message?: string): TypeError; readonly prototype: TypeError; } @@ -1137,7 +1144,7 @@ interface URIError extends Error { } interface URIErrorConstructor extends ErrorConstructor { - new(message?: string): URIError; + new (message?: string): URIError; (message?: string): URIError; readonly prototype: URIError; } @@ -1173,7 +1180,6 @@ interface JSON { */ declare var JSON: JSON; - ///////////////////////////// /// ECMAScript Array API (specially handled by compiler) ///////////////////////////// @@ -1497,7 +1503,7 @@ interface Array { } interface ArrayConstructor { - new(arrayLength?: number): any[]; + new (arrayLength?: number): any[]; new (arrayLength: number): T[]; new (...items: T[]): T[]; (arrayLength?: number): any[]; @@ -1553,13 +1559,12 @@ interface Promise { /** * Recursively unwraps the "awaited type" of a type. Non-promise "thenables" should resolve to `never`. This emulates the behavior of `await`. */ -type Awaited = - T extends null | undefined ? T : // special case for `null | undefined` when not in `--strictNullChecks` mode - T extends object & { then(onfulfilled: infer F, ...args: infer _): any } ? // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped - F extends ((value: infer V, ...args: infer _) => any) ? // if the argument to `then` is callable, extracts the first argument - Awaited : // recursively unwrap the value - never : // the argument to `then` was not callable - T; // non-object or non-thenable +type Awaited = T extends null | undefined ? T : // special case for `null | undefined` when not in `--strictNullChecks` mode + T extends object & { then(onfulfilled: infer F, ...args: infer _): any; } ? // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped + F extends ((value: infer V, ...args: infer _) => any) ? // if the argument to `then` is callable, extracts the first argument + Awaited : // recursively unwrap the value + never : // the argument to `then` was not callable + T; // non-object or non-thenable interface ArrayLike { readonly length: number; @@ -1664,7 +1669,7 @@ type Uncapitalize = intrinsic; /** * Marker for contextual 'this' type */ -interface ThisType { } +interface ThisType {} /** * Stores types to be used with WeakSet, WeakMap, WeakRef, and FinalizationRegistry @@ -1703,7 +1708,7 @@ type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; - new(byteLength: number): ArrayBuffer; + new (byteLength: number): ArrayBuffer; isView(arg: any): arg is ArrayBufferView; } declare var ArrayBuffer: ArrayBufferConstructor; @@ -1855,7 +1860,7 @@ interface DataView { interface DataViewConstructor { readonly prototype: DataView; - new(buffer: ArrayBufferLike & { BYTES_PER_ELEMENT?: never }, byteOffset?: number, byteLength?: number): DataView; + new (buffer: ArrayBufferLike & { BYTES_PER_ELEMENT?: never; }, byteOffset?: number, byteLength?: number): DataView; } declare var DataView: DataViewConstructor; @@ -2108,9 +2113,9 @@ interface Int8Array { } interface Int8ArrayConstructor { readonly prototype: Int8Array; - new(length: number): Int8Array; - new(array: ArrayLike | ArrayBufferLike): Int8Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; + new (length: number): Int8Array; + new (array: ArrayLike | ArrayBufferLike): Int8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -2136,8 +2141,6 @@ interface Int8ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int8Array; - - } declare var Int8Array: Int8ArrayConstructor; @@ -2391,9 +2394,9 @@ interface Uint8Array { interface Uint8ArrayConstructor { readonly prototype: Uint8Array; - new(length: number): Uint8Array; - new(array: ArrayLike | ArrayBufferLike): Uint8Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; + new (length: number): Uint8Array; + new (array: ArrayLike | ArrayBufferLike): Uint8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2419,7 +2422,6 @@ interface Uint8ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8Array; - } declare var Uint8Array: Uint8ArrayConstructor; @@ -2673,9 +2675,9 @@ interface Uint8ClampedArray { interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; - new(length: number): Uint8ClampedArray; - new(array: ArrayLike | ArrayBufferLike): Uint8ClampedArray; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; + new (length: number): Uint8ClampedArray; + new (array: ArrayLike | ArrayBufferLike): Uint8ClampedArray; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2953,9 +2955,9 @@ interface Int16Array { interface Int16ArrayConstructor { readonly prototype: Int16Array; - new(length: number): Int16Array; - new(array: ArrayLike | ArrayBufferLike): Int16Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; + new (length: number): Int16Array; + new (array: ArrayLike | ArrayBufferLike): Int16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2981,8 +2983,6 @@ interface Int16ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int16Array; - - } declare var Int16Array: Int16ArrayConstructor; @@ -3236,9 +3236,9 @@ interface Uint16Array { interface Uint16ArrayConstructor { readonly prototype: Uint16Array; - new(length: number): Uint16Array; - new(array: ArrayLike | ArrayBufferLike): Uint16Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; + new (length: number): Uint16Array; + new (array: ArrayLike | ArrayBufferLike): Uint16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -3264,8 +3264,6 @@ interface Uint16ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint16Array; - - } declare var Uint16Array: Uint16ArrayConstructor; /** @@ -3518,9 +3516,9 @@ interface Int32Array { interface Int32ArrayConstructor { readonly prototype: Int32Array; - new(length: number): Int32Array; - new(array: ArrayLike | ArrayBufferLike): Int32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; + new (length: number): Int32Array; + new (array: ArrayLike | ArrayBufferLike): Int32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3546,7 +3544,6 @@ interface Int32ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int32Array; - } declare var Int32Array: Int32ArrayConstructor; @@ -3799,9 +3796,9 @@ interface Uint32Array { interface Uint32ArrayConstructor { readonly prototype: Uint32Array; - new(length: number): Uint32Array; - new(array: ArrayLike | ArrayBufferLike): Uint32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; + new (length: number): Uint32Array; + new (array: ArrayLike | ArrayBufferLike): Uint32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3827,7 +3824,6 @@ interface Uint32ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint32Array; - } declare var Uint32Array: Uint32ArrayConstructor; @@ -4081,9 +4077,9 @@ interface Float32Array { interface Float32ArrayConstructor { readonly prototype: Float32Array; - new(length: number): Float32Array; - new(array: ArrayLike | ArrayBufferLike): Float32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; + new (length: number): Float32Array; + new (array: ArrayLike | ArrayBufferLike): Float32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -4109,8 +4105,6 @@ interface Float32ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float32Array; - - } declare var Float32Array: Float32ArrayConstructor; @@ -4364,9 +4358,9 @@ interface Float64Array { interface Float64ArrayConstructor { readonly prototype: Float64Array; - new(length: number): Float64Array; - new(array: ArrayLike | ArrayBufferLike): Float64Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; + new (length: number): Float64Array; + new (array: ArrayLike | ArrayBufferLike): Float64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. @@ -4392,7 +4386,6 @@ interface Float64ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float64Array; - } declare var Float64Array: Float64ArrayConstructor; @@ -4426,7 +4419,7 @@ declare namespace Intl { resolvedOptions(): ResolvedCollatorOptions; } var Collator: { - new(locales?: string | string[], options?: CollatorOptions): Collator; + new (locales?: string | string[], options?: CollatorOptions): Collator; (locales?: string | string[], options?: CollatorOptions): Collator; supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; }; @@ -4462,7 +4455,7 @@ declare namespace Intl { resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { - new(locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; readonly prototype: NumberFormat; @@ -4506,7 +4499,7 @@ declare namespace Intl { resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { - new(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; readonly prototype: DateTimeFormat; diff --git a/cli/tsc/dts/lib.esnext.array.d.ts b/cli/tsc/dts/lib.esnext.array.d.ts index 5bf6612fc6..bcf6fb62cf 100644 --- a/cli/tsc/dts/lib.esnext.array.d.ts +++ b/cli/tsc/dts/lib.esnext.array.d.ts @@ -15,283 +15,6 @@ and limitations under the License. /// -interface Array { - /** Copies and reverses the elements in an array.*/ - toReversed(): T[]; - - /** - * Copies and sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. - * ```ts - * [11,2,22,1].sort((a, b) => a - b) - * ``` - */ - toSorted(compareFn?: (a: T, b: T) => number): T[]; - - /** - * Copies and elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - * @param deleteCount The number of elements to remove. - * @returns An array containing the elements that were deleted. - */ - toSpliced(start: number, deleteCount?: number): T[]; - /** - * Copies and removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - * @param deleteCount The number of elements to remove. - * @param items Elements to insert into the array in place of the deleted elements. - * @returns An array containing the elements that were deleted. - */ - toSpliced(start: number, deleteCount: number, ...items: F[]): (F | T)[]; - - /** - * Copies and replaces the element at the given index with the provided value. - * @param index The zero-based location in the array for which to replace an element. - * @param value Element to insert into the array in place of the replaced element. - */ - with(index: number, value: F): (F | T)[]; - } - -interface ReadonlyArray { - /** Copies and reverses the elements in an array.*/ - toReversed(): T[]; - - /** - * Copies and sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. - * ```ts - * [11,2,22,1].sort((a, b) => a - b) - * ``` - */ - toSorted(compareFn?: (a: T, b: T) => number): T[]; - - /** - * Copies and elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - * @param deleteCount The number of elements to remove. - * @returns An array containing the elements that were deleted. - */ - toSpliced(start: number, deleteCount?: number): T[]; - /** - * Copies and removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - * @param deleteCount The number of elements to remove. - * @param items Elements to insert into the array in place of the deleted elements. - * @returns An array containing the elements that were deleted. - */ - toSpliced(start: number, deleteCount: number, ...items: F[]): (F | T)[]; - - /** - * Copies and replaces the element at the given index with the provided value. - * @param index The zero-based location in the array for which to replace an element. - * @param value Element to insert into the array in place of the replaced element. - */ - with(index: number, value: F): (F | T)[]; -} - -interface Int8Array { - /** Copies and reverses the elements in an array.*/ - toReversed(): Int8Array; - - /** - * Copies and sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending order. - * ```ts - * [11,2,22,1].sort((a, b) => a - b) - * ``` - */ - toSorted(compareFn?: (a: number, b: number) => number): Int8Array; - - with(index: number, value: number): Int8Array; -} - -interface Uint8Array { - /** Copies and reverses the elements in an array.*/ - toReversed(): Uint8Array; - - /** - * Copies and sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending order. - * ```ts - * [11,2,22,1].sort((a, b) => a - b) - * ``` - */ - toSorted(compareFn?: (a: number, b: number) => number): Uint8Array; - - with(index: number, value: number): Uint8Array; -} - -interface Uint8ClampedArray { - /** Copies and reverses the elements in an array.*/ - toReversed(): Uint8ClampedArray; - - /** - * Copies and sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending order. - * ```ts - * [11,2,22,1].sort((a, b) => a - b) - * ``` - */ - toSorted(compareFn?: (a: number, b: number) => number): Uint8ClampedArray; - - with(index: number, value: number): Uint8ClampedArray; -} - - -interface Int16Array { - /** Copies and reverses the elements in an array.*/ - toReversed(): Int16Array; - - /** - * Copies and sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending order. - * ```ts - * [11,2,22,1].sort((a, b) => a - b) - * ``` - */ - toSorted(compareFn?: (a: number, b: number) => number): Int16Array; - - with(index: number, value: number): Int16Array; -} - -interface Uint16Array { - /** Copies and reverses the elements in an array.*/ - toReversed(): Uint16Array; - - /** - * Copies and sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending order. - * ```ts - * [11,2,22,1].sort((a, b) => a - b) - * ``` - */ - toSorted(compareFn?: (a: number, b: number) => number): Uint16Array; - - with(index: number, value: number): Uint16Array; -} - -interface Int32Array { - /** Copies and reverses the elements in an array.*/ - toReversed(): Int32Array; - - /** - * Copies and sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending order. - * ```ts - * [11,2,22,1].sort((a, b) => a - b) - * ``` - */ - toSorted(compareFn?: (a: number, b: number) => number): Int32Array; - - with(index: number, value: number): Int32Array; -} - -interface Uint32Array { - /** Copies and reverses the elements in an array.*/ - toReversed(): Uint32Array; - - /** - * Copies and sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending order. - * ```ts - * [11,2,22,1].sort((a, b) => a - b) - * ``` - */ - toSorted(compareFn?: (a: number, b: number) => number): Uint32Array; - - with(index: number, value: number): Uint32Array; -} - -interface Float32Array { - /** Copies and reverses the elements in an array.*/ - toReversed(): Float32Array; - - /** - * Copies and sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending order. - * ```ts - * [11,2,22,1].sort((a, b) => a - b) - * ``` - */ - toSorted(compareFn?: (a: number, b: number) => number): Float32Array; - - with(index: number, value: number): Float32Array; -} - -interface Float64Array { - /** Copies and reverses the elements in an array.*/ - toReversed(): Float64Array; - - /** - * Copies and sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending order. - * ```ts - * [11,2,22,1].sort((a, b) => a - b) - * ``` - */ - toSorted(compareFn?: (a: number, b: number) => number): Float64Array; - - with(index: number, value: number): Float64Array; -} - -interface BigInt64Array { - /** Copies and reverses the elements in an array.*/ - toReversed(): BigInt64Array; - - /** - * Copies and sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending order. - * ```ts - * [11,2,22,1].sort((a, b) => a - b) - * ``` - */ - toSorted(compareFn?: (a: bigint, b: bigint) => number | bigint): BigInt64Array; - - with(index: number, value: number): BigInt64Array; -} - -interface BigUint64Array { - /** Copies and reverses the elements in an array.*/ - toReversed(): BigUint64Array; - - /** - * Copies and sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending order. - * ```ts - * [11,2,22,1].sort((a, b) => a - b) - * ``` - */ - toSorted(compareFn?: (a: bigint, b: bigint) => number | bigint): BigUint64Array; - - with(index: number, value: number): BigUint64Array; -} - // NOTE(bartlomieju): taken from https://github.com/microsoft/TypeScript/issues/50803#issuecomment-1249030430 // while we wait for these types to officially ship interface ArrayConstructor { diff --git a/cli/tsc/dts/lib.esnext.disposable.d.ts b/cli/tsc/dts/lib.esnext.disposable.d.ts index 2051e48885..7225dead2f 100644 --- a/cli/tsc/dts/lib.esnext.disposable.d.ts +++ b/cli/tsc/dts/lib.esnext.disposable.d.ts @@ -88,18 +88,18 @@ interface DisposableStack { * constructor() { * // stack will be disposed when exiting constructor for any reason * using stack = new DisposableStack(); - * + * * // get first resource * this.#res1 = stack.use(getResource1()); - * + * * // get second resource. If this fails, both `stack` and `#res1` will be disposed. * this.#res2 = stack.use(getResource2()); - * + * * // all operations succeeded, move resources out of `stack` so that they aren't disposed * // when constructor exits * this.#disposables = stack.move(); * } - * + * * [Symbol.dispose]() { * this.#disposables.dispose(); * } @@ -112,7 +112,7 @@ interface DisposableStack { } interface DisposableStackConstructor { - new(): DisposableStack; + new (): DisposableStack; readonly prototype: DisposableStack; } declare var DisposableStack: DisposableStackConstructor; @@ -155,18 +155,18 @@ interface AsyncDisposableStack { * constructor() { * // stack will be disposed when exiting constructor for any reason * using stack = new DisposableStack(); - * + * * // get first resource * this.#res1 = stack.use(getResource1()); - * + * * // get second resource. If this fails, both `stack` and `#res1` will be disposed. * this.#res2 = stack.use(getResource2()); - * + * * // all operations succeeded, move resources out of `stack` so that they aren't disposed * // when constructor exits * this.#disposables = stack.move(); * } - * + * * [Symbol.dispose]() { * this.#disposables.dispose(); * } @@ -179,7 +179,7 @@ interface AsyncDisposableStack { } interface AsyncDisposableStackConstructor { - new(): AsyncDisposableStack; + new (): AsyncDisposableStack; readonly prototype: AsyncDisposableStack; } declare var AsyncDisposableStack: AsyncDisposableStackConstructor; diff --git a/cli/tsc/dts/lib.esnext.full.d.ts b/cli/tsc/dts/lib.esnext.full.d.ts index d5308f3b89..0e00a37377 100644 --- a/cli/tsc/dts/lib.esnext.full.d.ts +++ b/cli/tsc/dts/lib.esnext.full.d.ts @@ -20,4 +20,4 @@ and limitations under the License. /// /// /// -/// \ No newline at end of file +/// diff --git a/cli/tsc/dts/lib.esnext.intl.d.ts b/cli/tsc/dts/lib.esnext.intl.d.ts index 4f1cee2f54..c02e8b8160 100644 --- a/cli/tsc/dts/lib.esnext.intl.d.ts +++ b/cli/tsc/dts/lib.esnext.intl.d.ts @@ -17,12 +17,12 @@ and limitations under the License. /// declare namespace Intl { - interface NumberRangeFormatPart extends NumberFormatPart { - source: "startRange" | "endRange" | "shared" - } + interface NumberRangeFormatPart extends NumberFormatPart { + source: "startRange" | "endRange" | "shared"; + } - interface NumberFormat { - formatRange(start: number | bigint, end: number | bigint): string; - formatRangeToParts(start: number | bigint, end: number | bigint): NumberRangeFormatPart[]; - } + interface NumberFormat { + formatRange(start: number | bigint, end: number | bigint): string; + formatRangeToParts(start: number | bigint, end: number | bigint): NumberRangeFormatPart[]; + } } diff --git a/cli/tsc/dts/lib.scripthost.d.ts b/cli/tsc/dts/lib.scripthost.d.ts index 14cebb5314..b2364b58fa 100644 --- a/cli/tsc/dts/lib.scripthost.d.ts +++ b/cli/tsc/dts/lib.scripthost.d.ts @@ -16,13 +16,10 @@ and limitations under the License. /// - - ///////////////////////////// /// Windows Script Host APIS ///////////////////////////// - interface ActiveXObject { new (s: string): any; } @@ -262,7 +259,7 @@ interface Enumerator { interface EnumeratorConstructor { new (safearray: SafeArray): Enumerator; - new (collection: { Item(index: any): T }): Enumerator; + new (collection: { Item(index: any): T; }): Enumerator; new (collection: any): Enumerator; } diff --git a/cli/tsc/dts/lib.webworker.d.ts b/cli/tsc/dts/lib.webworker.d.ts index b98cf20163..82f0b0b308 100644 --- a/cli/tsc/dts/lib.webworker.d.ts +++ b/cli/tsc/dts/lib.webworker.d.ts @@ -2628,7 +2628,7 @@ interface EventTarget { */ addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: AddEventListenerOptions | boolean): void; /** - * Dispatches a synthetic event to event target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) */ @@ -5340,7 +5340,9 @@ interface SubtleCrypto { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) */ exportKey(format: "jwk", key: CryptoKey): Promise; exportKey(format: Exclude, key: CryptoKey): Promise; + exportKey(format: KeyFormat, key: CryptoKey): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey(algorithm: "Ed25519", extractable: boolean, keyUsages: ReadonlyArray<"sign" | "verify">): Promise; generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: ReadonlyArray): Promise; generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: ReadonlyArray): Promise; generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): Promise; @@ -9098,7 +9100,7 @@ declare function close(): void; declare function postMessage(message: any, transfer: Transferable[]): void; declare function postMessage(message: any, options?: StructuredSerializeOptions): void; /** - * Dispatches a synthetic event to event target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) */ @@ -9138,7 +9140,7 @@ declare var self: WorkerGlobalScope & typeof globalThis; */ declare function importScripts(...urls: (string | URL)[]): void; /** - * Dispatches a synthetic event to event target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) */ diff --git a/cli/tsc/dts/lib.webworker.importscripts.d.ts b/cli/tsc/dts/lib.webworker.importscripts.d.ts index 5ca328c567..4d88c831b4 100644 --- a/cli/tsc/dts/lib.webworker.importscripts.d.ts +++ b/cli/tsc/dts/lib.webworker.importscripts.d.ts @@ -16,7 +16,6 @@ and limitations under the License. /// - ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// diff --git a/cli/tsc/dts/typescript.d.ts b/cli/tsc/dts/typescript.d.ts index ed93d0290e..7cb761a391 100644 --- a/cli/tsc/dts/typescript.d.ts +++ b/cli/tsc/dts/typescript.d.ts @@ -14,11 +14,4129 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { + namespace server { + type ActionSet = "action::set"; + type ActionInvalidate = "action::invalidate"; + type ActionPackageInstalled = "action::packageInstalled"; + type EventTypesRegistry = "event::typesRegistry"; + type EventBeginInstallTypes = "event::beginInstallTypes"; + type EventEndInstallTypes = "event::endInstallTypes"; + type EventInitializationFailed = "event::initializationFailed"; + type ActionWatchTypingLocations = "action::watchTypingLocations"; + interface TypingInstallerResponse { + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed | ActionWatchTypingLocations; + } + interface TypingInstallerRequestWithProjectName { + readonly projectName: string; + } + interface DiscoverTypings extends TypingInstallerRequestWithProjectName { + readonly fileNames: string[]; + readonly projectRootPath: Path; + readonly compilerOptions: CompilerOptions; + readonly typeAcquisition: TypeAcquisition; + readonly unresolvedImports: SortedReadonlyArray; + readonly cachePath?: string; + readonly kind: "discover"; + } + interface CloseProject extends TypingInstallerRequestWithProjectName { + readonly kind: "closeProject"; + } + interface TypesRegistryRequest { + readonly kind: "typesRegistry"; + } + interface InstallPackageRequest extends TypingInstallerRequestWithProjectName { + readonly kind: "installPackage"; + readonly fileName: Path; + readonly packageName: string; + readonly projectRootPath: Path; + } + interface PackageInstalledResponse extends ProjectResponse { + readonly kind: ActionPackageInstalled; + readonly success: boolean; + readonly message: string; + } + interface InitializationFailedResponse extends TypingInstallerResponse { + readonly kind: EventInitializationFailed; + readonly message: string; + readonly stack?: string; + } + interface ProjectResponse extends TypingInstallerResponse { + readonly projectName: string; + } + interface InvalidateCachedTypings extends ProjectResponse { + readonly kind: ActionInvalidate; + } + interface InstallTypes extends ProjectResponse { + readonly kind: EventBeginInstallTypes | EventEndInstallTypes; + readonly eventId: number; + readonly typingsInstallerVersion: string; + readonly packagesToInstall: readonly string[]; + } + interface BeginInstallTypes extends InstallTypes { + readonly kind: EventBeginInstallTypes; + } + interface EndInstallTypes extends InstallTypes { + readonly kind: EventEndInstallTypes; + readonly installSuccess: boolean; + } + interface InstallTypingHost extends JsTyping.TypingResolutionHost { + useCaseSensitiveFileNames: boolean; + writeFile(path: string, content: string): void; + createDirectory(path: string): void; + getCurrentDirectory?(): string; + } + interface SetTypings extends ProjectResponse { + readonly typeAcquisition: TypeAcquisition; + readonly compilerOptions: CompilerOptions; + readonly typings: string[]; + readonly unresolvedImports: SortedReadonlyArray; + readonly kind: ActionSet; + } + interface WatchTypingLocations extends ProjectResponse { + /** if files is undefined, retain same set of watchers */ + readonly files: readonly string[] | undefined; + readonly kind: ActionWatchTypingLocations; + } + namespace protocol { + enum CommandTypes { + JsxClosingTag = "jsxClosingTag", + LinkedEditingRange = "linkedEditingRange", + Brace = "brace", + BraceCompletion = "braceCompletion", + GetSpanOfEnclosingComment = "getSpanOfEnclosingComment", + Change = "change", + Close = "close", + /** @deprecated Prefer CompletionInfo -- see comment on CompletionsResponse */ + Completions = "completions", + CompletionInfo = "completionInfo", + CompletionDetails = "completionEntryDetails", + CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList", + CompileOnSaveEmitFile = "compileOnSaveEmitFile", + Configure = "configure", + Definition = "definition", + DefinitionAndBoundSpan = "definitionAndBoundSpan", + Implementation = "implementation", + Exit = "exit", + FileReferences = "fileReferences", + Format = "format", + Formatonkey = "formatonkey", + Geterr = "geterr", + GeterrForProject = "geterrForProject", + SemanticDiagnosticsSync = "semanticDiagnosticsSync", + SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", + SuggestionDiagnosticsSync = "suggestionDiagnosticsSync", + NavBar = "navbar", + Navto = "navto", + NavTree = "navtree", + NavTreeFull = "navtree-full", + DocumentHighlights = "documentHighlights", + Open = "open", + Quickinfo = "quickinfo", + References = "references", + Reload = "reload", + Rename = "rename", + Saveto = "saveto", + SignatureHelp = "signatureHelp", + FindSourceDefinition = "findSourceDefinition", + Status = "status", + TypeDefinition = "typeDefinition", + ProjectInfo = "projectInfo", + ReloadProjects = "reloadProjects", + Unknown = "unknown", + OpenExternalProject = "openExternalProject", + OpenExternalProjects = "openExternalProjects", + CloseExternalProject = "closeExternalProject", + UpdateOpen = "updateOpen", + GetOutliningSpans = "getOutliningSpans", + TodoComments = "todoComments", + Indentation = "indentation", + DocCommentTemplate = "docCommentTemplate", + CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", + GetCodeFixes = "getCodeFixes", + GetCombinedCodeFix = "getCombinedCodeFix", + ApplyCodeActionCommand = "applyCodeActionCommand", + GetSupportedCodeFixes = "getSupportedCodeFixes", + GetApplicableRefactors = "getApplicableRefactors", + GetEditsForRefactor = "getEditsForRefactor", + GetMoveToRefactoringFileSuggestions = "getMoveToRefactoringFileSuggestions", + OrganizeImports = "organizeImports", + GetEditsForFileRename = "getEditsForFileRename", + ConfigurePlugin = "configurePlugin", + SelectionRange = "selectionRange", + ToggleLineComment = "toggleLineComment", + ToggleMultilineComment = "toggleMultilineComment", + CommentSelection = "commentSelection", + UncommentSelection = "uncommentSelection", + PrepareCallHierarchy = "prepareCallHierarchy", + ProvideCallHierarchyIncomingCalls = "provideCallHierarchyIncomingCalls", + ProvideCallHierarchyOutgoingCalls = "provideCallHierarchyOutgoingCalls", + ProvideInlayHints = "provideInlayHints", + WatchChange = "watchChange", + } + /** + * A TypeScript Server message + */ + interface Message { + /** + * Sequence number of the message + */ + seq: number; + /** + * One of "request", "response", or "event" + */ + type: "request" | "response" | "event"; + } + /** + * Client-initiated request message + */ + interface Request extends Message { + type: "request"; + /** + * The command to execute + */ + command: string; + /** + * Object containing arguments for the command + */ + arguments?: any; + } + /** + * Request to reload the project structure for all the opened files + */ + interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; + } + /** + * Server-initiated event message + */ + interface Event extends Message { + type: "event"; + /** + * Name of event + */ + event: string; + /** + * Event-specific information + */ + body?: any; + } + /** + * Response by server to client request message. + */ + interface Response extends Message { + type: "response"; + /** + * Sequence number of the request message. + */ + request_seq: number; + /** + * Outcome of the request. + */ + success: boolean; + /** + * The command requested. + */ + command: string; + /** + * If success === false, this should always be provided. + * Otherwise, may (or may not) contain a success message. + */ + message?: string; + /** + * Contains message body if success === true. + */ + body?: any; + /** + * Contains extra information that plugin can include to be passed on + */ + metadata?: unknown; + /** + * Exposes information about the performance of this request-response pair. + */ + performanceData?: PerformanceData; + } + interface PerformanceData { + /** + * Time spent updating the program graph, in milliseconds. + */ + updateGraphDurationMs?: number; + /** + * The time spent creating or updating the auto-import program, in milliseconds. + */ + createAutoImportProviderProgramDurationMs?: number; + } + /** + * Arguments for FileRequest messages. + */ + interface FileRequestArgs { + /** + * The file for the request (absolute pathname required). + */ + file: string; + projectFileName?: string; + } + interface StatusRequest extends Request { + command: CommandTypes.Status; + } + interface StatusResponseBody { + /** + * The TypeScript version (`ts.version`). + */ + version: string; + } + /** + * Response to StatusRequest + */ + interface StatusResponse extends Response { + body: StatusResponseBody; + } + /** + * Requests a JS Doc comment template for a given position + */ + interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + /** + * Response to DocCommentTemplateRequest + */ + interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + /** + * A request to get TODO comments from the file + */ + interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; + arguments: TodoCommentRequestArgs; + } + /** + * Arguments for TodoCommentRequest request. + */ + interface TodoCommentRequestArgs extends FileRequestArgs { + /** + * Array of target TodoCommentDescriptors that describes TODO comments to be found + */ + descriptors: TodoCommentDescriptor[]; + } + /** + * Response for TodoCommentRequest request. + */ + interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + /** + * A request to determine if the caret is inside a comment. + */ + interface SpanOfEnclosingCommentRequest extends FileLocationRequest { + command: CommandTypes.GetSpanOfEnclosingComment; + arguments: SpanOfEnclosingCommentRequestArgs; + } + interface SpanOfEnclosingCommentRequestArgs extends FileLocationRequestArgs { + /** + * Requires that the enclosing span be a multi-line comment, or else the request returns undefined. + */ + onlyMultiLine: boolean; + } + /** + * Request to obtain outlining spans in file. + */ + interface OutliningSpansRequest extends FileRequest { + command: CommandTypes.GetOutliningSpans; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + /** + * Classification of the contents of the span + */ + kind: OutliningSpanKind; + } + /** + * Response to OutliningSpansRequest request. + */ + interface OutliningSpansResponse extends Response { + body?: OutliningSpan[]; + } + /** + * A request to get indentation for a location in file + */ + interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; + arguments: IndentationRequestArgs; + } + /** + * Response for IndentationRequest request. + */ + interface IndentationResponse extends Response { + body?: IndentationResult; + } + /** + * Indentation result representing where indentation should be placed + */ + interface IndentationResult { + /** + * The base position in the document that the indent should be relative to + */ + position: number; + /** + * The number of columns the indent should be at relative to the position's column. + */ + indentation: number; + } + /** + * Arguments for IndentationRequest request. + */ + interface IndentationRequestArgs extends FileLocationRequestArgs { + /** + * An optional set of settings to be used when computing indentation. + * If argument is omitted - then it will use settings for file that were previously set via 'configure' request or global settings. + */ + options?: EditorSettings; + } + /** + * Arguments for ProjectInfoRequest request. + */ + interface ProjectInfoRequestArgs extends FileRequestArgs { + /** + * Indicate if the file name list of the project is needed + */ + needFileNameList: boolean; + } + /** + * A request to get the project information of the current file. + */ + interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; + arguments: ProjectInfoRequestArgs; + } + /** + * A request to retrieve compiler options diagnostics for a project + */ + interface CompilerOptionsDiagnosticsRequest extends Request { + arguments: CompilerOptionsDiagnosticsRequestArgs; + } + /** + * Arguments for CompilerOptionsDiagnosticsRequest request. + */ + interface CompilerOptionsDiagnosticsRequestArgs { + /** + * Name of the project to retrieve compiler options diagnostics. + */ + projectFileName: string; + } + /** + * Response message body for "projectInfo" request + */ + interface ProjectInfo { + /** + * For configured project, this is the normalized path of the 'tsconfig.json' file + * For inferred project, this is undefined + */ + configFileName: string; + /** + * The list of normalized file name in the project, including 'lib.d.ts' + */ + fileNames?: string[]; + /** + * Indicates if the project has a active language service instance + */ + languageServiceDisabled?: boolean; + } + /** + * Represents diagnostic info that includes location of diagnostic in two forms + * - start position and length of the error span + * - startLocation and endLocation - a pair of Location objects that store start/end line and offset of the error span. + */ + interface DiagnosticWithLinePosition { + message: string; + start: number; + length: number; + startLocation: Location; + endLocation: Location; + category: string; + code: number; + /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ + reportsUnnecessary?: {}; + reportsDeprecated?: {}; + relatedInformation?: DiagnosticRelatedInformation[]; + } + /** + * Response message for "projectInfo" request + */ + interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + /** + * Request whose sole parameter is a file name. + */ + interface FileRequest extends Request { + arguments: FileRequestArgs; + } + /** + * Instances of this interface specify a location in a source file: + * (file, line, character offset), where line and character offset are 1-based. + */ + interface FileLocationRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + line: number; + /** + * The character offset (on the line) for the request (1-based). + */ + offset: number; + } + type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + /** + * Request refactorings at a given position or selection area. + */ + interface GetApplicableRefactorsRequest extends Request { + command: CommandTypes.GetApplicableRefactors; + arguments: GetApplicableRefactorsRequestArgs; + } + type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs & { + triggerReason?: RefactorTriggerReason; + kind?: string; + /** + * Include refactor actions that require additional arguments to be passed when + * calling 'GetEditsForRefactor'. When true, clients should inspect the + * `isInteractive` property of each returned `RefactorActionInfo` + * and ensure they are able to collect the appropriate arguments for any + * interactive refactor before offering it. + */ + includeInteractiveActions?: boolean; + }; + type RefactorTriggerReason = "implicit" | "invoked"; + /** + * Response is a list of available refactorings. + * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring + */ + interface GetApplicableRefactorsResponse extends Response { + body?: ApplicableRefactorInfo[]; + } + /** + * Request refactorings at a given position or selection area to move to an existing file. + */ + interface GetMoveToRefactoringFileSuggestionsRequest extends Request { + command: CommandTypes.GetMoveToRefactoringFileSuggestions; + arguments: GetMoveToRefactoringFileSuggestionsRequestArgs; + } + type GetMoveToRefactoringFileSuggestionsRequestArgs = FileLocationOrRangeRequestArgs & { + kind?: string; + }; + /** + * Response is a list of available files. + * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring + */ + interface GetMoveToRefactoringFileSuggestions extends Response { + body: { + newFileName: string; + files: string[]; + }; + } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ + interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ + name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ + description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ + inlineable?: boolean; + actions: RefactorActionInfo[]; + } + /** + * Represents a single refactoring action - for example, the "Extract Method..." refactor might + * offer several actions, each corresponding to a surround class or closure to extract into. + */ + interface RefactorActionInfo { + /** + * The programmatic name of the refactoring action + */ + name: string; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ + description: string; + /** + * A message to show to the user if the refactoring cannot be applied in + * the current context. + */ + notApplicableReason?: string; + /** + * The hierarchical dotted name of the refactor action. + */ + kind?: string; + /** + * Indicates that the action requires additional arguments to be passed + * when calling 'GetEditsForRefactor'. + */ + isInteractive?: boolean; + } + interface GetEditsForRefactorRequest extends Request { + command: CommandTypes.GetEditsForRefactor; + arguments: GetEditsForRefactorRequestArgs; + } + /** + * Request the edits that a particular refactoring action produces. + * Callers must specify the name of the refactor and the name of the action. + */ + type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { + refactor: string; + action: string; + interactiveRefactorArguments?: InteractiveRefactorArguments; + }; + interface GetEditsForRefactorResponse extends Response { + body?: RefactorEditInfo; + } + interface RefactorEditInfo { + edits: FileCodeEdits[]; + /** + * An optional location where the editor should start a rename operation once + * the refactoring edits have been applied + */ + renameLocation?: Location; + renameFilename?: string; + notApplicableReason?: string; + } + /** + * Organize imports by: + * 1) Removing unused imports + * 2) Coalescing imports from the same module + * 3) Sorting imports + */ + interface OrganizeImportsRequest extends Request { + command: CommandTypes.OrganizeImports; + arguments: OrganizeImportsRequestArgs; + } + type OrganizeImportsScope = GetCombinedCodeFixScope; + enum OrganizeImportsMode { + All = "All", + SortAndCombine = "SortAndCombine", + RemoveUnused = "RemoveUnused", + } + interface OrganizeImportsRequestArgs { + scope: OrganizeImportsScope; + /** @deprecated Use `mode` instead */ + skipDestructiveCodeActions?: boolean; + mode?: OrganizeImportsMode; + } + interface OrganizeImportsResponse extends Response { + body: readonly FileCodeEdits[]; + } + interface GetEditsForFileRenameRequest extends Request { + command: CommandTypes.GetEditsForFileRename; + arguments: GetEditsForFileRenameRequestArgs; + } + /** Note: Paths may also be directories. */ + interface GetEditsForFileRenameRequestArgs { + readonly oldFilePath: string; + readonly newFilePath: string; + } + interface GetEditsForFileRenameResponse extends Response { + body: readonly FileCodeEdits[]; + } + /** + * Request for the available codefixes at a specific position. + */ + interface CodeFixRequest extends Request { + command: CommandTypes.GetCodeFixes; + arguments: CodeFixRequestArgs; + } + interface GetCombinedCodeFixRequest extends Request { + command: CommandTypes.GetCombinedCodeFix; + arguments: GetCombinedCodeFixRequestArgs; + } + interface GetCombinedCodeFixResponse extends Response { + body: CombinedCodeActions; + } + interface ApplyCodeActionCommandRequest extends Request { + command: CommandTypes.ApplyCodeActionCommand; + arguments: ApplyCodeActionCommandRequestArgs; + } + interface ApplyCodeActionCommandResponse extends Response { + } + interface FileRangeRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + startLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + startOffset: number; + /** + * The line number for the request (1-based). + */ + endLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + endOffset: number; + } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ + interface CodeFixRequestArgs extends FileRangeRequestArgs { + /** + * Errorcodes we want to get the fixes for. + */ + errorCodes: readonly number[]; + } + interface GetCombinedCodeFixRequestArgs { + scope: GetCombinedCodeFixScope; + fixId: {}; + } + interface GetCombinedCodeFixScope { + type: "file"; + args: FileRequestArgs; + } + interface ApplyCodeActionCommandRequestArgs { + /** May also be an array of commands. */ + command: {}; + } + /** + * Response for GetCodeFixes request. + */ + interface GetCodeFixesResponse extends Response { + body?: CodeAction[]; + } + /** + * A request whose arguments specify a file location (file, line, col). + */ + interface FileLocationRequest extends FileRequest { + arguments: FileLocationRequestArgs; + } + /** + * A request to get codes of supported code fixes. + */ + interface GetSupportedCodeFixesRequest extends Request { + command: CommandTypes.GetSupportedCodeFixes; + arguments?: Partial; + } + /** + * A response for GetSupportedCodeFixesRequest request. + */ + interface GetSupportedCodeFixesResponse extends Response { + /** + * List of error codes supported by the server. + */ + body?: string[]; + } + /** + * A request to get encoded semantic classifications for a span in the file + */ + interface EncodedSemanticClassificationsRequest extends FileRequest { + arguments: EncodedSemanticClassificationsRequestArgs; + } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + /** + * Optional parameter for the semantic highlighting response, if absent it + * defaults to "original". + */ + format?: "original" | "2020"; + } + /** The response for a EncodedSemanticClassificationsRequest */ + interface EncodedSemanticClassificationsResponse extends Response { + body?: EncodedSemanticClassificationsResponseBody; + } + /** + * Implementation response message. Gives series of text spans depending on the format ar. + */ + interface EncodedSemanticClassificationsResponseBody { + endOfLineState: EndOfLineState; + spans: number[]; + } + /** + * Arguments in document highlight request; include: filesToSearch, file, + * line, offset. + */ + interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + /** + * List of files to search for document highlights. + */ + filesToSearch: string[]; + } + /** + * Go to definition request; value of command field is + * "definition". Return response giving the file locations that + * define the symbol found in file at location line, col. + */ + interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; + } + interface DefinitionAndBoundSpanRequest extends FileLocationRequest { + readonly command: CommandTypes.DefinitionAndBoundSpan; + } + interface FindSourceDefinitionRequest extends FileLocationRequest { + readonly command: CommandTypes.FindSourceDefinition; + } + interface DefinitionAndBoundSpanResponse extends Response { + readonly body: DefinitionInfoAndBoundSpan; + } + /** + * Go to type request; value of command field is + * "typeDefinition". Return response giving the file locations that + * define the type for the symbol found in file at location line, col. + */ + interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; + } + /** + * Go to implementation request; value of command field is + * "implementation". Return response giving the file locations that + * implement the symbol found in file at location line, col. + */ + interface ImplementationRequest extends FileLocationRequest { + command: CommandTypes.Implementation; + } + /** + * Location in source code expressed as (one-based) line and (one-based) column offset. + */ + interface Location { + line: number; + offset: number; + } + /** + * Object found in response messages defining a span of text in source code. + */ + interface TextSpan { + /** + * First character of the definition. + */ + start: Location; + /** + * One character past last character of the definition. + */ + end: Location; + } + /** + * Object found in response messages defining a span of text in a specific source file. + */ + interface FileSpan extends TextSpan { + /** + * File containing text span. + */ + file: string; + } + interface JSDocTagInfo { + /** Name of the JSDoc tag */ + name: string; + /** + * Comment text after the JSDoc tag -- the text after the tag name until the next tag or end of comment + * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. + */ + text?: string | SymbolDisplayPart[]; + } + interface TextSpanWithContext extends TextSpan { + contextStart?: Location; + contextEnd?: Location; + } + interface FileSpanWithContext extends FileSpan, TextSpanWithContext { + } + interface DefinitionInfo extends FileSpanWithContext { + /** + * When true, the file may or may not exist. + */ + unverified?: boolean; + } + interface DefinitionInfoAndBoundSpan { + definitions: readonly DefinitionInfo[]; + textSpan: TextSpan; + } + /** + * Definition response message. Gives text range for definition. + */ + interface DefinitionResponse extends Response { + body?: DefinitionInfo[]; + } + interface DefinitionInfoAndBoundSpanResponse extends Response { + body?: DefinitionInfoAndBoundSpan; + } + /** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */ + type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse; + /** + * Definition response message. Gives text range for definition. + */ + interface TypeDefinitionResponse extends Response { + body?: FileSpanWithContext[]; + } + /** + * Implementation response message. Gives text range for implementations. + */ + interface ImplementationResponse extends Response { + body?: FileSpanWithContext[]; + } + /** + * Request to get brace completion for a location in the file. + */ + interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; + arguments: BraceCompletionRequestArgs; + } + /** + * Argument for BraceCompletionRequest request. + */ + interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + /** + * Kind of opening brace + */ + openingBrace: string; + } + interface JsxClosingTagRequest extends FileLocationRequest { + readonly command: CommandTypes.JsxClosingTag; + readonly arguments: JsxClosingTagRequestArgs; + } + interface JsxClosingTagRequestArgs extends FileLocationRequestArgs { + } + interface JsxClosingTagResponse extends Response { + readonly body: TextInsertion; + } + interface LinkedEditingRangeRequest extends FileLocationRequest { + readonly command: CommandTypes.LinkedEditingRange; + } + interface LinkedEditingRangesBody { + ranges: TextSpan[]; + wordPattern?: string; + } + interface LinkedEditingRangeResponse extends Response { + readonly body: LinkedEditingRangesBody; + } + /** + * Get document highlights request; value of command field is + * "documentHighlights". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; + arguments: DocumentHighlightsRequestArgs; + } + /** + * Span augmented with extra information that denotes the kind of the highlighting to be used for span. + */ + interface HighlightSpan extends TextSpanWithContext { + kind: HighlightSpanKind; + } + /** + * Represents a set of highligh spans for a give name + */ + interface DocumentHighlightsItem { + /** + * File containing highlight spans. + */ + file: string; + /** + * Spans to highlight in file. + */ + highlightSpans: HighlightSpan[]; + } + /** + * Response for a DocumentHighlightsRequest request. + */ + interface DocumentHighlightsResponse extends Response { + body?: DocumentHighlightsItem[]; + } + /** + * Find references request; value of command field is + * "references". Return response giving the file locations that + * reference the symbol found in file at location line, col. + */ + interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; + } + interface ReferencesResponseItem extends FileSpanWithContext { + /** + * Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has loaded the referencing files). + * + * If {@link UserPreferences.disableLineTextInReferences} is enabled, the property won't be filled + */ + lineText?: string; + /** + * True if reference is a write location, false otherwise. + */ + isWriteAccess: boolean; + /** + * Present only if the search was triggered from a declaration. + * True indicates that the references refers to the same symbol + * (i.e. has the same meaning) as the declaration that began the + * search. + */ + isDefinition?: boolean; + } + /** + * The body of a "references" response message. + */ + interface ReferencesResponseBody { + /** + * The file locations referencing the symbol. + */ + refs: readonly ReferencesResponseItem[]; + /** + * The name of the symbol. + */ + symbolName: string; + /** + * The start character offset of the symbol (on the line provided by the references request). + */ + symbolStartOffset: number; + /** + * The full display name of the symbol. + */ + symbolDisplayString: string; + } + /** + * Response to "references" request. + */ + interface ReferencesResponse extends Response { + body?: ReferencesResponseBody; + } + interface FileReferencesRequest extends FileRequest { + command: CommandTypes.FileReferences; + } + interface FileReferencesResponseBody { + /** + * The file locations referencing the symbol. + */ + refs: readonly ReferencesResponseItem[]; + /** + * The name of the symbol. + */ + symbolName: string; + } + interface FileReferencesResponse extends Response { + body?: FileReferencesResponseBody; + } + /** + * Argument for RenameRequest request. + */ + interface RenameRequestArgs extends FileLocationRequestArgs { + /** + * Should text at specified location be found/changed in comments? + */ + findInComments?: boolean; + /** + * Should text at specified location be found/changed in strings? + */ + findInStrings?: boolean; + } + /** + * Rename request; value of command field is "rename". Return + * response giving the file locations that reference the symbol + * found in file at location line, col. Also return full display + * name of the symbol so that client can print it unambiguously. + */ + interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; + arguments: RenameRequestArgs; + } + /** + * Information about the item to be renamed. + */ + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + /** + * True if item can be renamed. + */ + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; + /** + * Display name of the item to be renamed. + */ + displayName: string; + /** + * Full display name of item to be renamed. + */ + fullDisplayName: string; + /** + * The items's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** Span of text to rename. */ + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage: string; + } + /** + * A group of text spans, all in 'file'. + */ + interface SpanGroup { + /** The file to which the spans apply */ + file: string; + /** The text spans in this group */ + locs: RenameTextSpan[]; + } + interface RenameTextSpan extends TextSpanWithContext { + readonly prefixText?: string; + readonly suffixText?: string; + } + interface RenameResponseBody { + /** + * Information about the item to be renamed. + */ + info: RenameInfo; + /** + * An array of span groups (one per file) that refer to the item to be renamed. + */ + locs: readonly SpanGroup[]; + } + /** + * Rename response message. + */ + interface RenameResponse extends Response { + body?: RenameResponseBody; + } + /** + * Represents a file in external project. + * External project is project whose set of files, compilation options and open\close state + * is maintained by the client (i.e. if all this data come from .csproj file in Visual Studio). + * External project will exist even if all files in it are closed and should be closed explicitly. + * If external project includes one or more tsconfig.json/jsconfig.json files then tsserver will + * create configured project for every config file but will maintain a link that these projects were created + * as a result of opening external project so they should be removed once external project is closed. + */ + interface ExternalFile { + /** + * Name of file file + */ + fileName: string; + /** + * Script kind of the file + */ + scriptKind?: ScriptKindName | ScriptKind; + /** + * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) + */ + hasMixedContent?: boolean; + /** + * Content of the file + */ + content?: string; + } + /** + * Represent an external project + */ + interface ExternalProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of root files in project + */ + rootFiles: ExternalFile[]; + /** + * Compiler options for the project + */ + options: ExternalProjectCompilerOptions; + /** + * Explicitly specified type acquisition for the project + */ + typeAcquisition?: TypeAcquisition; + } + interface CompileOnSaveMixin { + /** + * If compile on save is enabled for the project + */ + compileOnSave?: boolean; + } + /** + * For external projects, some of the project settings are sent together with + * compiler settings. + */ + type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin & WatchOptions; + interface FileWithProjectReferenceRedirectInfo { + /** + * Name of file + */ + fileName: string; + /** + * True if the file is primarily included in a referenced project + */ + isSourceOfProjectReferenceRedirect: boolean; + } + /** + * Represents a set of changes that happen in project + */ + interface ProjectChanges { + /** + * List of added files + */ + added: string[] | FileWithProjectReferenceRedirectInfo[]; + /** + * List of removed files + */ + removed: string[] | FileWithProjectReferenceRedirectInfo[]; + /** + * List of updated files + */ + updated: string[] | FileWithProjectReferenceRedirectInfo[]; + /** + * List of files that have had their project reference redirect status updated + * Only provided when the synchronizeProjectList request has includeProjectReferenceRedirectInfo set to true + */ + updatedRedirects?: FileWithProjectReferenceRedirectInfo[]; + } + /** + * Information found in a configure request. + */ + interface ConfigureRequestArguments { + /** + * Information about the host, for example 'Emacs 24.4' or + * 'Sublime Text version 3075' + */ + hostInfo?: string; + /** + * If present, tab settings apply only to this file. + */ + file?: string; + /** + * The format options to use during formatting and other code editing features. + */ + formatOptions?: FormatCodeSettings; + preferences?: UserPreferences; + /** + * The host's additional supported .js file extensions + */ + extraFileExtensions?: FileExtensionInfo[]; + watchOptions?: WatchOptions; + } + enum WatchFileKind { + FixedPollingInterval = "FixedPollingInterval", + PriorityPollingInterval = "PriorityPollingInterval", + DynamicPriorityPolling = "DynamicPriorityPolling", + FixedChunkSizePolling = "FixedChunkSizePolling", + UseFsEvents = "UseFsEvents", + UseFsEventsOnParentDirectory = "UseFsEventsOnParentDirectory", + } + enum WatchDirectoryKind { + UseFsEvents = "UseFsEvents", + FixedPollingInterval = "FixedPollingInterval", + DynamicPriorityPolling = "DynamicPriorityPolling", + FixedChunkSizePolling = "FixedChunkSizePolling", + } + enum PollingWatchKind { + FixedInterval = "FixedInterval", + PriorityInterval = "PriorityInterval", + DynamicPriority = "DynamicPriority", + FixedChunkSize = "FixedChunkSize", + } + interface WatchOptions { + watchFile?: WatchFileKind | ts.WatchFileKind; + watchDirectory?: WatchDirectoryKind | ts.WatchDirectoryKind; + fallbackPolling?: PollingWatchKind | ts.PollingWatchKind; + synchronousWatchDirectory?: boolean; + excludeDirectories?: string[]; + excludeFiles?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + /** + * Configure request; value of command field is "configure". Specifies + * host information, such as host type, tab size, and indent size. + */ + interface ConfigureRequest extends Request { + command: CommandTypes.Configure; + arguments: ConfigureRequestArguments; + } + /** + * Response to "configure" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ConfigureResponse extends Response { + } + interface ConfigurePluginRequestArguments { + pluginName: string; + configuration: any; + } + interface ConfigurePluginRequest extends Request { + command: CommandTypes.ConfigurePlugin; + arguments: ConfigurePluginRequestArguments; + } + interface ConfigurePluginResponse extends Response { + } + interface SelectionRangeRequest extends FileRequest { + command: CommandTypes.SelectionRange; + arguments: SelectionRangeRequestArgs; + } + interface SelectionRangeRequestArgs extends FileRequestArgs { + locations: Location[]; + } + interface SelectionRangeResponse extends Response { + body?: SelectionRange[]; + } + interface SelectionRange { + textSpan: TextSpan; + parent?: SelectionRange; + } + interface ToggleLineCommentRequest extends FileRequest { + command: CommandTypes.ToggleLineComment; + arguments: FileRangeRequestArgs; + } + interface ToggleMultilineCommentRequest extends FileRequest { + command: CommandTypes.ToggleMultilineComment; + arguments: FileRangeRequestArgs; + } + interface CommentSelectionRequest extends FileRequest { + command: CommandTypes.CommentSelection; + arguments: FileRangeRequestArgs; + } + interface UncommentSelectionRequest extends FileRequest { + command: CommandTypes.UncommentSelection; + arguments: FileRangeRequestArgs; + } + /** + * Information found in an "open" request. + */ + interface OpenRequestArgs extends FileRequestArgs { + /** + * Used when a version of the file content is known to be more up to date than the one on disk. + * Then the known content will be used upon opening instead of the disk copy + */ + fileContent?: string; + /** + * Used to specify the script kind of the file explicitly. It could be one of the following: + * "TS", "JS", "TSX", "JSX" + */ + scriptKindName?: ScriptKindName; + /** + * Used to limit the searching for project config file. If given the searching will stop at this + * root path; otherwise it will go all the way up to the dist root path. + */ + projectRootPath?: string; + } + type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; + /** + * Open request; value of command field is "open". Notify the + * server that the client has file open. The server will not + * monitor the filesystem for changes in this file and will assume + * that the client is updating the server (using the change and/or + * reload messages) when the file changes. Server does not currently + * send a response to an open request. + */ + interface OpenRequest extends Request { + command: CommandTypes.Open; + arguments: OpenRequestArgs; + } + /** + * Request to open or update external project + */ + interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; + arguments: OpenExternalProjectArgs; + } + /** + * Arguments to OpenExternalProjectRequest request + */ + type OpenExternalProjectArgs = ExternalProject; + /** + * Request to open multiple external projects + */ + interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; + arguments: OpenExternalProjectsArgs; + } + /** + * Arguments to OpenExternalProjectsRequest + */ + interface OpenExternalProjectsArgs { + /** + * List of external projects to open or update + */ + projects: ExternalProject[]; + } + /** + * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectResponse extends Response { + } + /** + * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectsResponse extends Response { + } + /** + * Request to close external project. + */ + interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; + arguments: CloseExternalProjectRequestArgs; + } + /** + * Arguments to CloseExternalProjectRequest request + */ + interface CloseExternalProjectRequestArgs { + /** + * Name of the project to close + */ + projectFileName: string; + } + /** + * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface CloseExternalProjectResponse extends Response { + } + /** + * Request to synchronize list of open files with the client + */ + interface UpdateOpenRequest extends Request { + command: CommandTypes.UpdateOpen; + arguments: UpdateOpenRequestArgs; + } + /** + * Arguments to UpdateOpenRequest + */ + interface UpdateOpenRequestArgs { + /** + * List of newly open files + */ + openFiles?: OpenRequestArgs[]; + /** + * List of open files files that were changes + */ + changedFiles?: FileCodeEdits[]; + /** + * List of files that were closed + */ + closedFiles?: string[]; + } + /** + * External projects have a typeAcquisition option so they need to be added separately to compiler options for inferred projects. + */ + type InferredProjectCompilerOptions = ExternalProjectCompilerOptions & TypeAcquisition; + /** + * Request to set compiler options for inferred projects. + * External projects are opened / closed explicitly. + * Configured projects are opened when user opens loose file that has 'tsconfig.json' or 'jsconfig.json' anywhere in one of containing folders. + * This configuration file will be used to obtain a list of files and configuration settings for the project. + * Inferred projects are created when user opens a loose file that is not the part of external project + * or configured project and will contain only open file and transitive closure of referenced files if 'useOneInferredProject' is false, + * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. + */ + interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; + arguments: SetCompilerOptionsForInferredProjectsArgs; + } + /** + * Argument for SetCompilerOptionsForInferredProjectsRequest request. + */ + interface SetCompilerOptionsForInferredProjectsArgs { + /** + * Compiler options to be used with inferred projects. + */ + options: InferredProjectCompilerOptions; + /** + * Specifies the project root path used to scope compiler options. + * It is an error to provide this property if the server has not been started with + * `useInferredProjectPerProjectRoot` enabled. + */ + projectRootPath?: string; + } + /** + * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so + * no body field is required. + */ + interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + /** + * Exit request; value of command field is "exit". Ask the server process + * to exit. + */ + interface ExitRequest extends Request { + command: CommandTypes.Exit; + } + /** + * Close request; value of command field is "close". Notify the + * server that the client has closed a previously open file. If + * file is still referenced by open files, the server will resume + * monitoring the filesystem for changes to file. Server does not + * currently send a response to a close request. + */ + interface CloseRequest extends FileRequest { + command: CommandTypes.Close; + } + interface WatchChangeRequest extends Request { + command: CommandTypes.WatchChange; + arguments: WatchChangeRequestArgs; + } + interface WatchChangeRequestArgs { + id: number; + path: string; + eventType: "create" | "delete" | "update"; + } + /** + * Request to obtain the list of files that should be regenerated if target file is recompiled. + * NOTE: this us query-only operation and does not generate any output on disk. + */ + interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; + } + /** + * Contains a list of files that should be regenerated in a project + */ + interface CompileOnSaveAffectedFileListSingleProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of files names that should be recompiled + */ + fileNames: string[]; + /** + * true if project uses outFile or out compiler option + */ + projectUsesOutFile: boolean; + } + /** + * Response for CompileOnSaveAffectedFileListRequest request; + */ + interface CompileOnSaveAffectedFileListResponse extends Response { + body: CompileOnSaveAffectedFileListSingleProject[]; + } + /** + * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. + */ + interface CompileOnSaveEmitFileRequest extends FileRequest { + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; + } + /** + * Arguments for CompileOnSaveEmitFileRequest + */ + interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + /** + * if true - then file should be recompiled even if it does not have any changes. + */ + forced?: boolean; + includeLinePosition?: boolean; + /** if true - return response as object with emitSkipped and diagnostics */ + richResponse?: boolean; + } + interface CompileOnSaveEmitFileResponse extends Response { + body: boolean | EmitResult; + } + interface EmitResult { + emitSkipped: boolean; + diagnostics: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Quickinfo request; value of command field is + * "quickinfo". Return response giving a quick type and + * documentation string for the symbol found in file at location + * line, col. + */ + interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; + arguments: FileLocationRequestArgs; + } + /** + * Body of QuickInfoResponse. + */ + interface QuickInfoResponseBody { + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Starting file location of symbol. + */ + start: Location; + /** + * One past last character of symbol. + */ + end: Location; + /** + * Type and kind of symbol. + */ + displayString: string; + /** + * Documentation associated with symbol. + * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. + */ + documentation: string | SymbolDisplayPart[]; + /** + * JSDoc tags associated with symbol. + */ + tags: JSDocTagInfo[]; + } + /** + * Quickinfo response message. + */ + interface QuickInfoResponse extends Response { + body?: QuickInfoResponseBody; + } + /** + * Arguments for format messages. + */ + interface FormatRequestArgs extends FileLocationRequestArgs { + /** + * Last line of range for which to format text in file. + */ + endLine: number; + /** + * Character offset on last line of range for which to format text in file. + */ + endOffset: number; + /** + * Format options to be used. + */ + options?: FormatCodeSettings; + } + /** + * Format request; value of command field is "format". Return + * response giving zero or more edit instructions. The edit + * instructions will be sorted in file order. Applying the edit + * instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; + arguments: FormatRequestArgs; + } + /** + * Object found in response messages defining an editing + * instruction for a span of text in source code. The effect of + * this instruction is to replace the text starting at start and + * ending one character before end with newText. For an insertion, + * the text span is empty. For a deletion, newText is empty. + */ + interface CodeEdit { + /** + * First character of the text span to edit. + */ + start: Location; + /** + * One character past last character of the text span to edit. + */ + end: Location; + /** + * Replace the span defined above with this string (may be + * the empty string). + */ + newText: string; + } + interface FileCodeEdits { + fileName: string; + textChanges: CodeEdit[]; + } + interface CodeFixResponse extends Response { + /** The code actions that are available */ + body?: CodeFixAction[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileCodeEdits[]; + /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ + commands?: {}[]; + } + interface CombinedCodeActions { + changes: readonly FileCodeEdits[]; + commands?: readonly {}[]; + } + interface CodeFixAction extends CodeAction { + /** Short name to identify the fix, for use by telemetry. */ + fixName: string; + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + /** Should be present if and only if 'fixId' is. */ + fixAllDescription?: string; + } + /** + * Format and format on key response message. + */ + interface FormatResponse extends Response { + body?: CodeEdit[]; + } + /** + * Arguments for format on key messages. + */ + interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + /** + * Key pressed (';', '\n', or '}'). + */ + key: string; + options?: FormatCodeSettings; + } + /** + * Format on key request; value of command field is + * "formatonkey". Given file location and key typed (as string), + * return response giving zero or more edit instructions. The + * edit instructions will be sorted in file order. Applying the + * edit instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; + arguments: FormatOnKeyRequestArgs; + } + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; + enum CompletionTriggerKind { + /** Completion was triggered by typing an identifier, manual invocation (e.g Ctrl+Space) or via API. */ + Invoked = 1, + /** Completion was triggered by a trigger character. */ + TriggerCharacter = 2, + /** Completion was re-triggered as the current completion list is incomplete. */ + TriggerForIncompleteCompletions = 3, + } + /** + * Arguments for completions messages. + */ + interface CompletionsRequestArgs extends FileLocationRequestArgs { + /** + * Optional prefix to apply to possible completions. + */ + prefix?: string; + /** + * Character that was responsible for triggering completion. + * Should be `undefined` if a user manually requested completion. + */ + triggerCharacter?: CompletionsTriggerCharacter; + triggerKind?: CompletionTriggerKind; + /** + * @deprecated Use UserPreferences.includeCompletionsForModuleExports + */ + includeExternalModuleExports?: boolean; + /** + * @deprecated Use UserPreferences.includeCompletionsWithInsertText + */ + includeInsertTextCompletions?: boolean; + } + /** + * Completions request; value of command field is "completions". + * Given a file location (file, line, col) and a prefix (which may + * be the empty string), return the possible completions that + * begin with prefix. + */ + interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions | CommandTypes.CompletionInfo; + arguments: CompletionsRequestArgs; + } + /** + * Arguments for completion details request. + */ + interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + /** + * Names of one or more entries for which to obtain details. + */ + entryNames: (string | CompletionEntryIdentifier)[]; + } + interface CompletionEntryIdentifier { + name: string; + source?: string; + data?: unknown; + } + /** + * Completion entry details request; value of command field is + * "completionEntryDetails". Given a file location (file, line, + * col) and an array of completion entry names return more + * detailed information for each completion entry. + */ + interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; + arguments: CompletionDetailsRequestArgs; + } + /** + * Part of a symbol description. + */ + interface SymbolDisplayPart { + /** + * Text of an item describing the symbol. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + } + /** A part of a symbol description that links from a jsdoc @link tag to a declaration */ + interface JSDocLinkDisplayPart extends SymbolDisplayPart { + /** The location of the declaration that the @link tag links to. */ + target: FileSpan; + } + /** + * An item found in a completion response. + */ + interface CompletionEntry { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * A string that is used for comparing completion items so that they can be ordered. This + * is often the same as the name but may be different in certain circumstances. + */ + sortText: string; + /** + * Text to insert instead of `name`. + * This is used to support bracketed completions; If `name` might be "a-b" but `insertText` would be `["a-b"]`, + * coupled with `replacementSpan` to replace a dotted access with a bracket access. + */ + insertText?: string; + /** + * A string that should be used when filtering a set of + * completion items. + */ + filterText?: string; + /** + * `insertText` should be interpreted as a snippet if true. + */ + isSnippet?: true; + /** + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. + */ + replacementSpan?: TextSpan; + /** + * Indicates whether commiting this completion entry will require additional code actions to be + * made to avoid errors. The CompletionEntryDetails will have these actions. + */ + hasAction?: true; + /** + * Identifier (not necessarily human-readable) identifying where this completion came from. + */ + source?: string; + /** + * Human-readable description of the `source`. + */ + sourceDisplay?: SymbolDisplayPart[]; + /** + * Additional details for the label. + */ + labelDetails?: CompletionEntryLabelDetails; + /** + * If true, this completion should be highlighted as recommended. There will only be one of these. + * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. + * Then either that enum/class or a namespace containing it will be the recommended symbol. + */ + isRecommended?: true; + /** + * If true, this completion was generated from traversing the name table of an unchecked JS file, + * and therefore may not be accurate. + */ + isFromUncheckedFile?: true; + /** + * If true, this completion was for an auto-import of a module not yet in the program, but listed + * in the project package.json. Used for telemetry reporting. + */ + isPackageJsonImport?: true; + /** + * If true, this completion was an auto-import-style completion of an import statement (i.e., the + * module specifier was inserted along with the imported identifier). Used for telemetry reporting. + */ + isImportStatementCompletion?: true; + /** + * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, + * that allows TS Server to look up the symbol represented by the completion item, disambiguating + * items with the same name. + */ + data?: unknown; + } + interface CompletionEntryLabelDetails { + /** + * An optional string which is rendered less prominently directly after + * {@link CompletionEntry.name name}, without any spacing. Should be + * used for function signatures or type annotations. + */ + detail?: string; + /** + * An optional string which is rendered less prominently after + * {@link CompletionEntryLabelDetails.detail}. Should be used for fully qualified + * names or file path. + */ + description?: string; + } + /** + * Additional completion entry details, available on demand + */ + interface CompletionEntryDetails { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Display parts of the symbol (similar to quick info). + */ + displayParts: SymbolDisplayPart[]; + /** + * Documentation strings for the symbol. + */ + documentation?: SymbolDisplayPart[]; + /** + * JSDoc tags for the symbol. + */ + tags?: JSDocTagInfo[]; + /** + * The associated code actions for this entry + */ + codeActions?: CodeAction[]; + /** + * @deprecated Use `sourceDisplay` instead. + */ + source?: SymbolDisplayPart[]; + /** + * Human-readable description of the `source` from the CompletionEntry. + */ + sourceDisplay?: SymbolDisplayPart[]; + } + /** @deprecated Prefer CompletionInfoResponse, which supports several top-level fields in addition to the array of entries. */ + interface CompletionsResponse extends Response { + body?: CompletionEntry[]; + } + interface CompletionInfoResponse extends Response { + body?: CompletionInfo; + } + interface CompletionInfo { + readonly flags?: number; + readonly isGlobalCompletion: boolean; + readonly isMemberCompletion: boolean; + readonly isNewIdentifierLocation: boolean; + /** + * In the absence of `CompletionEntry["replacementSpan"]`, the editor may choose whether to use + * this span or its default one. If `CompletionEntry["replacementSpan"]` is defined, that span + * must be used to commit that completion entry. + */ + readonly optionalReplacementSpan?: TextSpan; + readonly isIncomplete?: boolean; + readonly entries: readonly CompletionEntry[]; + } + interface CompletionDetailsResponse extends Response { + body?: CompletionEntryDetails[]; + } + /** + * Signature help information for a single parameter + */ + interface SignatureHelpParameter { + /** + * The parameter's name + */ + name: string; + /** + * Documentation of the parameter. + */ + documentation: SymbolDisplayPart[]; + /** + * Display parts of the parameter. + */ + displayParts: SymbolDisplayPart[]; + /** + * Whether the parameter is optional or not. + */ + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + */ + interface SignatureHelpItem { + /** + * Whether the signature accepts a variable number of arguments. + */ + isVariadic: boolean; + /** + * The prefix display parts. + */ + prefixDisplayParts: SymbolDisplayPart[]; + /** + * The suffix display parts. + */ + suffixDisplayParts: SymbolDisplayPart[]; + /** + * The separator display parts. + */ + separatorDisplayParts: SymbolDisplayPart[]; + /** + * The signature helps items for the parameters. + */ + parameters: SignatureHelpParameter[]; + /** + * The signature's documentation + */ + documentation: SymbolDisplayPart[]; + /** + * The signature's JSDoc tags + */ + tags: JSDocTagInfo[]; + } + /** + * Signature help items found in the response of a signature help request. + */ + interface SignatureHelpItems { + /** + * The signature help items. + */ + items: SignatureHelpItem[]; + /** + * The span for which signature help should appear on a signature + */ + applicableSpan: TextSpan; + /** + * The item selected in the set of available help items. + */ + selectedItemIndex: number; + /** + * The argument selected in the set of parameters. + */ + argumentIndex: number; + /** + * The argument count + */ + argumentCount: number; + } + type SignatureHelpTriggerCharacter = "," | "(" | "<"; + type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")"; + /** + * Arguments of a signature help request. + */ + interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + /** + * Reason why signature help was invoked. + * See each individual possible + */ + triggerReason?: SignatureHelpTriggerReason; + } + type SignatureHelpTriggerReason = SignatureHelpInvokedReason | SignatureHelpCharacterTypedReason | SignatureHelpRetriggeredReason; + /** + * Signals that the user manually requested signature help. + * The language service will unconditionally attempt to provide a result. + */ + interface SignatureHelpInvokedReason { + kind: "invoked"; + triggerCharacter?: undefined; + } + /** + * Signals that the signature help request came from a user typing a character. + * Depending on the character and the syntactic context, the request may or may not be served a result. + */ + interface SignatureHelpCharacterTypedReason { + kind: "characterTyped"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter: SignatureHelpTriggerCharacter; + } + /** + * Signals that this signature help request came from typing a character or moving the cursor. + * This should only occur if a signature help session was already active and the editor needs to see if it should adjust. + * The language service will unconditionally attempt to provide a result. + * `triggerCharacter` can be `undefined` for a retrigger caused by a cursor move. + */ + interface SignatureHelpRetriggeredReason { + kind: "retrigger"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter?: SignatureHelpRetriggerCharacter; + } + /** + * Signature help request; value of command field is "signatureHelp". + * Given a file location (file, line, col), return the signature + * help. + */ + interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; + arguments: SignatureHelpRequestArgs; + } + /** + * Response object for a SignatureHelpRequest. + */ + interface SignatureHelpResponse extends Response { + body?: SignatureHelpItems; + } + type InlayHintKind = "Type" | "Parameter" | "Enum"; + interface InlayHintsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + } + interface InlayHintsRequest extends Request { + command: CommandTypes.ProvideInlayHints; + 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[]; + } + /** + * Synchronous request for semantic diagnostics of one file. + */ + interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; + arguments: SemanticDiagnosticsSyncRequestArgs; + } + interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous sematic diagnostics request. + */ + interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + interface SuggestionDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SuggestionDiagnosticsSync; + arguments: SuggestionDiagnosticsSyncRequestArgs; + } + type SuggestionDiagnosticsSyncRequestArgs = SemanticDiagnosticsSyncRequestArgs; + type SuggestionDiagnosticsSyncResponse = SemanticDiagnosticsSyncResponse; + /** + * Synchronous request for syntactic diagnostics of one file. + */ + interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous syntactic diagnostics request. + */ + interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Arguments for GeterrForProject request. + */ + interface GeterrForProjectRequestArgs { + /** + * the file requesting project error list + */ + file: string; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * GeterrForProjectRequest request; value of command field is + * "geterrForProject". It works similarly with 'Geterr', only + * it request for every file in this project. + */ + interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; + arguments: GeterrForProjectRequestArgs; + } + /** + * Arguments for geterr messages. + */ + interface GeterrRequestArgs { + /** + * List of file names for which to compute compiler errors. + * The files will be checked in list order. + */ + files: string[]; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * Geterr request; value of command field is "geterr". Wait for + * delay milliseconds and then, if during the wait no change or + * reload messages have arrived for the first file in the files + * list, get the syntactic errors for the file, field requests, + * and then get the semantic errors for the file. Repeat with a + * smaller delay for each subsequent file on the files list. Best + * practice for an editor is to send a file list containing each + * file that is currently visible, in most-recently-used order. + */ + interface GeterrRequest extends Request { + command: CommandTypes.Geterr; + arguments: GeterrRequestArgs; + } + type RequestCompletedEventName = "requestCompleted"; + /** + * Event that is sent when server have finished processing request with specified id. + */ + interface RequestCompletedEvent extends Event { + event: RequestCompletedEventName; + body: RequestCompletedEventBody; + } + interface RequestCompletedEventBody { + request_seq: number; + } + /** + * Item of diagnostic information found in a DiagnosticEvent message. + */ + interface Diagnostic { + /** + * Starting file location at which text applies. + */ + start: Location; + /** + * The last file location at which the text applies. + */ + end: Location; + /** + * Text of diagnostic message. + */ + text: string; + /** + * The category of the diagnostic message, e.g. "error", "warning", or "suggestion". + */ + category: string; + reportsUnnecessary?: {}; + reportsDeprecated?: {}; + /** + * Any related spans the diagnostic may have, such as other locations relevant to an error, such as declarartion sites + */ + relatedInformation?: DiagnosticRelatedInformation[]; + /** + * The error code of the diagnostic message. + */ + code?: number; + /** + * The name of the plugin reporting the message. + */ + source?: string; + } + interface DiagnosticWithFileName extends Diagnostic { + /** + * Name of the file the diagnostic is in + */ + fileName: string; + } + /** + * Represents additional spans returned with a diagnostic which are relevant to it + */ + interface DiagnosticRelatedInformation { + /** + * The category of the related information message, e.g. "error", "warning", or "suggestion". + */ + category: string; + /** + * The code used ot identify the related information + */ + code: number; + /** + * Text of related or additional information. + */ + message: string; + /** + * Associated location + */ + span?: FileSpan; + } + interface DiagnosticEventBody { + /** + * The file for which diagnostic information is reported. + */ + file: string; + /** + * An array of diagnostic information items. + */ + diagnostics: Diagnostic[]; + } + type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag"; + /** + * Event message for DiagnosticEventKind event types. + * These events provide syntactic and semantic errors for a file. + */ + interface DiagnosticEvent extends Event { + body?: DiagnosticEventBody; + event: DiagnosticEventKind; + } + interface ConfigFileDiagnosticEventBody { + /** + * The file which trigged the searching and error-checking of the config file + */ + triggerFile: string; + /** + * The name of the found config file. + */ + configFile: string; + /** + * An arry of diagnostic information items for the found config file. + */ + diagnostics: DiagnosticWithFileName[]; + } + /** + * Event message for "configFileDiag" event type. + * This event provides errors for a found config file. + */ + interface ConfigFileDiagnosticEvent extends Event { + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; + } + type ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; + interface ProjectLanguageServiceStateEvent extends Event { + event: ProjectLanguageServiceStateEventName; + body?: ProjectLanguageServiceStateEventBody; + } + interface ProjectLanguageServiceStateEventBody { + /** + * Project name that has changes in the state of language service. + * For configured projects this will be the config file path. + * For external projects this will be the name of the projects specified when project was open. + * For inferred projects this event is not raised. + */ + projectName: string; + /** + * True if language service state switched from disabled to enabled + * and false otherwise. + */ + languageServiceEnabled: boolean; + } + type ProjectsUpdatedInBackgroundEventName = "projectsUpdatedInBackground"; + interface ProjectsUpdatedInBackgroundEvent extends Event { + event: ProjectsUpdatedInBackgroundEventName; + body: ProjectsUpdatedInBackgroundEventBody; + } + interface ProjectsUpdatedInBackgroundEventBody { + /** + * Current set of open files + */ + openFiles: string[]; + } + type ProjectLoadingStartEventName = "projectLoadingStart"; + interface ProjectLoadingStartEvent extends Event { + event: ProjectLoadingStartEventName; + body: ProjectLoadingStartEventBody; + } + interface ProjectLoadingStartEventBody { + /** name of the project */ + projectName: string; + /** reason for loading */ + reason: string; + } + type ProjectLoadingFinishEventName = "projectLoadingFinish"; + interface ProjectLoadingFinishEvent extends Event { + event: ProjectLoadingFinishEventName; + body: ProjectLoadingFinishEventBody; + } + interface ProjectLoadingFinishEventBody { + /** name of the project */ + projectName: string; + } + type SurveyReadyEventName = "surveyReady"; + interface SurveyReadyEvent extends Event { + event: SurveyReadyEventName; + body: SurveyReadyEventBody; + } + interface SurveyReadyEventBody { + /** Name of the survey. This is an internal machine- and programmer-friendly name */ + surveyId: string; + } + type LargeFileReferencedEventName = "largeFileReferenced"; + interface LargeFileReferencedEvent extends Event { + event: LargeFileReferencedEventName; + body: LargeFileReferencedEventBody; + } + interface LargeFileReferencedEventBody { + /** + * name of the large file being loaded + */ + file: string; + /** + * size of the file + */ + fileSize: number; + /** + * max file size allowed on the server + */ + maxFileSize: number; + } + type CreateFileWatcherEventName = "createFileWatcher"; + interface CreateFileWatcherEvent extends Event { + readonly event: CreateFileWatcherEventName; + readonly body: CreateFileWatcherEventBody; + } + interface CreateFileWatcherEventBody { + readonly id: number; + readonly path: string; + } + type CreateDirectoryWatcherEventName = "createDirectoryWatcher"; + interface CreateDirectoryWatcherEvent extends Event { + readonly event: CreateDirectoryWatcherEventName; + readonly body: CreateDirectoryWatcherEventBody; + } + interface CreateDirectoryWatcherEventBody { + readonly id: number; + readonly path: string; + readonly recursive: boolean; + } + type CloseFileWatcherEventName = "closeFileWatcher"; + interface CloseFileWatcherEvent extends Event { + readonly event: CloseFileWatcherEventName; + readonly body: CloseFileWatcherEventBody; + } + interface CloseFileWatcherEventBody { + readonly id: number; + } + /** + * Arguments for reload request. + */ + interface ReloadRequestArgs extends FileRequestArgs { + /** + * Name of temporary file from which to reload file + * contents. May be same as file. + */ + tmpfile: string; + } + /** + * Reload request message; value of command field is "reload". + * Reload contents of file with name given by the 'file' argument + * from temporary file with name given by the 'tmpfile' argument. + * The two names can be identical. + */ + interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; + arguments: ReloadRequestArgs; + } + /** + * Response to "reload" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ReloadResponse extends Response { + } + /** + * Arguments for saveto request. + */ + interface SavetoRequestArgs extends FileRequestArgs { + /** + * Name of temporary file into which to save server's view of + * file contents. + */ + tmpfile: string; + } + /** + * Saveto request message; value of command field is "saveto". + * For debugging purposes, save to a temporaryfile (named by + * argument 'tmpfile') the contents of file named by argument + * 'file'. The server does not currently send a response to a + * "saveto" request. + */ + interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; + arguments: SavetoRequestArgs; + } + /** + * Arguments for navto request message. + */ + interface NavtoRequestArgs { + /** + * Search term to navigate to from current location; term can + * be '.*' or an identifier prefix. + */ + searchValue: string; + /** + * Optional limit on the number of items to return. + */ + maxResultCount?: number; + /** + * The file for the request (absolute pathname required). + */ + file?: string; + /** + * Optional flag to indicate we want results for just the current file + * or the entire project. + */ + currentFileOnly?: boolean; + projectFileName?: string; + } + /** + * Navto request message; value of command field is "navto". + * Return list of objects giving file locations and symbols that + * match the search term given in argument 'searchTerm'. The + * context for the search is given by the named file. + */ + interface NavtoRequest extends Request { + command: CommandTypes.Navto; + arguments: NavtoRequestArgs; + } + /** + * An item found in a navto response. + */ + interface NavtoItem extends FileSpan { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * exact, substring, or prefix. + */ + matchKind: string; + /** + * If this was a case sensitive or insensitive match. + */ + isCaseSensitive: boolean; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * Name of symbol's container symbol (if any); for example, + * the class name if symbol is a class member. + */ + containerName?: string; + /** + * Kind of symbol's container symbol (if any). + */ + containerKind?: ScriptElementKind; + } + /** + * Navto response message. Body is an array of navto items. Each + * item gives a symbol that matched the search term. + */ + interface NavtoResponse extends Response { + body?: NavtoItem[]; + } + /** + * Arguments for change request message. + */ + interface ChangeRequestArgs extends FormatRequestArgs { + /** + * Optional string to insert at location (file, line, offset). + */ + insertString?: string; + } + /** + * Change request message; value of command field is "change". + * Update the server's view of the file named by argument 'file'. + * Server does not currently send a response to a change request. + */ + interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; + arguments: ChangeRequestArgs; + } + /** + * Response to "brace" request. + */ + interface BraceResponse extends Response { + body?: TextSpan[]; + } + /** + * Brace matching request; value of command field is "brace". + * Return response giving the file locations of matching braces + * found in file at location line, offset. + */ + interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; + } + /** + * NavBar items request; value of command field is "navbar". + * Return response giving the list of navigation bar entries + * extracted from the requested file. + */ + interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; + } + /** + * NavTree request; value of command field is "navtree". + * Return response giving the navigation tree of the requested file. + */ + interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; + } + interface NavigationBarItem { + /** + * The item's display text. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The definition locations of the item. + */ + spans: TextSpan[]; + /** + * Optional children. + */ + childItems?: NavigationBarItem[]; + /** + * Number of levels deep this item should appear. + */ + indent: number; + } + /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ + interface NavigationTree { + text: string; + kind: ScriptElementKind; + kindModifiers: string; + spans: TextSpan[]; + nameSpan: TextSpan | undefined; + childItems?: NavigationTree[]; + } + type TelemetryEventName = "telemetry"; + interface TelemetryEvent extends Event { + event: TelemetryEventName; + body: TelemetryEventBody; + } + interface TelemetryEventBody { + telemetryEventName: string; + payload: any; + } + type TypesInstallerInitializationFailedEventName = "typesInstallerInitializationFailed"; + interface TypesInstallerInitializationFailedEvent extends Event { + event: TypesInstallerInitializationFailedEventName; + body: TypesInstallerInitializationFailedEventBody; + } + interface TypesInstallerInitializationFailedEventBody { + message: string; + } + type TypingsInstalledTelemetryEventName = "typingsInstalled"; + interface TypingsInstalledTelemetryEventBody extends TelemetryEventBody { + telemetryEventName: TypingsInstalledTelemetryEventName; + payload: TypingsInstalledTelemetryEventPayload; + } + interface TypingsInstalledTelemetryEventPayload { + /** + * Comma separated list of installed typing packages + */ + installedPackages: string; + /** + * true if install request succeeded, otherwise - false + */ + installSuccess: boolean; + /** + * version of typings installer + */ + typingsInstallerVersion: string; + } + type BeginInstallTypesEventName = "beginInstallTypes"; + type EndInstallTypesEventName = "endInstallTypes"; + interface BeginInstallTypesEvent extends Event { + event: BeginInstallTypesEventName; + body: BeginInstallTypesEventBody; + } + interface EndInstallTypesEvent extends Event { + event: EndInstallTypesEventName; + body: EndInstallTypesEventBody; + } + interface InstallTypesEventBody { + /** + * correlation id to match begin and end events + */ + eventId: number; + /** + * list of packages to install + */ + packages: readonly string[]; + } + interface BeginInstallTypesEventBody extends InstallTypesEventBody { + } + interface EndInstallTypesEventBody extends InstallTypesEventBody { + /** + * true if installation succeeded, otherwise false + */ + success: boolean; + } + interface NavBarResponse extends Response { + body?: NavigationBarItem[]; + } + interface NavTreeResponse extends Response { + body?: NavigationTree; + } + interface CallHierarchyItem { + name: string; + kind: ScriptElementKind; + kindModifiers?: string; + file: string; + span: TextSpan; + selectionSpan: TextSpan; + containerName?: string; + } + interface CallHierarchyIncomingCall { + from: CallHierarchyItem; + fromSpans: TextSpan[]; + } + interface CallHierarchyOutgoingCall { + to: CallHierarchyItem; + fromSpans: TextSpan[]; + } + interface PrepareCallHierarchyRequest extends FileLocationRequest { + command: CommandTypes.PrepareCallHierarchy; + } + interface PrepareCallHierarchyResponse extends Response { + readonly body: CallHierarchyItem | CallHierarchyItem[]; + } + interface ProvideCallHierarchyIncomingCallsRequest extends FileLocationRequest { + command: CommandTypes.ProvideCallHierarchyIncomingCalls; + } + interface ProvideCallHierarchyIncomingCallsResponse extends Response { + readonly body: CallHierarchyIncomingCall[]; + } + interface ProvideCallHierarchyOutgoingCallsRequest extends FileLocationRequest { + command: CommandTypes.ProvideCallHierarchyOutgoingCalls; + } + interface ProvideCallHierarchyOutgoingCallsResponse extends Response { + readonly body: CallHierarchyOutgoingCall[]; + } + enum IndentStyle { + None = "None", + Block = "Block", + Smart = "Smart", + } + enum SemicolonPreference { + Ignore = "ignore", + Insert = "insert", + Remove = "remove", + } + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle | ts.IndentStyle; + trimTrailingWhitespace?: boolean; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterConstructor?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingEmptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + insertSpaceBeforeFunctionParenthesis?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; + semicolons?: SemicolonPreference; + indentSwitchCase?: boolean; + } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "auto" | "double" | "single"; + /** + * If enabled, TypeScript will search through all external modules' exports and add them to the completions list. + * This affects lone identifier completions but not completions on the right hand side of `obj.`. + */ + readonly includeCompletionsForModuleExports?: boolean; + /** + * Enables auto-import-style completions on partially-typed import statements. E.g., allows + * `import write|` to be completed to `import { writeFile } from "fs"`. + */ + readonly includeCompletionsForImportStatements?: boolean; + /** + * Allows completions to be formatted with snippet text, indicated by `CompletionItem["isSnippet"]`. + */ + readonly includeCompletionsWithSnippetText?: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ + readonly includeCompletionsWithInsertText?: boolean; + /** + * Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled, + * member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined + * values, with insertion text to replace preceding `.` tokens with `?.`. + */ + readonly includeAutomaticOptionalChainCompletions?: boolean; + /** + * If enabled, completions for class members (e.g. methods and properties) will include + * a whole declaration for the member. + * E.g., `class A { f| }` could be completed to `class A { foo(): number {} }`, instead of + * `class A { foo }`. + */ + readonly includeCompletionsWithClassMemberSnippets?: boolean; + /** + * If enabled, object literal methods will have a method declaration completion entry in addition + * to the regular completion entry containing just the method name. + * E.g., `const objectLiteral: T = { f| }` could be completed to `const objectLiteral: T = { foo(): void {} }`, + * in addition to `const objectLiteral: T = { foo }`. + */ + readonly includeCompletionsWithObjectLiteralMethodSnippets?: boolean; + /** + * Indicates whether {@link CompletionEntry.labelDetails completion entry label details} are supported. + * If not, contents of `labelDetails` may be included in the {@link CompletionEntry.name} property. + */ + readonly useLabelDetailsInCompletionEntries?: boolean; + readonly allowIncompleteCompletions?: boolean; + readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "auto" | "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + readonly lazyConfiguredProjectsFromExternalProject?: boolean; + readonly providePrefixAndSuffixTextForRename?: boolean; + readonly provideRefactorNotApplicableReason?: boolean; + readonly allowRenameOfImportPath?: boolean; + readonly includePackageJsonAutoImports?: "auto" | "on" | "off"; + readonly jsxAttributeCompletionStyle?: "auto" | "braces" | "none"; + readonly displayPartsForJSDoc?: boolean; + readonly generateReturnInDocTemplate?: boolean; + readonly includeInlayParameterNameHints?: "none" | "literals" | "all"; + readonly includeInlayParameterNameHintsWhenArgumentMatchesName?: boolean; + readonly includeInlayFunctionParameterTypeHints?: boolean; + readonly includeInlayVariableTypeHints?: boolean; + readonly includeInlayVariableTypeHintsWhenTypeMatchesName?: boolean; + 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. + */ + readonly organizeImportsIgnoreCase?: "auto" | boolean; + /** + * Indicates whether imports should be organized via an "ordinal" (binary) comparison using the numeric value + * of their code points, or via "unicode" collation (via the + * [Unicode Collation Algorithm](https://unicode.org/reports/tr10/#Scope)) using rules associated with the locale + * specified in {@link organizeImportsCollationLocale}. + * + * Default: `"ordinal"`. + */ + readonly organizeImportsCollation?: "ordinal" | "unicode"; + /** + * Indicates the locale to use for "unicode" collation. If not specified, the locale `"en"` is used as an invariant + * for the sake of consistent sorting. Use `"auto"` to use the detected UI locale. + * + * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`. + * + * Default: `"en"` + */ + readonly organizeImportsCollationLocale?: string; + /** + * Indicates whether numeric collation should be used for digit sequences in strings. When `true`, will collate + * strings such that `a1z < a2z < a100z`. When `false`, will collate strings such that `a1z < a100z < a2z`. + * + * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`. + * + * Default: `false` + */ + readonly organizeImportsNumericCollation?: boolean; + /** + * Indicates whether accents and other diacritic marks are considered unequal for the purpose of collation. When + * `true`, characters with accents and other diacritics will be collated in the order defined by the locale specified + * in {@link organizeImportsCollationLocale}. + * + * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`. + * + * Default: `true` + */ + readonly organizeImportsAccentCollation?: boolean; + /** + * Indicates whether upper case or lower case should sort first. When `false`, the default order for the locale + * specified in {@link organizeImportsCollationLocale} is used. + * + * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`. This preference is also + * ignored if we are using case-insensitive sorting, which occurs when {@link organizeImportsIgnoreCase} is `true`, + * or if {@link organizeImportsIgnoreCase} is `"auto"` and the auto-detected case sensitivity is determined to be + * case-insensitive. + * + * Default: `false` + */ + readonly organizeImportsCaseFirst?: "upper" | "lower" | false; + /** + * Indicates whether {@link ReferencesResponseItem.lineText} is supported. + */ + readonly disableLineTextInReferences?: boolean; + /** + * Indicates whether to exclude standard library and node_modules file symbols from navTo results. + */ + readonly excludeLibrarySymbolsInNavTo?: boolean; + } + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + alwaysStrict?: boolean; + baseUrl?: string; + charset?: string; + checkJs?: boolean; + declaration?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + downlevelIteration?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + importHelpers?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit | ts.JsxEmit; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind | ts.ModuleKind; + moduleResolution?: ModuleResolutionKind | ts.ModuleResolutionKind; + newLine?: NewLineKind | ts.NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + plugins?: PluginImport[]; + preserveConstEnums?: boolean; + preserveSymlinks?: boolean; + project?: string; + reactNamespace?: string; + removeComments?: boolean; + references?: ProjectReference[]; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strict?: boolean; + strictNullChecks?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + useDefineForClassFields?: boolean; + target?: ScriptTarget | ts.ScriptTarget; + traceResolution?: boolean; + resolveJsonModule?: boolean; + types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + enum JsxEmit { + None = "None", + Preserve = "Preserve", + ReactNative = "ReactNative", + React = "React", + } + enum ModuleKind { + None = "None", + CommonJS = "CommonJS", + AMD = "AMD", + UMD = "UMD", + System = "System", + ES6 = "ES6", + ES2015 = "ES2015", + ESNext = "ESNext", + } + enum ModuleResolutionKind { + Classic = "Classic", + Node = "Node", + } + enum NewLineKind { + Crlf = "Crlf", + Lf = "Lf", + } + enum ScriptTarget { + ES3 = "ES3", + ES5 = "ES5", + ES6 = "ES6", + ES2015 = "ES2015", + ES2016 = "ES2016", + ES2017 = "ES2017", + ES2018 = "ES2018", + ES2019 = "ES2019", + ES2020 = "ES2020", + ES2021 = "ES2021", + ES2022 = "ES2022", + ESNext = "ESNext", + } + enum ClassificationType { + comment = 1, + identifier = 2, + keyword = 3, + numericLiteral = 4, + operator = 5, + stringLiteral = 6, + regularExpressionLiteral = 7, + whiteSpace = 8, + text = 9, + punctuation = 10, + className = 11, + enumName = 12, + interfaceName = 13, + moduleName = 14, + typeParameterName = 15, + typeAliasName = 16, + parameterName = 17, + docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25, + } + } + namespace typingsInstaller { + interface Log { + isEnabled(): boolean; + writeLine(text: string): void; + } + type RequestCompletedAction = (success: boolean) => void; + interface PendingRequest { + requestId: number; + packageNames: string[]; + cwd: string; + onRequestCompleted: RequestCompletedAction; + } + abstract class TypingsInstaller { + protected readonly installTypingHost: InstallTypingHost; + private readonly globalCachePath; + private readonly safeListPath; + private readonly typesMapLocation; + private readonly throttleLimit; + protected readonly log: Log; + private readonly packageNameToTypingLocation; + private readonly missingTypingsSet; + private readonly knownCachesSet; + private readonly projectWatchers; + private safeList; + private installRunCount; + private inFlightRequestCount; + abstract readonly typesRegistry: Map>; + constructor(installTypingHost: InstallTypingHost, globalCachePath: string, safeListPath: Path, typesMapLocation: Path, throttleLimit: number, log?: Log); + closeProject(req: CloseProject): void; + private closeWatchers; + install(req: DiscoverTypings): void; + private initializeSafeList; + private processCacheLocation; + private filterTypings; + protected ensurePackageDirectoryExists(directory: string): void; + private installTypings; + private ensureDirectoryExists; + private watchFiles; + private createSetTypings; + private installTypingsAsync; + private executeWithThrottling; + protected abstract installWorker(requestId: number, packageNames: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void; + protected abstract sendResponse(response: SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | WatchTypingLocations): void; + protected readonly latestDistTag = "latest"; + } + } + interface CompressedData { + length: number; + compressionKind: string; + data: any; + } + type ModuleImportResult = { + module: {}; + error: undefined; + } | { + module: undefined; + error: { + stack?: string; + message?: string; + }; + }; + /** @deprecated Use {@link ModuleImportResult} instead. */ + type RequireResult = ModuleImportResult; + interface ServerHost extends System { + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; + setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + clearTimeout(timeoutId: any): void; + setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; + clearImmediate(timeoutId: any): void; + gc?(): void; + trace?(s: string): void; + require?(initialPath: string, moduleName: string): ModuleImportResult; + } + function createInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, cachePath?: string): DiscoverTypings; + function toNormalizedPath(fileName: string): NormalizedPath; + function normalizedPathToPath(normalizedPath: NormalizedPath, currentDirectory: string, getCanonicalFileName: (f: string) => string): Path; + function asNormalizedPath(fileName: string): NormalizedPath; + function createNormalizedPathMap(): NormalizedPathMap; + function isInferredProjectName(name: string): boolean; + function makeInferredProjectName(counter: number): string; + function createSortedArray(): SortedArray; + enum LogLevel { + terse = 0, + normal = 1, + requestTime = 2, + verbose = 3, + } + const emptyArray: SortedReadonlyArray; + interface Logger { + close(): void; + hasLevel(level: LogLevel): boolean; + loggingEnabled(): boolean; + perftrc(s: string): void; + info(s: string): void; + startGroup(): void; + endGroup(): void; + msg(s: string, type?: Msg): void; + getLogFileName(): string | undefined; + } + enum Msg { + Err = "Err", + Info = "Info", + Perf = "Perf", + } + namespace Errors { + function ThrowNoProject(): never; + function ThrowProjectLanguageServiceDisabled(): never; + function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never; + } + type NormalizedPath = string & { + __normalizedPathTag: any; + }; + interface NormalizedPathMap { + get(path: NormalizedPath): T | undefined; + set(path: NormalizedPath, value: T): void; + contains(path: NormalizedPath): boolean; + remove(path: NormalizedPath): void; + } + function isDynamicFileName(fileName: NormalizedPath): boolean; + class ScriptInfo { + private readonly host; + readonly fileName: NormalizedPath; + readonly scriptKind: ScriptKind; + readonly hasMixedContent: boolean; + readonly path: Path; + /** + * All projects that include this file + */ + readonly containingProjects: Project[]; + private formatSettings; + private preferences; + constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent: boolean, path: Path, initialVersion?: number); + isScriptOpen(): boolean; + open(newText: string | undefined): void; + close(fileExists?: boolean): void; + getSnapshot(): IScriptSnapshot; + private ensureRealPath; + getFormatCodeSettings(): FormatCodeSettings | undefined; + getPreferences(): protocol.UserPreferences | undefined; + attachToProject(project: Project): boolean; + isAttached(project: Project): boolean; + detachFromProject(project: Project): void; + detachAllProjects(): void; + getDefaultProject(): Project; + registerFileUpdate(): void; + setOptions(formatSettings: FormatCodeSettings, preferences: protocol.UserPreferences | undefined): void; + getLatestVersion(): string; + saveTo(fileName: string): void; + reloadFromFile(tempFileName?: NormalizedPath): boolean; + editContent(start: number, end: number, newText: string): void; + markContainingProjectsAsDirty(): void; + isOrphan(): boolean; + /** + * @param line 1 based index + */ + lineToTextSpan(line: number): TextSpan; + /** + * @param line 1 based index + * @param offset 1 based index + */ + lineOffsetToPosition(line: number, offset: number): number; + positionToLineOffset(position: number): protocol.Location; + isJavaScript(): boolean; + } + interface InstallPackageOptionsWithProject extends InstallPackageOptions { + projectName: string; + projectRootPath: Path; + } + interface ITypingsInstaller { + isKnownTypesPackageName(name: string): boolean; + installPackage(options: InstallPackageOptionsWithProject): Promise; + enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray | undefined): void; + attach(projectService: ProjectService): void; + onProjectClosed(p: Project): void; + readonly globalTypingsCacheLocation: string | undefined; + } + const nullTypingsInstaller: ITypingsInstaller; + function allRootFilesAreJsOrDts(project: Project): boolean; + function allFilesAreJsOrDts(project: Project): boolean; + enum ProjectKind { + Inferred = 0, + Configured = 1, + External = 2, + AutoImportProvider = 3, + Auxiliary = 4, + } + interface PluginCreateInfo { + project: Project; + languageService: LanguageService; + languageServiceHost: LanguageServiceHost; + serverHost: ServerHost; + session?: Session; + config: any; + } + interface PluginModule { + create(createInfo: PluginCreateInfo): LanguageService; + getExternalFiles?(proj: Project, updateLevel: ProgramUpdateLevel): string[]; + onConfigurationChanged?(config: any): void; + } + interface PluginModuleWithName { + name: string; + module: PluginModule; + } + type PluginModuleFactory = (mod: { + typescript: typeof ts; + }) => PluginModule; + abstract class Project implements LanguageServiceHost, ModuleResolutionHost { + readonly projectKind: ProjectKind; + readonly projectService: ProjectService; + private documentRegistry; + private compilerOptions; + compileOnSaveEnabled: boolean; + protected watchOptions: WatchOptions | undefined; + private rootFiles; + private rootFilesMap; + private program; + private externalFiles; + private missingFilesMap; + private generatedFilesMap; + protected languageService: LanguageService; + languageServiceEnabled: boolean; + readonly trace?: (s: string) => void; + readonly realpath?: (path: string) => string; + private builderState; + /** + * Set of files names that were updated since the last call to getChangesSinceVersion. + */ + private updatedFileNames; + /** + * Set of files that was returned from the last call to getChangesSinceVersion. + */ + private lastReportedFileNames; + /** + * Last version that was reported. + */ + private lastReportedVersion; + /** + * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one) + * This property is changed in 'updateGraph' based on the set of files in program + */ + private projectProgramVersion; + /** + * Current version of the project state. It is changed when: + * - new root file was added/removed + * - edit happen in some file that is currently included in the project. + * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project + */ + private projectStateVersion; + protected projectErrors: Diagnostic[] | undefined; + protected isInitialLoadPending: () => boolean; + private readonly cancellationToken; + isNonTsProject(): boolean; + isJsOnlyProject(): boolean; + static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {} | undefined; + readonly jsDocParsingMode: JSDocParsingMode | undefined; + isKnownTypesPackageName(name: string): boolean; + installPackage(options: InstallPackageOptions): Promise; + private get typingsCache(); + getCompilationSettings(): ts.CompilerOptions; + getCompilerOptions(): ts.CompilerOptions; + getNewLine(): string; + getProjectVersion(): string; + getProjectReferences(): readonly ProjectReference[] | undefined; + getScriptFileNames(): string[]; + private getOrCreateScriptInfoAndAttachToProject; + getScriptKind(fileName: string): ts.ScriptKind; + getScriptVersion(filename: string): string; + getScriptSnapshot(filename: string): IScriptSnapshot | undefined; + getCancellationToken(): HostCancellationToken; + getCurrentDirectory(): string; + getDefaultLibFileName(): string; + useCaseSensitiveFileNames(): boolean; + readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; + readFile(fileName: string): string | undefined; + writeFile(fileName: string, content: string): void; + fileExists(file: string): boolean; + directoryExists(path: string): boolean; + getDirectories(path: string): string[]; + log(s: string): void; + error(s: string): void; + private setInternalCompilerOptionsForEmittingJsFiles; + /** + * Get the errors that dont have any file name associated + */ + getGlobalProjectErrors(): readonly Diagnostic[]; + /** + * Get all the project errors + */ + getAllProjectErrors(): readonly Diagnostic[]; + setProjectErrors(projectErrors: Diagnostic[] | undefined): void; + getLanguageService(ensureSynchronized?: boolean): LanguageService; + getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; + /** + * Returns true if emit was conducted + */ + emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): EmitResult; + enableLanguageService(): void; + disableLanguageService(lastFileExceededProgramSize?: string): void; + getProjectName(): string; + protected removeLocalTypingsFromTypeAcquisition(newTypeAcquisition: TypeAcquisition): TypeAcquisition; + getExternalFiles(updateLevel?: ProgramUpdateLevel): SortedReadonlyArray; + getSourceFile(path: Path): ts.SourceFile | undefined; + close(): void; + private detachScriptInfoIfNotRoot; + isClosed(): boolean; + hasRoots(): boolean; + getRootFiles(): ts.server.NormalizedPath[]; + getRootScriptInfos(): ts.server.ScriptInfo[]; + getScriptInfos(): ScriptInfo[]; + getExcludedFiles(): readonly NormalizedPath[]; + getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean): ts.server.NormalizedPath[]; + hasConfigFile(configFilePath: NormalizedPath): boolean; + containsScriptInfo(info: ScriptInfo): boolean; + containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean; + isRoot(info: ScriptInfo): boolean; + addRoot(info: ScriptInfo, fileName?: NormalizedPath): void; + addMissingFileRoot(fileName: NormalizedPath): void; + removeFile(info: ScriptInfo, fileExists: boolean, detachFromProject: boolean): void; + registerFileUpdate(fileName: string): void; + markAsDirty(): void; + /** + * Updates set of files that contribute to this project + * @returns: true if set of files in the project stays the same and false - otherwise. + */ + updateGraph(): boolean; + protected removeExistingTypings(include: string[]): string[]; + private updateGraphWorker; + private detachScriptInfoFromProject; + private addMissingFileWatcher; + private isWatchedMissingFile; + private createGeneratedFileWatcher; + private isValidGeneratedFileWatcher; + private clearGeneratedFileWatch; + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; + getScriptInfo(uncheckedFileName: string): ts.server.ScriptInfo | undefined; + filesToString(writeProjectFileNames: boolean): string; + setCompilerOptions(compilerOptions: CompilerOptions): void; + setTypeAcquisition(newTypeAcquisition: TypeAcquisition | undefined): void; + getTypeAcquisition(): ts.TypeAcquisition; + protected removeRoot(info: ScriptInfo): void; + protected enableGlobalPlugins(options: CompilerOptions): void; + protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; + /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ + refreshDiagnostics(): void; + } + /** + * If a file is opened and no tsconfig (or jsconfig) is found, + * the file and its imports/references are put into an InferredProject. + */ + class InferredProject extends Project { + private _isJsInferredProject; + toggleJsInferredProject(isJsInferredProject: boolean): void; + setCompilerOptions(options?: CompilerOptions): void; + /** this is canonical project root path */ + readonly projectRootPath: string | undefined; + addRoot(info: ScriptInfo): void; + removeRoot(info: ScriptInfo): void; + isProjectWithSingleRoot(): boolean; + close(): void; + getTypeAcquisition(): TypeAcquisition; + } + class AutoImportProviderProject extends Project { + private hostProject; + private rootFileNames; + isOrphan(): boolean; + updateGraph(): boolean; + hasRoots(): boolean; + markAsDirty(): void; + getScriptFileNames(): string[]; + getLanguageService(): never; + getHostForAutoImportProvider(): never; + getProjectReferences(): readonly ts.ProjectReference[] | undefined; + } + /** + * If a file is opened, the server will look for a tsconfig (or jsconfig) + * and if successful create a ConfiguredProject for it. + * Otherwise it will create an InferredProject. + */ + class ConfiguredProject extends Project { + readonly canonicalConfigFilePath: NormalizedPath; + /** Ref count to the project when opened from external project */ + private externalProjectRefCount; + private projectReferences; + /** + * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph + * @returns: true if set of files in the project stays the same and false - otherwise. + */ + updateGraph(): boolean; + getConfigFilePath(): ts.server.NormalizedPath; + getProjectReferences(): readonly ProjectReference[] | undefined; + updateReferences(refs: readonly ProjectReference[] | undefined): void; + /** + * Get the errors that dont have any file name associated + */ + getGlobalProjectErrors(): readonly Diagnostic[]; + /** + * Get all the project errors + */ + getAllProjectErrors(): readonly Diagnostic[]; + setProjectErrors(projectErrors: Diagnostic[]): void; + close(): void; + getEffectiveTypeRoots(): string[]; + } + /** + * Project whose configuration is handled externally, such as in a '.csproj'. + * These are created only if a host explicitly calls `openExternalProject`. + */ + class ExternalProject extends Project { + externalProjectName: string; + compileOnSaveEnabled: boolean; + excludedFiles: readonly NormalizedPath[]; + updateGraph(): boolean; + getExcludedFiles(): readonly ts.server.NormalizedPath[]; + } + function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings; + function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin; + function convertWatchOptions(protocolOptions: protocol.ExternalProjectCompilerOptions, currentDirectory?: string): WatchOptionsAndErrors | undefined; + function convertTypeAcquisition(protocolOptions: protocol.InferredProjectCompilerOptions): TypeAcquisition | undefined; + function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind; + function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; + const maxProgramSizeForNonTsFiles: number; + const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + interface ProjectsUpdatedInBackgroundEvent { + eventName: typeof ProjectsUpdatedInBackgroundEvent; + data: { + openFiles: string[]; + }; + } + const ProjectLoadingStartEvent = "projectLoadingStart"; + interface ProjectLoadingStartEvent { + eventName: typeof ProjectLoadingStartEvent; + data: { + project: Project; + reason: string; + }; + } + const ProjectLoadingFinishEvent = "projectLoadingFinish"; + interface ProjectLoadingFinishEvent { + eventName: typeof ProjectLoadingFinishEvent; + data: { + project: Project; + }; + } + const LargeFileReferencedEvent = "largeFileReferenced"; + interface LargeFileReferencedEvent { + eventName: typeof LargeFileReferencedEvent; + data: { + file: string; + fileSize: number; + maxFileSize: number; + }; + } + const ConfigFileDiagEvent = "configFileDiag"; + interface ConfigFileDiagEvent { + eventName: typeof ConfigFileDiagEvent; + data: { + triggerFile: string; + configFileName: string; + diagnostics: readonly Diagnostic[]; + }; + } + const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; + interface ProjectLanguageServiceStateEvent { + eventName: typeof ProjectLanguageServiceStateEvent; + data: { + project: Project; + languageServiceEnabled: boolean; + }; + } + const ProjectInfoTelemetryEvent = "projectInfo"; + /** This will be converted to the payload of a protocol.TelemetryEvent in session.defaultEventHandler. */ + interface ProjectInfoTelemetryEvent { + readonly eventName: typeof ProjectInfoTelemetryEvent; + readonly data: ProjectInfoTelemetryEventData; + } + const OpenFileInfoTelemetryEvent = "openFileInfo"; + /** + * Info that we may send about a file that was just opened. + * Info about a file will only be sent once per session, even if the file changes in ways that might affect the info. + * Currently this is only sent for '.js' files. + */ + interface OpenFileInfoTelemetryEvent { + readonly eventName: typeof OpenFileInfoTelemetryEvent; + readonly data: OpenFileInfoTelemetryEventData; + } + const CreateFileWatcherEvent: protocol.CreateFileWatcherEventName; + interface CreateFileWatcherEvent { + readonly eventName: protocol.CreateFileWatcherEventName; + readonly data: protocol.CreateFileWatcherEventBody; + } + const CreateDirectoryWatcherEvent: protocol.CreateDirectoryWatcherEventName; + interface CreateDirectoryWatcherEvent { + readonly eventName: protocol.CreateDirectoryWatcherEventName; + readonly data: protocol.CreateDirectoryWatcherEventBody; + } + const CloseFileWatcherEvent: protocol.CloseFileWatcherEventName; + interface CloseFileWatcherEvent { + readonly eventName: protocol.CloseFileWatcherEventName; + readonly data: protocol.CloseFileWatcherEventBody; + } + interface ProjectInfoTelemetryEventData { + /** Cryptographically secure hash of project file location. */ + readonly projectId: string; + /** Count of file extensions seen in the project. */ + readonly fileStats: FileStats; + /** + * Any compiler options that might contain paths will be taken out. + * Enum compiler options will be converted to strings. + */ + readonly compilerOptions: CompilerOptions; + readonly extends: boolean | undefined; + readonly files: boolean | undefined; + readonly include: boolean | undefined; + readonly exclude: boolean | undefined; + readonly compileOnSave: boolean; + readonly typeAcquisition: ProjectInfoTypeAcquisitionData; + readonly configFileName: "tsconfig.json" | "jsconfig.json" | "other"; + readonly projectType: "external" | "configured"; + readonly languageServiceEnabled: boolean; + /** TypeScript version used by the server. */ + readonly version: string; + } + interface OpenFileInfoTelemetryEventData { + readonly info: OpenFileInfo; + } + interface ProjectInfoTypeAcquisitionData { + readonly enable: boolean | undefined; + readonly include: boolean; + readonly exclude: boolean; + } + interface FileStats { + readonly js: number; + readonly jsSize?: number; + readonly jsx: number; + readonly jsxSize?: number; + readonly ts: number; + readonly tsSize?: number; + readonly tsx: number; + readonly tsxSize?: number; + readonly dts: number; + readonly dtsSize?: number; + readonly deferred: number; + readonly deferredSize?: number; + } + interface OpenFileInfo { + readonly checkJs: boolean; + } + type ProjectServiceEvent = LargeFileReferencedEvent | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent | CreateFileWatcherEvent | CreateDirectoryWatcherEvent | CloseFileWatcherEvent; + type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; + interface SafeList { + [name: string]: { + match: RegExp; + exclude?: (string | number)[][]; + types?: string[]; + }; + } + interface TypesMapFile { + typesMap: SafeList; + simpleMap: { + [libName: string]: string; + }; + } + interface HostConfiguration { + formatCodeOptions: FormatCodeSettings; + preferences: protocol.UserPreferences; + hostInfo: string; + extraFileExtensions?: FileExtensionInfo[]; + watchOptions?: WatchOptions; + } + interface OpenConfiguredProjectResult { + configFileName?: NormalizedPath; + configFileErrors?: readonly Diagnostic[]; + } + interface ProjectServiceOptions { + host: ServerHost; + logger: Logger; + cancellationToken: HostCancellationToken; + useSingleInferredProject: boolean; + useInferredProjectPerProjectRoot: boolean; + typingsInstaller?: ITypingsInstaller; + eventHandler?: ProjectServiceEventHandler; + canUseWatchEvents?: boolean; + suppressDiagnosticEvents?: boolean; + throttleWaitMilliseconds?: number; + globalPlugins?: readonly string[]; + pluginProbeLocations?: readonly string[]; + allowLocalPluginLoads?: boolean; + typesMapLocation?: string; + serverMode?: LanguageServiceMode; + session: Session | undefined; + jsDocParsingMode?: JSDocParsingMode; + } + interface WatchOptionsAndErrors { + watchOptions: WatchOptions; + errors: Diagnostic[] | undefined; + } + class ProjectService { + private readonly nodeModulesWatchers; + /** + * Contains all the deleted script info's version information so that + * it does not reset when creating script info again + * (and could have potentially collided with version where contents mismatch) + */ + private readonly filenameToScriptInfoVersion; + private readonly allJsFilesForOpenFileTelemetry; + /** + * maps external project file name to list of config files that were the part of this project + */ + private readonly externalProjectToConfiguredProjectMap; + /** + * external projects (configuration and list of root files is not controlled by tsserver) + */ + readonly externalProjects: ExternalProject[]; + /** + * projects built from openFileRoots + */ + readonly inferredProjects: InferredProject[]; + /** + * projects specified by a tsconfig.json file + */ + readonly configuredProjects: Map; + /** + * Open files: with value being project root path, and key being Path of the file that is open + */ + readonly openFiles: Map; + /** + * Map of open files that are opened without complete path but have projectRoot as current directory + */ + private readonly openFilesWithNonRootedDiskPath; + private compilerOptionsForInferredProjects; + private compilerOptionsForInferredProjectsPerProjectRoot; + private watchOptionsForInferredProjects; + private watchOptionsForInferredProjectsPerProjectRoot; + private typeAcquisitionForInferredProjects; + private typeAcquisitionForInferredProjectsPerProjectRoot; + /** + * Project size for configured or external projects + */ + private readonly projectToSizeMap; + private readonly hostConfiguration; + private safelist; + private readonly legacySafelist; + private pendingProjectUpdates; + readonly currentDirectory: NormalizedPath; + readonly toCanonicalFileName: (f: string) => string; + readonly host: ServerHost; + readonly logger: Logger; + readonly cancellationToken: HostCancellationToken; + readonly useSingleInferredProject: boolean; + readonly useInferredProjectPerProjectRoot: boolean; + readonly typingsInstaller: ITypingsInstaller; + private readonly globalCacheLocationDirectoryPath; + readonly throttleWaitMilliseconds?: number; + private readonly suppressDiagnosticEvents?; + readonly globalPlugins: readonly string[]; + readonly pluginProbeLocations: readonly string[]; + readonly allowLocalPluginLoads: boolean; + readonly typesMapLocation: string | undefined; + readonly serverMode: LanguageServiceMode; + /** Tracks projects that we have already sent telemetry for. */ + private readonly seenProjects; + private performanceEventHandler?; + private pendingPluginEnablements?; + private currentPluginEnablementPromise?; + readonly jsDocParsingMode: JSDocParsingMode | undefined; + constructor(opts: ProjectServiceOptions); + toPath(fileName: string): Path; + private loadTypesMap; + updateTypingsForProject(response: SetTypings | InvalidateCachedTypings | PackageInstalledResponse): void; + private delayUpdateProjectGraph; + private delayUpdateProjectGraphs; + setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.InferredProjectCompilerOptions, projectRootPath?: string): void; + findProject(projectName: string): Project | undefined; + getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project | undefined; + private doEnsureDefaultProjectForFile; + getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string): ScriptInfo | undefined; + /** + * Ensures the project structures are upto date + * This means, + * - we go through all the projects and update them if they are dirty + * - if updates reflect some change in structure or there was pending request to ensure projects for open files + * ensure that each open script info has project + */ + private ensureProjectStructuresUptoDate; + getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings; + getPreferences(file: NormalizedPath): protocol.UserPreferences; + getHostFormatCodeOptions(): FormatCodeSettings; + getHostPreferences(): protocol.UserPreferences; + private onSourceFileChanged; + private handleSourceMapProjects; + private delayUpdateSourceInfoProjects; + private delayUpdateProjectsOfScriptInfoPath; + private handleDeletedFile; + private removeProject; + private assignOrphanScriptInfosToInferredProject; + /** + * Remove this file from the set of open, non-configured files. + * @param info The file that has been closed or newly configured + */ + private closeOpenFile; + private deleteScriptInfo; + private configFileExists; + /** + * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project + */ + private configFileExistenceImpactsRootOfInferredProject; + /** + * This is called on file close, so that we stop watching the config file for this script info + */ + private stopWatchingConfigFilesForClosedScriptInfo; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + */ + private forEachConfigFileLocation; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + * If script info is passed in, it is asserted to be open script info + * otherwise just file name + */ + private getConfigFileNameForFile; + private printProjects; + private getConfiguredProjectByCanonicalConfigFilePath; + private findExternalProjectByProjectName; + /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ + private getFilenameForExceededTotalSizeLimitForNonTsFiles; + private createExternalProject; + private addFilesToNonInferredProject; + private updateNonInferredProjectFiles; + private updateRootAndOptionsOfNonInferredProject; + private sendConfigFileDiagEvent; + private getOrCreateInferredProjectForProjectRootPathIfEnabled; + private getOrCreateSingleInferredProjectIfEnabled; + private getOrCreateSingleInferredWithoutProjectRoot; + private createInferredProject; + getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; + private watchClosedScriptInfo; + private createNodeModulesWatcher; + private watchClosedScriptInfoInNodeModules; + private getModifiedTime; + private refreshScriptInfo; + private refreshScriptInfosInDirectory; + private stopWatchingScriptInfo; + private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath; + private getOrCreateScriptInfoOpenedByClientForNormalizedPath; + getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: { + fileExists(path: string): boolean; + }): ScriptInfo | undefined; + private getOrCreateScriptInfoWorker; + /** + * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred + */ + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; + getScriptInfoForPath(fileName: Path): ScriptInfo | undefined; + private addSourceInfoToSourceMap; + private addMissingSourceMapFile; + setHostConfiguration(args: protocol.ConfigureRequestArguments): void; + closeLog(): void; + /** + * This function rebuilds the project for every file opened by the client + * This does not reload contents of open files from disk. But we could do that if needed + */ + reloadProjects(): void; + /** + * This function goes through all the openFiles and tries to file the config file for them. + * If the config file is found and it refers to existing project, it reloads it either immediately + * or schedules it for reload depending on delayReload option + * If there is no existing project it just opens the configured project for the config file + * reloadForInfo provides a way to filter out files to reload configured project for + */ + private reloadConfiguredProjectForFiles; + /** + * Remove the root of inferred project if script info is part of another project + */ + private removeRootOfInferredProjectIfNowPartOfOtherProject; + /** + * This function is to update the project structure for every inferred project. + * It is called on the premise that all the configured projects are + * up to date. + * This will go through open files and assign them to inferred project if open file is not part of any other project + * After that all the inferred project graphs are updated + */ + private ensureProjectForOpenFiles; + /** + * Open file whose contents is managed by the client + * @param filename is absolute pathname + * @param fileContent is a known version of the file content that is more up to date than the one on disk + */ + openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult; + private findExternalProjectContainingOpenScriptInfo; + private getOrCreateOpenScriptInfo; + private assignProjectToOpenedScriptInfo; + private createAncestorProjects; + private ensureProjectChildren; + private cleanupAfterOpeningFile; + openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; + private removeOrphanConfiguredProjects; + private removeOrphanScriptInfos; + private telemetryOnOpenFile; + /** + * Close file whose contents is managed by the client + * @param filename is absolute pathname + */ + closeClientFile(uncheckedFileName: string): void; + private collectChanges; + private closeConfiguredProjectReferencedFromExternalProject; + closeExternalProject(uncheckedFileName: string): void; + openExternalProjects(projects: protocol.ExternalProject[]): void; + /** Makes a filename safe to insert in a RegExp */ + private static readonly filenameEscapeRegexp; + private static escapeFilenameForRegex; + resetSafeList(): void; + applySafeList(proj: protocol.ExternalProject): NormalizedPath[]; + openExternalProject(proj: protocol.ExternalProject): void; + hasDeferredExtension(): boolean; + private enableRequestedPluginsAsync; + private enableRequestedPluginsWorker; + private enableRequestedPluginsForProjectAsync; + configurePlugin(args: protocol.ConfigurePluginRequestArguments): void; + } + function formatMessage(msg: T, logger: Logger, byteLength: (s: string, encoding: BufferEncoding) => number, newLine: string): string; + interface ServerCancellationToken extends HostCancellationToken { + setRequest(requestId: number): void; + resetRequest(requestId: number): void; + } + const nullCancellationToken: ServerCancellationToken; + interface PendingErrorCheck { + fileName: NormalizedPath; + project: Project; + } + /** @deprecated use ts.server.protocol.CommandTypes */ + type CommandNames = protocol.CommandTypes; + /** @deprecated use ts.server.protocol.CommandTypes */ + const CommandNames: any; + type Event = (body: T, eventName: string) => void; + interface EventSender { + event: Event; + } + interface SessionOptions { + host: ServerHost; + cancellationToken: ServerCancellationToken; + useSingleInferredProject: boolean; + useInferredProjectPerProjectRoot: boolean; + typingsInstaller?: ITypingsInstaller; + byteLength: (buf: string, encoding?: BufferEncoding) => number; + hrtime: (start?: [ + number, + number, + ]) => [ + number, + number, + ]; + logger: Logger; + /** + * If falsy, all events are suppressed. + */ + canUseEvents: boolean; + canUseWatchEvents?: boolean; + eventHandler?: ProjectServiceEventHandler; + /** Has no effect if eventHandler is also specified. */ + suppressDiagnosticEvents?: boolean; + serverMode?: LanguageServiceMode; + throttleWaitMilliseconds?: number; + noGetErrOnBackgroundUpdate?: boolean; + globalPlugins?: readonly string[]; + pluginProbeLocations?: readonly string[]; + allowLocalPluginLoads?: boolean; + typesMapLocation?: string; + } + class Session implements EventSender { + private readonly gcTimer; + protected projectService: ProjectService; + private changeSeq; + private performanceData; + private currentRequestId; + private errorCheck; + protected host: ServerHost; + private readonly cancellationToken; + protected readonly typingsInstaller: ITypingsInstaller; + protected byteLength: (buf: string, encoding?: BufferEncoding) => number; + private hrtime; + protected logger: Logger; + protected canUseEvents: boolean; + private suppressDiagnosticEvents?; + private eventHandler; + private readonly noGetErrOnBackgroundUpdate?; + constructor(opts: SessionOptions); + private sendRequestCompletedEvent; + private addPerformanceData; + private performanceEventHandler; + private defaultEventHandler; + private projectsUpdatedInBackgroundEvent; + logError(err: Error, cmd: string): void; + private logErrorWorker; + send(msg: protocol.Message): void; + protected writeMessage(msg: protocol.Message): void; + event(body: T, eventName: string): void; + private semanticCheck; + private syntacticCheck; + private suggestionCheck; + private sendDiagnosticsEvent; + /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */ + private updateErrorCheck; + private cleanProjects; + private cleanup; + private getEncodedSyntacticClassifications; + private getEncodedSemanticClassifications; + private getProject; + private getConfigFileAndProject; + private getConfigFileDiagnostics; + private convertToDiagnosticsWithLinePositionFromDiagnosticFile; + private getCompilerOptionsDiagnostics; + private convertToDiagnosticsWithLinePosition; + private getDiagnosticsWorker; + private getDefinition; + private mapDefinitionInfoLocations; + private getDefinitionAndBoundSpan; + private findSourceDefinition; + private getEmitOutput; + private mapJSDocTagInfo; + private mapDisplayParts; + private mapSignatureHelpItems; + private mapDefinitionInfo; + private static mapToOriginalLocation; + private toFileSpan; + private toFileSpanWithContext; + private getTypeDefinition; + private mapImplementationLocations; + private getImplementation; + private getSyntacticDiagnosticsSync; + private getSemanticDiagnosticsSync; + private getSuggestionDiagnosticsSync; + private getJsxClosingTag; + private getLinkedEditingRange; + private getDocumentHighlights; + private provideInlayHints; + private setCompilerOptionsForInferredProjects; + private getProjectInfo; + private getProjectInfoWorker; + private getRenameInfo; + private getProjects; + private getDefaultProject; + private getRenameLocations; + private mapRenameInfo; + private toSpanGroups; + private getReferences; + private getFileReferences; + /** + * @param fileName is the name of the file to be opened + * @param fileContent is a version of the file content that is known to be more up to date than the one on disk + */ + private openClientFile; + private getPosition; + private getPositionInFile; + private getFileAndProject; + private getFileAndLanguageServiceForSyntacticOperation; + private getFileAndProjectWorker; + private getOutliningSpans; + private getTodoComments; + private getDocCommentTemplate; + private getSpanOfEnclosingComment; + private getIndentation; + private getBreakpointStatement; + private getNameOrDottedNameSpan; + private isValidBraceCompletion; + private getQuickInfoWorker; + private getFormattingEditsForRange; + private getFormattingEditsForRangeFull; + private getFormattingEditsForDocumentFull; + private getFormattingEditsAfterKeystrokeFull; + private getFormattingEditsAfterKeystroke; + private getCompletions; + private getCompletionEntryDetails; + private getCompileOnSaveAffectedFileList; + private emitFile; + private getSignatureHelpItems; + private toPendingErrorCheck; + private getDiagnostics; + private change; + private reload; + private saveToTmp; + private closeClientFile; + private mapLocationNavigationBarItems; + private getNavigationBarItems; + private toLocationNavigationTree; + private getNavigationTree; + private getNavigateToItems; + private getFullNavigateToItems; + private getSupportedCodeFixes; + private isLocation; + private extractPositionOrRange; + private getRange; + private getApplicableRefactors; + private getEditsForRefactor; + private getMoveToRefactoringFileSuggestions; + private organizeImports; + private getEditsForFileRename; + private getCodeFixes; + private getCombinedCodeFix; + private applyCodeActionCommand; + private getStartAndEndPosition; + private mapCodeAction; + private mapCodeFixAction; + private mapTextChangesToCodeEdits; + private mapTextChangeToCodeEdit; + private convertTextChangeToCodeEdit; + private getBraceMatching; + private getDiagnosticsForProject; + private configurePlugin; + private getSmartSelectionRange; + private toggleLineComment; + private toggleMultilineComment; + private commentSelection; + private uncommentSelection; + private mapSelectionRange; + private getScriptInfoFromProjectService; + private toProtocolCallHierarchyItem; + private toProtocolCallHierarchyIncomingCall; + private toProtocolCallHierarchyOutgoingCall; + private prepareCallHierarchy; + private provideCallHierarchyIncomingCalls; + private provideCallHierarchyOutgoingCalls; + getCanonicalFileName(fileName: string): string; + exit(): void; + private notRequired; + private requiredResponse; + private handlers; + addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse): void; + private setCurrentRequest; + private resetCurrentRequest; + executeWithRequestId(requestId: number, f: () => T): T; + executeCommand(request: protocol.Request): HandlerResponse; + onMessage(message: TMessage): void; + protected parseMessage(message: TMessage): protocol.Request; + protected toStringMessage(message: TMessage): string; + private getFormatOptions; + private getPreferences; + private getHostFormatOptions; + private getHostPreferences; + } + interface HandlerResponse { + response?: {}; + responseRequired?: boolean; + } + } namespace deno { function setIsNodeSourceFileCallback(callback: IsNodeSourceFileCallback): void; function setNodeBuiltInModuleNames(names: readonly string[]): void; function setNodeOnlyGlobalNames(names: readonly string[]): void; - function createDenoForkContext({ mergeSymbol, globals, nodeGlobals, ambientModuleSymbolRegex, }: { + function createDenoForkContext({ mergeSymbol, globals, nodeGlobals, ambientModuleSymbolRegex }: { mergeSymbol(target: ts.Symbol, source: ts.Symbol, unidirectional?: boolean): ts.Symbol; globals: ts.SymbolTable; nodeGlobals: ts.SymbolTable; @@ -46,7 +4164,7 @@ declare namespace ts { subPath: string | undefined; } } - const versionMajorMinor = "5.2"; + const versionMajorMinor = "5.3"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -376,9 +4494,11 @@ declare namespace ts { DefaultClause = 297, HeritageClause = 298, CatchClause = 299, - AssertClause = 300, - AssertEntry = 301, - ImportTypeAssertionContainer = 302, + ImportAttributes = 300, + ImportAttribute = 301, + /** @deprecated */ AssertClause = 300, + /** @deprecated */ AssertEntry = 301, + /** @deprecated */ ImportTypeAssertionContainer = 302, PropertyAssignment = 303, ShorthandPropertyAssignment = 304, SpreadAssignment = 305, @@ -472,13 +4592,157 @@ declare namespace ts { FirstJSDocNode = 316, LastJSDocNode = 357, FirstJSDocTagNode = 334, - LastJSDocTagNode = 357 + LastJSDocTagNode = 357, } type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; - type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.AmpersandAmpersandEqualsToken | SyntaxKind.BarBarToken | SyntaxKind.BarBarEqualsToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionQuestionEqualsToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.HashToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; - type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AccessorKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SatisfiesKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.UsingKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; + type PunctuationSyntaxKind = + | SyntaxKind.OpenBraceToken + | SyntaxKind.CloseBraceToken + | SyntaxKind.OpenParenToken + | SyntaxKind.CloseParenToken + | SyntaxKind.OpenBracketToken + | SyntaxKind.CloseBracketToken + | SyntaxKind.DotToken + | SyntaxKind.DotDotDotToken + | SyntaxKind.SemicolonToken + | SyntaxKind.CommaToken + | SyntaxKind.QuestionDotToken + | SyntaxKind.LessThanToken + | SyntaxKind.LessThanSlashToken + | SyntaxKind.GreaterThanToken + | SyntaxKind.LessThanEqualsToken + | SyntaxKind.GreaterThanEqualsToken + | SyntaxKind.EqualsEqualsToken + | SyntaxKind.ExclamationEqualsToken + | SyntaxKind.EqualsEqualsEqualsToken + | SyntaxKind.ExclamationEqualsEqualsToken + | SyntaxKind.EqualsGreaterThanToken + | SyntaxKind.PlusToken + | SyntaxKind.MinusToken + | SyntaxKind.AsteriskToken + | SyntaxKind.AsteriskAsteriskToken + | SyntaxKind.SlashToken + | SyntaxKind.PercentToken + | SyntaxKind.PlusPlusToken + | SyntaxKind.MinusMinusToken + | SyntaxKind.LessThanLessThanToken + | SyntaxKind.GreaterThanGreaterThanToken + | SyntaxKind.GreaterThanGreaterThanGreaterThanToken + | SyntaxKind.AmpersandToken + | SyntaxKind.BarToken + | SyntaxKind.CaretToken + | SyntaxKind.ExclamationToken + | SyntaxKind.TildeToken + | SyntaxKind.AmpersandAmpersandToken + | SyntaxKind.AmpersandAmpersandEqualsToken + | SyntaxKind.BarBarToken + | SyntaxKind.BarBarEqualsToken + | SyntaxKind.QuestionQuestionToken + | SyntaxKind.QuestionQuestionEqualsToken + | SyntaxKind.QuestionToken + | SyntaxKind.ColonToken + | SyntaxKind.AtToken + | SyntaxKind.BacktickToken + | SyntaxKind.HashToken + | SyntaxKind.EqualsToken + | SyntaxKind.PlusEqualsToken + | SyntaxKind.MinusEqualsToken + | SyntaxKind.AsteriskEqualsToken + | SyntaxKind.AsteriskAsteriskEqualsToken + | SyntaxKind.SlashEqualsToken + | SyntaxKind.PercentEqualsToken + | SyntaxKind.LessThanLessThanEqualsToken + | SyntaxKind.GreaterThanGreaterThanEqualsToken + | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken + | SyntaxKind.AmpersandEqualsToken + | SyntaxKind.BarEqualsToken + | SyntaxKind.CaretEqualsToken; + type KeywordSyntaxKind = + | SyntaxKind.AbstractKeyword + | SyntaxKind.AccessorKeyword + | SyntaxKind.AnyKeyword + | SyntaxKind.AsKeyword + | SyntaxKind.AssertsKeyword + | SyntaxKind.AssertKeyword + | SyntaxKind.AsyncKeyword + | SyntaxKind.AwaitKeyword + | SyntaxKind.BigIntKeyword + | SyntaxKind.BooleanKeyword + | SyntaxKind.BreakKeyword + | SyntaxKind.CaseKeyword + | SyntaxKind.CatchKeyword + | SyntaxKind.ClassKeyword + | SyntaxKind.ConstKeyword + | SyntaxKind.ConstructorKeyword + | SyntaxKind.ContinueKeyword + | SyntaxKind.DebuggerKeyword + | SyntaxKind.DeclareKeyword + | SyntaxKind.DefaultKeyword + | SyntaxKind.DeleteKeyword + | SyntaxKind.DoKeyword + | SyntaxKind.ElseKeyword + | SyntaxKind.EnumKeyword + | SyntaxKind.ExportKeyword + | SyntaxKind.ExtendsKeyword + | SyntaxKind.FalseKeyword + | SyntaxKind.FinallyKeyword + | SyntaxKind.ForKeyword + | SyntaxKind.FromKeyword + | SyntaxKind.FunctionKeyword + | SyntaxKind.GetKeyword + | SyntaxKind.GlobalKeyword + | SyntaxKind.IfKeyword + | SyntaxKind.ImplementsKeyword + | SyntaxKind.ImportKeyword + | SyntaxKind.InferKeyword + | SyntaxKind.InKeyword + | SyntaxKind.InstanceOfKeyword + | SyntaxKind.InterfaceKeyword + | SyntaxKind.IntrinsicKeyword + | SyntaxKind.IsKeyword + | SyntaxKind.KeyOfKeyword + | SyntaxKind.LetKeyword + | SyntaxKind.ModuleKeyword + | SyntaxKind.NamespaceKeyword + | SyntaxKind.NeverKeyword + | SyntaxKind.NewKeyword + | SyntaxKind.NullKeyword + | SyntaxKind.NumberKeyword + | SyntaxKind.ObjectKeyword + | SyntaxKind.OfKeyword + | SyntaxKind.PackageKeyword + | SyntaxKind.PrivateKeyword + | SyntaxKind.ProtectedKeyword + | SyntaxKind.PublicKeyword + | SyntaxKind.ReadonlyKeyword + | SyntaxKind.OutKeyword + | SyntaxKind.OverrideKeyword + | SyntaxKind.RequireKeyword + | SyntaxKind.ReturnKeyword + | SyntaxKind.SatisfiesKeyword + | SyntaxKind.SetKeyword + | SyntaxKind.StaticKeyword + | SyntaxKind.StringKeyword + | SyntaxKind.SuperKeyword + | SyntaxKind.SwitchKeyword + | SyntaxKind.SymbolKeyword + | SyntaxKind.ThisKeyword + | SyntaxKind.ThrowKeyword + | SyntaxKind.TrueKeyword + | SyntaxKind.TryKeyword + | SyntaxKind.TypeKeyword + | SyntaxKind.TypeOfKeyword + | SyntaxKind.UndefinedKeyword + | SyntaxKind.UniqueKeyword + | SyntaxKind.UnknownKeyword + | SyntaxKind.UsingKeyword + | SyntaxKind.VarKeyword + | SyntaxKind.VoidKeyword + | SyntaxKind.WhileKeyword + | SyntaxKind.WithKeyword + | SyntaxKind.YieldKeyword; type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AccessorKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.InKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; @@ -516,36 +4780,36 @@ declare namespace ts { ReachabilityCheckFlags = 1536, ReachabilityAndEmitFlags = 5632, ContextFlags = 101441536, - TypeExcludesFlags = 81920 + TypeExcludesFlags = 81920, } enum ModifierFlags { None = 0, - Export = 1, - Ambient = 2, - Public = 4, - Private = 8, - Protected = 16, - Static = 32, - Readonly = 64, - Accessor = 128, - Abstract = 256, - Async = 512, - Default = 1024, - Const = 2048, - HasComputedJSDocModifiers = 4096, - Deprecated = 8192, - Override = 16384, - In = 32768, - Out = 65536, - Decorator = 131072, + Public = 1, + Private = 2, + Protected = 4, + Readonly = 8, + Override = 16, + Export = 32, + Abstract = 64, + Ambient = 128, + Static = 256, + Accessor = 512, + Async = 1024, + Default = 2048, + Const = 4096, + In = 8192, + Out = 16384, + Decorator = 32768, + Deprecated = 65536, + HasComputedJSDocModifiers = 268435456, HasComputedFlags = 536870912, - AccessibilityModifier = 28, - ParameterPropertyModifier = 16476, - NonPublicAccessibilityModifier = 24, - TypeScriptModifier = 117086, - ExportDefault = 1025, - All = 258047, - Modifier = 126975 + AccessibilityModifier = 7, + ParameterPropertyModifier = 31, + NonPublicAccessibilityModifier = 6, + TypeScriptModifier = 28895, + ExportDefault = 2080, + All = 131071, + Modifier = 98303, } enum JsxFlags { None = 0, @@ -553,7 +4817,7 @@ declare namespace ts { IntrinsicNamedElement = 1, /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ IntrinsicIndexedElement = 2, - IntrinsicElement = 3 + IntrinsicElement = 3, } interface Node extends ReadonlyTextRange { readonly kind: SyntaxKind; @@ -586,7 +4850,71 @@ declare namespace ts { interface FlowContainer extends Node { _flowContainerBrand: any; } - type HasJSDoc = AccessorDeclaration | ArrowFunction | BinaryExpression | Block | BreakStatement | CallSignatureDeclaration | CaseClause | ClassLikeDeclaration | ClassStaticBlockDeclaration | ConstructorDeclaration | ConstructorTypeNode | ConstructSignatureDeclaration | ContinueStatement | DebuggerStatement | DoStatement | ElementAccessExpression | EmptyStatement | EndOfFileToken | EnumDeclaration | EnumMember | ExportAssignment | ExportDeclaration | ExportSpecifier | ExpressionStatement | ForInStatement | ForOfStatement | ForStatement | FunctionDeclaration | FunctionExpression | FunctionTypeNode | Identifier | IfStatement | ImportDeclaration | ImportEqualsDeclaration | IndexSignatureDeclaration | InterfaceDeclaration | JSDocFunctionType | JSDocSignature | LabeledStatement | MethodDeclaration | MethodSignature | ModuleDeclaration | NamedTupleMember | NamespaceExportDeclaration | ObjectLiteralExpression | ParameterDeclaration | ParenthesizedExpression | PropertyAccessExpression | PropertyAssignment | PropertyDeclaration | PropertySignature | ReturnStatement | SemicolonClassElement | ShorthandPropertyAssignment | SpreadAssignment | SwitchStatement | ThrowStatement | TryStatement | TypeAliasDeclaration | TypeParameterDeclaration | VariableDeclaration | VariableStatement | WhileStatement | WithStatement; + type HasJSDoc = + | AccessorDeclaration + | ArrowFunction + | BinaryExpression + | Block + | BreakStatement + | CallSignatureDeclaration + | CaseClause + | ClassLikeDeclaration + | ClassStaticBlockDeclaration + | ConstructorDeclaration + | ConstructorTypeNode + | ConstructSignatureDeclaration + | ContinueStatement + | DebuggerStatement + | DoStatement + | ElementAccessExpression + | EmptyStatement + | EndOfFileToken + | EnumDeclaration + | EnumMember + | ExportAssignment + | ExportDeclaration + | ExportSpecifier + | ExpressionStatement + | ForInStatement + | ForOfStatement + | ForStatement + | FunctionDeclaration + | FunctionExpression + | FunctionTypeNode + | Identifier + | IfStatement + | ImportDeclaration + | ImportEqualsDeclaration + | IndexSignatureDeclaration + | InterfaceDeclaration + | JSDocFunctionType + | JSDocSignature + | LabeledStatement + | MethodDeclaration + | MethodSignature + | ModuleDeclaration + | NamedTupleMember + | NamespaceExportDeclaration + | ObjectLiteralExpression + | ParameterDeclaration + | ParenthesizedExpression + | PropertyAccessExpression + | PropertyAssignment + | PropertyDeclaration + | PropertySignature + | ReturnStatement + | SemicolonClassElement + | ShorthandPropertyAssignment + | SpreadAssignment + | SwitchStatement + | ThrowStatement + | TryStatement + | TypeAliasDeclaration + | TypeParameterDeclaration + | VariableDeclaration + | VariableStatement + | WhileStatement + | WithStatement; type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; type HasTypeArguments = CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement | JsxSelfClosingElement; type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; @@ -650,7 +4978,7 @@ declare namespace ts { ReservedInNestedScopes = 8, Optimistic = 16, FileLevel = 32, - AllowNameSubstitution = 64 + AllowNameSubstitution = 64, } interface Identifier extends PrimaryExpression, Declaration, JSDocContainer, FlowContainer { readonly kind: SyntaxKind.Identifier; @@ -678,7 +5006,7 @@ declare namespace ts { readonly right: Identifier; } type EntityName = Identifier | QualifiedName; - type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier; + type PropertyName = Identifier | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier; type MemberName = Identifier | PrivateIdentifier; type DeclarationName = PropertyName | JsxAttributeName | StringLiteralLike | ElementAccessExpression | BindingPattern | EntityNameExpression; interface Declaration extends Node { @@ -901,17 +5229,19 @@ declare namespace ts { interface KeywordTypeNode extends KeywordToken, TypeNode { readonly kind: TKind; } + /** @deprecated */ interface ImportTypeAssertionContainer extends Node { readonly kind: SyntaxKind.ImportTypeAssertionContainer; readonly parent: ImportTypeNode; - readonly assertClause: AssertClause; + /** @deprecated */ readonly assertClause: AssertClause; readonly multiLine?: boolean; } interface ImportTypeNode extends NodeWithTypeArguments { readonly kind: SyntaxKind.ImportType; readonly isTypeOf: boolean; readonly argument: TypeNode; - readonly assertions?: ImportTypeAssertionContainer; + /** @deprecated */ readonly assertions?: ImportTypeAssertionContainer; + readonly attributes?: ImportAttributes; readonly qualifier?: EntityName; } interface ThisTypeNode extends TypeNode { @@ -1218,7 +5548,7 @@ declare namespace ts { Octal = 32, HexSpecifier = 64, BinarySpecifier = 128, - OctalSpecifier = 256 + OctalSpecifier = 256, } interface NumericLiteral extends LiteralExpression, Declaration { readonly kind: SyntaxKind.NumericLiteral; @@ -1346,7 +5676,10 @@ declare namespace ts { readonly typeArguments?: NodeArray; readonly template: TemplateLiteral; } - type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator | JsxOpeningLikeElement; + interface InstanceofExpression extends BinaryExpression { + readonly operatorToken: Token; + } + type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator | JsxOpeningLikeElement | InstanceofExpression; interface AsExpression extends Expression { readonly kind: SyntaxKind.AsExpression; readonly expression: Expression; @@ -1702,7 +6035,8 @@ declare namespace ts { readonly importClause?: ImportClause; /** If this is not a StringLiteral it will be a grammar error. */ readonly moduleSpecifier: Expression; - readonly assertClause?: AssertClause; + /** @deprecated */ readonly assertClause?: AssertClause; + readonly attributes?: ImportAttributes; } type NamedImportBindings = NamespaceImport | NamedImports; type NamedExportBindings = NamespaceExport | NamedExports; @@ -1713,17 +6047,26 @@ declare namespace ts { readonly name?: Identifier; readonly namedBindings?: NamedImportBindings; } - type AssertionKey = Identifier | StringLiteral; - interface AssertEntry extends Node { - readonly kind: SyntaxKind.AssertEntry; - readonly parent: AssertClause; - readonly name: AssertionKey; + /** @deprecated */ + type AssertionKey = ImportAttributeName; + /** @deprecated */ + interface AssertEntry extends ImportAttribute { + } + /** @deprecated */ + interface AssertClause extends ImportAttributes { + } + type ImportAttributeName = Identifier | StringLiteral; + interface ImportAttribute extends Node { + readonly kind: SyntaxKind.ImportAttribute; + readonly parent: ImportAttributes; + readonly name: ImportAttributeName; readonly value: Expression; } - interface AssertClause extends Node { - readonly kind: SyntaxKind.AssertClause; + interface ImportAttributes extends Node { + readonly token: SyntaxKind.WithKeyword | SyntaxKind.AssertKeyword; + readonly kind: SyntaxKind.ImportAttributes; readonly parent: ImportDeclaration | ExportDeclaration; - readonly elements: NodeArray; + readonly elements: NodeArray; readonly multiLine?: boolean; } interface NamespaceImport extends NamedDeclaration { @@ -1749,7 +6092,8 @@ declare namespace ts { readonly exportClause?: NamedExportBindings; /** If this is not a StringLiteral it will be a grammar error. */ readonly moduleSpecifier?: Expression; - readonly assertClause?: AssertClause; + /** @deprecated */ readonly assertClause?: AssertClause; + readonly attributes?: ImportAttributes; } interface NamedImports extends Node { readonly kind: SyntaxKind.NamedImports; @@ -1778,41 +6122,50 @@ declare namespace ts { } type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; type TypeOnlyCompatibleAliasDeclaration = ImportClause | ImportEqualsDeclaration | NamespaceImport | ImportOrExportSpecifier | ExportDeclaration | NamespaceExport; - type TypeOnlyImportDeclaration = ImportClause & { - readonly isTypeOnly: true; - readonly name: Identifier; - } | ImportEqualsDeclaration & { - readonly isTypeOnly: true; - } | NamespaceImport & { - readonly parent: ImportClause & { + type TypeOnlyImportDeclaration = + | ImportClause & { readonly isTypeOnly: true; - }; - } | ImportSpecifier & ({ - readonly isTypeOnly: true; - } | { - readonly parent: NamedImports & { + readonly name: Identifier; + } + | ImportEqualsDeclaration & { + readonly isTypeOnly: true; + } + | NamespaceImport & { readonly parent: ImportClause & { readonly isTypeOnly: true; }; - }; - }); - type TypeOnlyExportDeclaration = ExportSpecifier & ({ - readonly isTypeOnly: true; - } | { - readonly parent: NamedExports & { - readonly parent: ExportDeclaration & { + } + | ImportSpecifier + & ({ readonly isTypeOnly: true; - }; - }; - }) | ExportDeclaration & { - readonly isTypeOnly: true; - readonly moduleSpecifier: Expression; - } | NamespaceExport & { - readonly parent: ExportDeclaration & { + } | { + readonly parent: NamedImports & { + readonly parent: ImportClause & { + readonly isTypeOnly: true; + }; + }; + }); + type TypeOnlyExportDeclaration = + | ExportSpecifier + & ({ + readonly isTypeOnly: true; + } | { + readonly parent: NamedExports & { + readonly parent: ExportDeclaration & { + readonly isTypeOnly: true; + }; + }; + }) + | ExportDeclaration & { readonly isTypeOnly: true; readonly moduleSpecifier: Expression; + } + | NamespaceExport & { + readonly parent: ExportDeclaration & { + readonly isTypeOnly: true; + readonly moduleSpecifier: Expression; + }; }; - }; type TypeOnlyAliasDeclaration = TypeOnlyImportDeclaration | TypeOnlyExportDeclaration; /** * This is either an `export =` or an `export default` declaration. @@ -2060,7 +6413,7 @@ declare namespace ts { Referenced = 2048, Shared = 4096, Label = 12, - Condition = 96 + Condition = 96, } type FlowNode = FlowStart | FlowLabel | FlowAssignment | FlowCondition | FlowSwitchClause | FlowArrayMutation | FlowCall | FlowReduceLabel; interface FlowNodeBase { @@ -2370,7 +6723,7 @@ declare namespace ts { DiagnosticsPresent_OutputsSkipped = 1, DiagnosticsPresent_OutputsGenerated = 2, InvalidProject_OutputsSkipped = 3, - ProjectReferenceCycle_OutputsSkipped = 4 + ProjectReferenceCycle_OutputsSkipped = 4, } interface EmitResult { emitSkipped: boolean; @@ -2400,9 +6753,11 @@ declare namespace ts { /** Note that the resulting nodes cannot be checked. */ typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeNode | undefined; /** Note that the resulting nodes cannot be checked. */ - signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): SignatureDeclaration & { - typeArguments?: NodeArray; - } | undefined; + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): + | SignatureDeclaration & { + typeArguments?: NodeArray; + } + | undefined; /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): IndexSignatureDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ @@ -2457,6 +6812,7 @@ declare namespace ts { isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; + getMergedSymbol(symbol: Symbol): Symbol; getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean; /** Follow all aliases to get the original symbol. */ @@ -2559,7 +6915,7 @@ declare namespace ts { IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, - InInitialEntityName = 16777216 + InInitialEntityName = 16777216, } enum TypeFormatFlags { None = 0, @@ -2584,20 +6940,20 @@ declare namespace ts { InElementType = 2097152, InFirstTypeArgument = 4194304, InTypeAlias = 8388608, - NodeBuilderFlagsMask = 848330091 + NodeBuilderFlagsMask = 848330091, } enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, AllowAnyNodeKind = 4, - UseAliasDefinedOutsideCurrentScope = 8 + UseAliasDefinedOutsideCurrentScope = 8, } enum TypePredicateKind { This = 0, Identifier = 1, AssertsThis = 2, - AssertsIdentifier = 3 + AssertsIdentifier = 3, } interface TypePredicateBase { kind: TypePredicateKind; @@ -2688,7 +7044,7 @@ declare namespace ts { ExportHasLocal = 944, BlockScoped = 418, PropertyOrAccessor = 98308, - ClassMember = 106500 + ClassMember = 106500, } interface Symbol { flags: SymbolFlags; @@ -2725,7 +7081,7 @@ declare namespace ts { Resolving = "__resolving__", ExportEquals = "export=", Default = "default", - This = "this" + This = "this", } /** * This represents a string whose leading underscore have been escaped by adding extra leading underscores. @@ -2735,11 +7091,14 @@ declare namespace ts { * with a normal string (which is good, it cannot be misused on assignment or on usage), * while still being comparable with a normal string via === (also good) and castable from a string. */ - type __String = (string & { - __escapedIdentifier: void; - }) | (void & { - __escapedIdentifier: void; - }) | InternalSymbolName; + type __String = + | (string & { + __escapedIdentifier: void; + }) + | (void & { + __escapedIdentifier: void; + }) + | InternalSymbolName; /** @deprecated Use ReadonlyMap<__String, T> instead. */ type ReadonlyUnderscoreEscapedMap = ReadonlyMap<__String, T>; /** @deprecated Use Map<__String, T> instead. */ @@ -2795,7 +7154,7 @@ declare namespace ts { InstantiablePrimitive = 406847488, Instantiable = 465829888, StructuredOrInstantiable = 469499904, - Narrowable = 536624127 + Narrowable = 536624127, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2872,7 +7231,7 @@ declare namespace ts { ClassOrInterface = 3, ContainsSpread = 2097152, ObjectRestType = 4194304, - InstantiationExpressionType = 8388608 + InstantiationExpressionType = 8388608, } interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2920,7 +7279,7 @@ declare namespace ts { Fixed = 3, Variable = 12, NonRequired = 14, - NonRest = 11 + NonRest = 11, } interface TupleType extends GenericType { elementFlags: readonly ElementFlags[]; @@ -2997,12 +7356,13 @@ declare namespace ts { } enum SignatureKind { Call = 0, - Construct = 1 + Construct = 1, } interface Signature { declaration?: SignatureDeclaration | JSDocSignature; typeParameters?: readonly TypeParameter[]; parameters: readonly Symbol[]; + thisParameter?: Symbol; } interface Signature { getDeclaration(): SignatureDeclaration; @@ -3015,7 +7375,7 @@ declare namespace ts { } enum IndexKind { String = 0, - Number = 1 + Number = 1, } interface IndexInfo { keyType: Type; @@ -3038,7 +7398,7 @@ declare namespace ts { AlwaysStrict = 1024, MaxValue = 2048, PriorityImpliesCombination = 416, - Circularity = -1 + Circularity = -1, } interface FileExtensionInfo { extension: string; @@ -3089,7 +7449,7 @@ declare namespace ts { Warning = 0, Error = 1, Suggestion = 2, - Message = 3 + Message = 3, } enum ModuleResolutionKind { Classic = 1, @@ -3102,7 +7462,7 @@ declare namespace ts { Node10 = 2, Node16 = 3, NodeNext = 99, - Bundler = 100 + Bundler = 100, } enum ModuleDetectionKind { /** @@ -3116,7 +7476,7 @@ declare namespace ts { /** * Consider all non-declaration files modules, regardless of present syntax */ - Force = 3 + Force = 3, } interface PluginImport { name: string; @@ -3137,19 +7497,19 @@ declare namespace ts { DynamicPriorityPolling = 2, FixedChunkSizePolling = 3, UseFsEvents = 4, - UseFsEventsOnParentDirectory = 5 + UseFsEventsOnParentDirectory = 5, } enum WatchDirectoryKind { UseFsEvents = 0, FixedPollingInterval = 1, DynamicPriorityPolling = 2, - FixedChunkSizePolling = 3 + FixedChunkSizePolling = 3, } enum PollingWatchKind { FixedInterval = 0, PriorityInterval = 1, DynamicPriority = 2, - FixedChunkSize = 3 + FixedChunkSize = 3, } type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; interface CompilerOptions { @@ -3285,7 +7645,7 @@ declare namespace ts { ES2022 = 7, ESNext = 99, Node16 = 100, - NodeNext = 199 + NodeNext = 199, } enum JsxEmit { None = 0, @@ -3293,16 +7653,16 @@ declare namespace ts { React = 2, ReactNative = 3, ReactJSX = 4, - ReactJSXDev = 5 + ReactJSXDev = 5, } enum ImportsNotUsedAsValues { Remove = 0, Preserve = 1, - Error = 2 + Error = 2, } enum NewLineKind { CarriageReturnLineFeed = 0, - LineFeed = 1 + LineFeed = 1, } interface LineAndCharacter { /** 0-based. */ @@ -3321,7 +7681,7 @@ declare namespace ts { * Used on extensions that doesn't define the ScriptKind but the content defines it. * Deferred extensions are going to be included in all project contexts. */ - Deferred = 7 + Deferred = 7, } enum ScriptTarget { ES3 = 0, @@ -3336,11 +7696,11 @@ declare namespace ts { ES2022 = 9, ESNext = 99, JSON = 100, - Latest = 99 + Latest = 99, } enum LanguageVariant { Standard = 0, - JSX = 1 + JSX = 1, } /** Either a parsed command line or a parsed tsconfig.json */ interface ParsedCommandLine { @@ -3356,7 +7716,7 @@ declare namespace ts { } enum WatchDirectoryFlags { None = 0, - Recursive = 1 + Recursive = 1, } interface CreateProgramOptions { rootNames: readonly string[]; @@ -3450,7 +7810,7 @@ declare namespace ts { Dmts = ".d.mts", Cjs = ".cjs", Cts = ".cts", - Dcts = ".d.cts" + Dcts = ".d.cts", } interface ResolvedModuleWithFailedLookupLocations { readonly resolvedModule: ResolvedModuleFull | undefined; @@ -3496,6 +7856,7 @@ declare namespace ts { hasInvalidatedResolutions?(filePath: Path): boolean; createHash?(data: string): string; getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; + jsDocParsingMode?: JSDocParsingMode; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -3537,7 +7898,7 @@ declare namespace ts { CustomPrologue = 2097152, NoHoisting = 4194304, Iterator = 8388608, - NoAsciiEscaping = 16777216 + NoAsciiEscaping = 16777216, } interface EmitHelperBase { readonly name: string; @@ -3562,7 +7923,7 @@ declare namespace ts { MappedTypeParameter = 3, Unspecified = 4, EmbeddedStatement = 5, - JsxAttributeValue = 6 + JsxAttributeValue = 6, } enum OuterExpressionKinds { Parentheses = 1, @@ -3571,7 +7932,7 @@ declare namespace ts { PartiallyEmittedExpressions = 8, Assertions = 6, All = 15, - ExcludeJSDocTypeAssertion = 16 + ExcludeJSDocTypeAssertion = 16, } type ImmediatelyInvokedFunctionExpression = CallExpression & { readonly expression: FunctionExpression; @@ -3696,8 +8057,8 @@ declare namespace ts { updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; createInferTypeNode(typeParameter: TypeParameterDeclaration): InferTypeNode; updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration): InferTypeNode; - createImportTypeNode(argument: TypeNode, assertions?: ImportTypeAssertionContainer, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; - updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, assertions: ImportTypeAssertionContainer | undefined, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode; + createImportTypeNode(argument: TypeNode, attributes?: ImportAttributes, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; + updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, attributes: ImportAttributes | undefined, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode; createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; createThisTypeNode(): ThisTypeNode; @@ -3854,16 +8215,20 @@ declare namespace ts { updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; createImportEqualsDeclaration(modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; updateImportEqualsDeclaration(node: ImportEqualsDeclaration, modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - createImportDeclaration(modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause): ImportDeclaration; - updateImportDeclaration(node: ImportDeclaration, modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; + createImportDeclaration(modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, attributes?: ImportAttributes): ImportDeclaration; + updateImportDeclaration(node: ImportDeclaration, modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, attributes: ImportAttributes | undefined): ImportDeclaration; createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; - createAssertClause(elements: NodeArray, multiLine?: boolean): AssertClause; - updateAssertClause(node: AssertClause, elements: NodeArray, multiLine?: boolean): AssertClause; - createAssertEntry(name: AssertionKey, value: Expression): AssertEntry; - updateAssertEntry(node: AssertEntry, name: AssertionKey, value: Expression): AssertEntry; - createImportTypeAssertionContainer(clause: AssertClause, multiLine?: boolean): ImportTypeAssertionContainer; - updateImportTypeAssertionContainer(node: ImportTypeAssertionContainer, clause: AssertClause, multiLine?: boolean): ImportTypeAssertionContainer; + /** @deprecated */ createAssertClause(elements: NodeArray, multiLine?: boolean): AssertClause; + /** @deprecated */ updateAssertClause(node: AssertClause, elements: NodeArray, multiLine?: boolean): AssertClause; + /** @deprecated */ createAssertEntry(name: AssertionKey, value: Expression): AssertEntry; + /** @deprecated */ updateAssertEntry(node: AssertEntry, name: AssertionKey, value: Expression): AssertEntry; + /** @deprecated */ createImportTypeAssertionContainer(clause: AssertClause, multiLine?: boolean): ImportTypeAssertionContainer; + /** @deprecated */ updateImportTypeAssertionContainer(node: ImportTypeAssertionContainer, clause: AssertClause, multiLine?: boolean): ImportTypeAssertionContainer; + createImportAttributes(elements: NodeArray, multiLine?: boolean): ImportAttributes; + updateImportAttributes(node: ImportAttributes, elements: NodeArray, multiLine?: boolean): ImportAttributes; + createImportAttribute(name: ImportAttributeName, value: Expression): ImportAttribute; + updateImportAttribute(node: ImportAttribute, name: ImportAttributeName, value: Expression): ImportAttribute; createNamespaceImport(name: Identifier): NamespaceImport; updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport; createNamespaceExport(name: Identifier): NamespaceExport; @@ -3874,8 +8239,8 @@ declare namespace ts { updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; createExportAssignment(modifiers: readonly ModifierLike[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; updateExportAssignment(node: ExportAssignment, modifiers: readonly ModifierLike[] | undefined, expression: Expression): ExportAssignment; - createExportDeclaration(modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, assertClause?: AssertClause): ExportDeclaration; - updateExportDeclaration(node: ExportDeclaration, modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, assertClause: AssertClause | undefined): ExportDeclaration; + createExportDeclaration(modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, attributes?: ImportAttributes): ExportDeclaration; + updateExportDeclaration(node: ExportDeclaration, modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, attributes: ImportAttributes | undefined): ExportDeclaration; createNamedExports(elements: readonly ExportSpecifier[]): NamedExports; updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]): NamedExports; createExportSpecifier(isTypeOnly: boolean, propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; @@ -4056,6 +8421,18 @@ declare namespace ts { createExportDefault(expression: Expression): ExportAssignment; createExternalModuleExport(exportName: Identifier): ExportDeclaration; restoreOuterExpressions(outerExpression: Expression | undefined, innerExpression: Expression, kinds?: OuterExpressionKinds): Expression; + /** + * Updates a node that may contain modifiers, replacing only the modifiers of the node. + */ + replaceModifiers(node: T, modifiers: readonly Modifier[] | ModifierFlags | undefined): T; + /** + * Updates a node that may contain decorators or modifiers, replacing only the decorators and modifiers of the node. + */ + replaceDecoratorsAndModifiers(node: T, modifiers: readonly ModifierLike[] | undefined): T; + /** + * Updates a node that contains a property name, replacing only the name of the node. + */ + replacePropertyName(node: T, name: T["name"]): T; } interface CoreTransformationContext { readonly factory: NodeFactory; @@ -4324,7 +8701,8 @@ declare namespace ts { ObjectBindingPatternElements = 525136, ArrayBindingPatternElements = 524880, ObjectLiteralExpressionProperties = 526226, - ImportClauseEntries = 526226, + ImportAttributes = 526226, + /** @deprecated */ ImportClauseEntries = 526226, ArrayLiteralExpressionElements = 8914, CommaListElements = 528, CallExpressionArguments = 2576, @@ -4351,7 +8729,34 @@ declare namespace ts { TypeParameters = 53776, Parameters = 2576, IndexSignatureParameters = 8848, - JSDocComment = 33 + JSDocComment = 33, + } + enum JSDocParsingMode { + /** + * Always parse JSDoc comments and include them in the AST. + * + * This is the default if no mode is provided. + */ + ParseAll = 0, + /** + * Never parse JSDoc comments, mo matter the file type. + */ + ParseNone = 1, + /** + * Parse only JSDoc comments which are needed to provide correct type errors. + * + * This will always parse JSDoc in non-TS files, but only parse JSDoc comments + * containing `@see` and `@link` in TS files. + */ + ParseForTypeErrors = 2, + /** + * Parse only JSDoc comments which are needed to provide correct type info. + * + * This will always parse JSDoc in non-TS files, but never in TS files. + * + * Note: Do not use this mode if you require accurate type errors; use {@link ParseForTypeErrors} instead. + */ + ParseForTypeInfo = 3, } interface UserPreferences { readonly disableSuggestions?: boolean; @@ -4384,12 +8789,14 @@ declare namespace ts { readonly interactiveInlayHints?: boolean; readonly allowRenameOfImportPath?: boolean; readonly autoImportFileExcludePatterns?: string[]; + readonly preferTypeOnlyAutoImports?: boolean; readonly organizeImportsIgnoreCase?: "auto" | boolean; readonly organizeImportsCollation?: "ordinal" | "unicode"; readonly organizeImportsLocale?: string; readonly organizeImportsNumericCollation?: boolean; readonly organizeImportsAccentCollation?: boolean; readonly organizeImportsCaseFirst?: "upper" | "lower" | false; + readonly excludeLibrarySymbolsInNavTo?: boolean; } /** Represents a bigint literal value without requiring bigint support */ interface PseudoBigInt { @@ -4399,7 +8806,7 @@ declare namespace ts { enum FileWatcherEventKind { Created = 0, Changed = 1, - Deleted = 2 + Deleted = 2, } type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind, modifiedTime?: Date) => void; type DirectoryWatcherCallback = (fileName: string) => void; @@ -4513,6 +8920,8 @@ declare namespace ts { setOnError(onError: ErrorCallback | undefined): void; setScriptTarget(scriptTarget: ScriptTarget): void; setLanguageVariant(variant: LanguageVariant): void; + setScriptKind(scriptKind: ScriptKind): void; + setJSDocParsingMode(kind: JSDocParsingMode): void; /** @deprecated use {@link resetTokenState} */ setTextPos(textPos: number): void; resetTokenState(pos: number): void; @@ -4752,8 +9161,8 @@ declare namespace ts { function isTypeOnlyImportDeclaration(node: Node): node is TypeOnlyImportDeclaration; function isTypeOnlyExportDeclaration(node: Node): node is TypeOnlyExportDeclaration; function isTypeOnlyImportOrExportDeclaration(node: Node): node is TypeOnlyAliasDeclaration; - function isAssertionKey(node: Node): node is AssertionKey; function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken; + function isImportAttributeName(node: Node): node is ImportAttributeName; function isModifier(node: Node): node is Modifier; function isEntityName(node: Node): node is EntityName; function isPropertyName(node: Node): node is PropertyName; @@ -4811,7 +9220,7 @@ declare namespace ts { function isJSDocLinkLike(node: Node): node is JSDocLink | JSDocLinkCode | JSDocLinkPlain; function hasRestParameter(s: SignatureDeclaration | JSDocSignature): boolean; function isRestParameter(node: ParameterDeclaration | JSDocParameterTag): boolean; - let unchangedTextChangeRange: TextChangeRange; + const unchangedTextChangeRange: TextChangeRange; type ParameterPropertyDeclaration = ParameterDeclaration & { parent: ConstructorDeclaration; name: Identifier; @@ -5055,8 +9464,12 @@ declare namespace ts { function isImportDeclaration(node: Node): node is ImportDeclaration; function isImportClause(node: Node): node is ImportClause; function isImportTypeAssertionContainer(node: Node): node is ImportTypeAssertionContainer; + /** @deprecated */ function isAssertClause(node: Node): node is AssertClause; + /** @deprecated */ function isAssertEntry(node: Node): node is AssertEntry; + function isImportAttributes(node: Node): node is ImportAttributes; + function isImportAttribute(node: Node): node is ImportAttribute; function isNamespaceImport(node: Node): node is NamespaceImport; function isNamespaceExport(node: Node): node is NamespaceExport; function isNamedImports(node: Node): node is NamedImports; @@ -5182,6 +9595,7 @@ declare namespace ts { * check specified by `isFileProbablyExternalModule` will be used to set the field. */ setExternalModuleIndicator?: (file: SourceFile) => void; + jsDocParsingMode?: JSDocParsingMode; } function parseCommandLine(commandLine: readonly string[], readFile?: (path: string) => string | undefined): ParsedCommandLine; /** @@ -5461,6 +9875,19 @@ declare namespace ts { function getTsBuildInfoEmitOutputFilePath(options: CompilerOptions): string | undefined; function getOutputFileNames(commandLine: ParsedCommandLine, inputFileName: string, ignoreCase: boolean): readonly string[]; function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; + enum ProgramUpdateLevel { + /** Program is updated with same root file names and options */ + Update = 0, + /** Loads program after updating root file names from the disk */ + RootNamesAndUpdate = 1, + /** + * Loads program completely, including: + * - re-reading contents of config file from disk + * - calculating root file names for the program + * - Updating the program + */ + Full = 2, + } function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; @@ -5772,6 +10199,7 @@ declare namespace ts { * Returns the module resolution cache used by a provided `resolveModuleNames` implementation so that any non-name module resolution operations (eg, package.json lookup) can reuse it */ getModuleResolutionCache?(): ModuleResolutionCache | undefined; + jsDocParsingMode?: JSDocParsingMode; } interface WatchCompilerHost extends ProgramHost, WatchHost { /** Instead of using output d.ts file from project reference, use its source file */ @@ -5885,7 +10313,7 @@ declare namespace ts { enum InvalidatedProjectKind { Build = 0, /** @deprecated */ UpdateBundle = 1, - UpdateOutputFileStamps = 2 + UpdateOutputFileStamps = 2, } interface InvalidatedProjectBase { readonly kind: InvalidatedProjectKind; @@ -5930,90 +10358,6 @@ declare namespace ts { readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[] | undefined, depth?: number): string[]; } } - namespace server { - type ActionSet = "action::set"; - type ActionInvalidate = "action::invalidate"; - type ActionPackageInstalled = "action::packageInstalled"; - type EventTypesRegistry = "event::typesRegistry"; - type EventBeginInstallTypes = "event::beginInstallTypes"; - type EventEndInstallTypes = "event::endInstallTypes"; - type EventInitializationFailed = "event::initializationFailed"; - type ActionWatchTypingLocations = "action::watchTypingLocations"; - interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed | ActionWatchTypingLocations; - } - interface TypingInstallerRequestWithProjectName { - readonly projectName: string; - } - interface DiscoverTypings extends TypingInstallerRequestWithProjectName { - readonly fileNames: string[]; - readonly projectRootPath: Path; - readonly compilerOptions: CompilerOptions; - readonly typeAcquisition: TypeAcquisition; - readonly unresolvedImports: SortedReadonlyArray; - readonly cachePath?: string; - readonly kind: "discover"; - } - interface CloseProject extends TypingInstallerRequestWithProjectName { - readonly kind: "closeProject"; - } - interface TypesRegistryRequest { - readonly kind: "typesRegistry"; - } - interface InstallPackageRequest extends TypingInstallerRequestWithProjectName { - readonly kind: "installPackage"; - readonly fileName: Path; - readonly packageName: string; - readonly projectRootPath: Path; - } - interface PackageInstalledResponse extends ProjectResponse { - readonly kind: ActionPackageInstalled; - readonly success: boolean; - readonly message: string; - } - interface InitializationFailedResponse extends TypingInstallerResponse { - readonly kind: EventInitializationFailed; - readonly message: string; - readonly stack?: string; - } - interface ProjectResponse extends TypingInstallerResponse { - readonly projectName: string; - } - interface InvalidateCachedTypings extends ProjectResponse { - readonly kind: ActionInvalidate; - } - interface InstallTypes extends ProjectResponse { - readonly kind: EventBeginInstallTypes | EventEndInstallTypes; - readonly eventId: number; - readonly typingsInstallerVersion: string; - readonly packagesToInstall: readonly string[]; - } - interface BeginInstallTypes extends InstallTypes { - readonly kind: EventBeginInstallTypes; - } - interface EndInstallTypes extends InstallTypes { - readonly kind: EventEndInstallTypes; - readonly installSuccess: boolean; - } - interface InstallTypingHost extends JsTyping.TypingResolutionHost { - useCaseSensitiveFileNames: boolean; - writeFile(path: string, content: string): void; - createDirectory(path: string): void; - getCurrentDirectory?(): string; - } - interface SetTypings extends ProjectResponse { - readonly typeAcquisition: TypeAcquisition; - readonly compilerOptions: CompilerOptions; - readonly typings: string[]; - readonly unresolvedImports: SortedReadonlyArray; - readonly kind: ActionSet; - } - interface WatchTypingLocations extends ProjectResponse { - /** if files is undefined, retain same set of watchers */ - readonly files: readonly string[] | undefined; - readonly kind: ActionWatchTypingLocations; - } - } function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings; /** * Represents an immutable snapshot of a script at a specified time.Once acquired, the @@ -6061,7 +10405,7 @@ declare namespace ts { enum LanguageServiceMode { Semantic = 0, PartialSemantic = 1, - Syntactic = 2 + Syntactic = 2, } interface IncompleteCompletionsCache { get(): CompletionInfo | undefined; @@ -6106,13 +10450,14 @@ declare namespace ts { installPackage?(options: InstallPackageOptions): Promise; writeFile?(fileName: string, content: string): void; getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; + jsDocParsingMode?: JSDocParsingMode | undefined; } type WithMetadata = T & { metadata?: unknown; }; enum SemanticClassificationFormat { Original = "original", - TwentyTwenty = "2020" + TwentyTwenty = "2020", } interface LanguageService { /** This is used as a part of restarting the language service. */ @@ -6230,7 +10575,7 @@ declare namespace ts { findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; getFileReferences(fileName: string): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean, excludeLibFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; getNavigationTree(fileName: string): NavigationTree; prepareCallHierarchy(fileName: string, position: number): CallHierarchyItem | CallHierarchyItem[] | undefined; @@ -6302,7 +10647,7 @@ declare namespace ts { enum OrganizeImportsMode { All = "All", SortAndCombine = "SortAndCombine", - RemoveUnused = "RemoveUnused" + RemoveUnused = "RemoveUnused", } interface OrganizeImportsArgs extends CombinedCodeFixScope { /** @deprecated Use `mode` instead */ @@ -6316,7 +10661,7 @@ declare namespace ts { /** Completion was triggered by a trigger character. */ TriggerCharacter = 2, /** Completion was re-triggered as the current completion list is incomplete. */ - TriggerForIncompleteCompletions = 3 + TriggerForIncompleteCompletions = 3, } interface GetCompletionsAtPositionOptions extends UserPreferences { /** @@ -6445,7 +10790,7 @@ declare namespace ts { enum InlayHintKind { Type = "Type", Parameter = "Parameter", - Enum = "Enum" + Enum = "Enum", } interface InlayHint { /** This property will be the empty string when displayParts is set. */ @@ -6609,7 +10954,7 @@ declare namespace ts { none = "none", definition = "definition", reference = "reference", - writtenReference = "writtenReference" + writtenReference = "writtenReference", } interface HighlightSpan { fileName?: string; @@ -6632,12 +10977,12 @@ declare namespace ts { enum IndentStyle { None = 0, Block = 1, - Smart = 2 + Smart = 2, } enum SemicolonPreference { Ignore = "ignore", Insert = "insert", - Remove = "remove" + Remove = "remove", } /** @deprecated - consider using EditorSettings instead */ interface EditorOptions { @@ -6744,7 +11089,7 @@ declare namespace ts { regularExpressionLiteral = 21, link = 22, linkName = 23, - linkText = 24 + linkText = 24, } interface SymbolDisplayPart { text: string; @@ -6839,7 +11184,7 @@ declare namespace ts { IsContinuation = 4, ResolvedModuleSpecifiers = 8, ResolvedModuleSpecifiersBeyondLimit = 16, - MayIncludeMethodSnippets = 32 + MayIncludeMethodSnippets = 32, } interface CompletionInfo { /** For performance telemetry. */ @@ -6869,7 +11214,7 @@ declare namespace ts { * in the case of InternalSymbolName.ExportEquals and InternalSymbolName.Default. */ exportName: string; - exportMapKey?: string; + exportMapKey?: ExportMapInfoKey; moduleSpecifier?: string; /** The file name declaring the export's module symbol, if it was an external module */ fileName?: string; @@ -6879,7 +11224,7 @@ declare namespace ts { isPackageJsonImport?: true; } interface CompletionEntryDataUnresolved extends CompletionEntryDataAutoImport { - exportMapKey: string; + exportMapKey: ExportMapInfoKey; } interface CompletionEntryDataResolved extends CompletionEntryDataAutoImport { moduleSpecifier: string; @@ -6964,12 +11309,12 @@ declare namespace ts { /** Declarations and expressions */ Code = "code", /** Contiguous blocks of import declarations */ - Imports = "imports" + Imports = "imports", } enum OutputFileType { JavaScript = 0, SourceMap = 1, - Declaration = 2 + Declaration = 2, } enum EndOfLineState { None = 0, @@ -6978,7 +11323,7 @@ declare namespace ts { InDoubleQuoteStringLiteral = 3, InTemplateHeadOrNoSubstitutionTemplate = 4, InTemplateMiddleOrTail = 5, - InTemplateSubstitutionPosition = 6 + InTemplateSubstitutionPosition = 6, } enum TokenClass { Punctuation = 0, @@ -6990,7 +11335,7 @@ declare namespace ts { NumberLiteral = 6, BigIntLiteral = 7, StringLiteral = 8, - RegExpLiteral = 9 + RegExpLiteral = 9, } interface ClassificationResult { finalLexState: EndOfLineState; @@ -7107,7 +11452,7 @@ declare namespace ts { /** Jsdoc @link: in `{@link C link text}`, the entity name "C" */ linkName = "link name", /** Jsdoc @link: in `{@link C link text}`, the link text "link text" */ - linkText = "link text" + linkText = "link text", } enum ScriptElementKindModifier { none = "", @@ -7131,7 +11476,7 @@ declare namespace ts { mjsModifier = ".mjs", dctsModifier = ".d.cts", ctsModifier = ".cts", - cjsModifier = ".cjs" + cjsModifier = ".cjs", } enum ClassificationTypeNames { comment = "comment", @@ -7157,7 +11502,7 @@ declare namespace ts { jsxSelfClosingTagName = "jsx self closing tag name", jsxAttribute = "jsx attribute", jsxText = "jsx text", - jsxAttributeStringLiteralValue = "jsx attribute string literal value" + jsxAttributeStringLiteralValue = "jsx attribute string literal value", } enum ClassificationType { comment = 1, @@ -7184,7 +11529,7 @@ declare namespace ts { jsxAttribute = 22, jsxText = 23, jsxAttributeStringLiteralValue = 24, - bigintLiteral = 25 + bigintLiteral = 25, } interface InlayHintsContext { file: SourceFile; @@ -7194,13 +11539,16 @@ declare namespace ts { span: TextSpan; preferences: UserPreferences; } + type ExportMapInfoKey = string & { + __exportInfoKey: void; + }; /** The classifier is used for syntactic highlighting in editors via the TSServer */ function createClassifier(): Classifier; interface DocumentHighlights { fileName: string; highlightSpans: HighlightSpan[]; } - function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string, jsDocParsingMode?: JSDocParsingMode): DocumentRegistry; /** * The document registry represents a store of SourceFile objects that can be shared between * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) @@ -7298,6 +11646,7 @@ declare namespace ts { moduleName?: string; renamedDependencies?: MapLike; transformers?: CustomTransformers; + jsDocParsingMode?: JSDocParsingMode; } interface TranspileOutput { outputText: string; @@ -7327,4 +11676,4 @@ declare namespace ts { */ function transform(source: T | T[], transformers: TransformerFactory[], compilerOptions?: CompilerOptions): TransformationResult; } -export = ts; \ No newline at end of file +export = ts;