diff --git a/dist/index.js b/dist/index.js index 1505af77..8abdc971 100644 --- a/dist/index.js +++ b/dist/index.js @@ -287569,11 +287569,11 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "4.7"; + ts.versionMajorMinor = "4.8"; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = "4.7.4"; + ts.version = "4.8.4"; /* @internal */ var Comparison; (function (Comparison) { @@ -287779,8 +287779,10 @@ var ts; return true; } ts.every = every; - function find(array, predicate) { - for (var i = 0; i < array.length; i++) { + function find(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { var value = array[i]; if (predicate(value, i)) { return value; @@ -287789,8 +287791,10 @@ var ts; return undefined; } ts.find = find; - function findLast(array, predicate) { - for (var i = array.length - 1; i >= 0; i--) { + function findLast(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { var value = array[i]; if (predicate(value, i)) { return value; @@ -287801,7 +287805,9 @@ var ts; ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ function findIndex(array, predicate, startIndex) { - for (var i = startIndex || 0; i < array.length; i++) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -287810,7 +287816,9 @@ var ts; } ts.findIndex = findIndex; function findLastIndex(array, predicate, startIndex) { - for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { if (predicate(array[i], i)) { return i; } @@ -288588,7 +288596,7 @@ var ts; * Returns the first element of an array if non-empty, `undefined` otherwise. */ function firstOrUndefined(array) { - return array.length === 0 ? undefined : array[0]; + return array === undefined || array.length === 0 ? undefined : array[0]; } ts.firstOrUndefined = firstOrUndefined; function first(array) { @@ -288600,7 +288608,7 @@ var ts; * Returns the last element of an array if non-empty, `undefined` otherwise. */ function lastOrUndefined(array) { - return array.length === 0 ? undefined : array[array.length - 1]; + return array === undefined || array.length === 0 ? undefined : array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; function last(array) { @@ -288941,6 +288949,43 @@ var ts; return createMultiMap(); } ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; + function createQueue(items) { + var elements = (items === null || items === void 0 ? void 0 : items.slice()) || []; + var headIndex = 0; + function isEmpty() { + return headIndex === elements.length; + } + function enqueue() { + var items = []; + for (var _i = 0; _i < arguments.length; _i++) { + items[_i] = arguments[_i]; + } + elements.push.apply(elements, items); + } + function dequeue() { + if (isEmpty()) { + throw new Error("Queue is empty"); + } + var result = elements[headIndex]; + elements[headIndex] = undefined; // Don't keep referencing dequeued item + headIndex++; + // If more than half of the queue is empty, copy the remaining elements to the + // front and shrink the array (unless we'd be saving fewer than 100 slots) + if (headIndex > 100 && headIndex > (elements.length >> 1)) { + var newLength = elements.length - headIndex; + elements.copyWithin(/*target*/ 0, /*start*/ headIndex); + elements.length = newLength; + headIndex = 0; + } + return result; + } + return { + enqueue: enqueue, + dequeue: dequeue, + isEmpty: isEmpty, + }; + } + ts.createQueue = createQueue; /** * Creates a Set with custom equality and hash code functionality. This is useful when you * want to use something looser than object identity - e.g. "has the same span". @@ -289129,6 +289174,10 @@ var ts; /** Does nothing. */ function noop(_) { } ts.noop = noop; + ts.noopPush = { + push: noop, + length: 0 + }; /** Do nothing and return false */ function returnFalse() { return false; @@ -289484,7 +289533,7 @@ var ts; * and 1 insertion/deletion at 3 characters) */ function getSpellingSuggestion(name, candidates, getName) { - var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var maximumLengthDifference = Math.max(2, Math.floor(name.length * 0.34)); var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result is worse than this, don't bother. var bestCandidate; for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -289711,6 +289760,7 @@ var ts; startsWith(candidate, prefix) && endsWith(candidate, suffix); } + ts.isPatternMatch = isPatternMatch; function and(f, g) { return function (arg) { return f(arg) && g(arg); }; } @@ -289903,6 +289953,7 @@ var ts; var currentAssertionLevel = 0 /* AssertionLevel.None */; Debug.currentLogLevel = LogLevel.Warning; Debug.isDebugging = false; + Debug.enableDeprecationWarnings = true; function getTypeScriptVersion() { return typeScriptVersion !== null && typeScriptVersion !== void 0 ? typeScriptVersion : (typeScriptVersion = new ts.Version(ts.version)); } @@ -290121,7 +290172,7 @@ var ts; return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; } if (isFlags) { - var result = ""; + var result = []; var remainingFlags = value; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var _a = members_1[_i], enumValue = _a[0], enumName = _a[1]; @@ -290129,12 +290180,12 @@ var ts; break; } if (enumValue !== 0 && enumValue & value) { - result = "".concat(result).concat(result ? "|" : "").concat(enumName); + result.push(enumName); remainingFlags &= ~enumValue; } } if (remainingFlags === 0) { - return result; + return result.join("|"); } } else { @@ -290148,7 +290199,15 @@ var ts; return value.toString(); } Debug.formatEnum = formatEnum; + var enumMemberCache = new ts.Map(); function getEnumMembers(enumObject) { + // Assuming enum objects do not change at runtime, we can cache the enum members list + // to reuse later. This saves us from reconstructing this each and every time we call + // a formatting function (which can be expensive for large enums like SyntaxKind). + var existing = enumMemberCache.get(enumObject); + if (existing) { + return existing; + } var result = []; for (var name in enumObject) { var value = enumObject[name]; @@ -290156,7 +290215,9 @@ var ts; result.push([value, name]); } } - return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + var sorted = ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + enumMemberCache.set(enumObject, sorted); + return sorted; } function formatSyntaxKind(kind) { return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); @@ -290202,6 +290263,22 @@ var ts; return formatEnum(flags, ts.FlowFlags, /*isFlags*/ true); } Debug.formatFlowFlags = formatFlowFlags; + function formatRelationComparisonResult(result) { + return formatEnum(result, ts.RelationComparisonResult, /*isFlags*/ true); + } + Debug.formatRelationComparisonResult = formatRelationComparisonResult; + function formatCheckMode(mode) { + return formatEnum(mode, ts.CheckMode, /*isFlags*/ true); + } + Debug.formatCheckMode = formatCheckMode; + function formatSignatureCheckMode(mode) { + return formatEnum(mode, ts.SignatureCheckMode, /*isFlags*/ true); + } + Debug.formatSignatureCheckMode = formatSignatureCheckMode; + function formatTypeFacts(facts) { + return formatEnum(facts, ts.TypeFacts, /*isFlags*/ true); + } + Debug.formatTypeFacts = formatTypeFacts; var isDebugInfoEnabled = false; var extendedDebugModule; function extendedDebug() { @@ -290500,7 +290577,7 @@ var ts; function createWarningDeprecation(name, errorAfter, since, message) { var hasWrittenDeprecation = false; return function () { - if (!hasWrittenDeprecation) { + if (Debug.enableDeprecationWarnings && !hasWrittenDeprecation) { log.warn(formatDeprecationMessage(name, /*error*/ false, errorAfter, since, message)); hasWrittenDeprecation = true; } @@ -290519,6 +290596,7 @@ var ts; warn ? createWarningDeprecation(name, errorAfter, since, options.message) : ts.noop; } + Debug.createDeprecation = createDeprecation; function wrapFunction(deprecation, func) { return function () { deprecation(); @@ -290526,10 +290604,53 @@ var ts; }; } function deprecate(func, options) { - var deprecation = createDeprecation(getFunctionName(func), options); + var _a; + var deprecation = createDeprecation((_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : getFunctionName(func), options); return wrapFunction(deprecation, func); } Debug.deprecate = deprecate; + function formatVariance(varianceFlags) { + var variance = varianceFlags & 7 /* VarianceFlags.VarianceMask */; + var result = variance === 0 /* VarianceFlags.Invariant */ ? "in out" : + variance === 3 /* VarianceFlags.Bivariant */ ? "[bivariant]" : + variance === 2 /* VarianceFlags.Contravariant */ ? "in" : + variance === 1 /* VarianceFlags.Covariant */ ? "out" : + variance === 4 /* VarianceFlags.Independent */ ? "[independent]" : ""; + if (varianceFlags & 8 /* VarianceFlags.Unmeasurable */) { + result += " (unmeasurable)"; + } + else if (varianceFlags & 16 /* VarianceFlags.Unreliable */) { + result += " (unreliable)"; + } + return result; + } + Debug.formatVariance = formatVariance; + var DebugTypeMapper = /** @class */ (function () { + function DebugTypeMapper() { + } + DebugTypeMapper.prototype.__debugToString = function () { + var _a; + type(this); + switch (this.kind) { + case 3 /* TypeMapKind.Function */: return ((_a = this.debugInfo) === null || _a === void 0 ? void 0 : _a.call(this)) || "(function mapper)"; + case 0 /* TypeMapKind.Simple */: return "".concat(this.source.__debugTypeToString(), " -> ").concat(this.target.__debugTypeToString()); + case 1 /* TypeMapKind.Array */: return ts.zipWith(this.sources, this.targets || ts.map(this.sources, function () { return "any"; }), function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(typeof t === "string" ? t : t.__debugTypeToString()); }).join(", "); + case 2 /* TypeMapKind.Deferred */: return ts.zipWith(this.sources, this.targets, function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(t().__debugTypeToString()); }).join(", "); + case 5 /* TypeMapKind.Merged */: + case 4 /* TypeMapKind.Composite */: return "m1: ".concat(this.mapper1.__debugToString().split("\n").join("\n "), "\nm2: ").concat(this.mapper2.__debugToString().split("\n").join("\n ")); + default: return assertNever(this); + } + }; + return DebugTypeMapper; + }()); + Debug.DebugTypeMapper = DebugTypeMapper; + function attachDebugPrototypeIfDebug(mapper) { + if (Debug.isDebugging) { + return Object.setPrototypeOf(mapper, DebugTypeMapper.prototype); + } + return mapper; + } + Debug.attachDebugPrototypeIfDebug = attachDebugPrototypeIfDebug; })(Debug = ts.Debug || (ts.Debug = {})); })(ts || (ts = {})); /* @internal */ @@ -291271,9 +291392,9 @@ var ts; eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } tracingEnabled.push = push; - function pop() { + function pop(results) { ts.Debug.assert(eventStack.length > 0); - writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); + writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp(), results); eventStack.length--; } tracingEnabled.pop = pop; @@ -291287,14 +291408,15 @@ var ts; tracingEnabled.popAll = popAll; // sample every 10ms var sampleInterval = 1000 * 10; - function writeStackEvent(index, endTime) { + function writeStackEvent(index, endTime, results) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { + ts.Debug.assert(!results, "`results` are not supported for events with `separateBeginAndEnd`"); writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } // test if [time,endTime) straddles a sampling point else if (sampleInterval - (time % sampleInterval) <= endTime - time) { - writeEvent("X", phase, name, args, "\"dur\":".concat(endTime - time), time); + writeEvent("X", phase, name, __assign(__assign({}, args), { results: results }), "\"dur\":".concat(endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { @@ -291793,6 +291915,7 @@ var ts; SyntaxKind[SyntaxKind["JSDocFunctionType"] = 317] = "JSDocFunctionType"; SyntaxKind[SyntaxKind["JSDocVariadicType"] = 318] = "JSDocVariadicType"; SyntaxKind[SyntaxKind["JSDocNamepathType"] = 319] = "JSDocNamepathType"; + SyntaxKind[SyntaxKind["JSDoc"] = 320] = "JSDoc"; /** @deprecated Use SyntaxKind.JSDoc */ SyntaxKind[SyntaxKind["JSDocComment"] = 320] = "JSDocComment"; SyntaxKind[SyntaxKind["JSDocText"] = 321] = "JSDocText"; @@ -291867,7 +291990,6 @@ var ts; SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 347] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 126] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 160] = "LastContextualKeyword"; - SyntaxKind[SyntaxKind["JSDoc"] = 320] = "JSDoc"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -291941,6 +292063,7 @@ var ts; ModifierFlags[ModifierFlags["Override"] = 16384] = "Override"; ModifierFlags[ModifierFlags["In"] = 32768] = "In"; ModifierFlags[ModifierFlags["Out"] = 65536] = "Out"; + ModifierFlags[ModifierFlags["Decorator"] = 131072] = "Decorator"; ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. @@ -291948,7 +292071,8 @@ var ts; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 116958] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 125951] = "All"; + ModifierFlags[ModifierFlags["All"] = 257023] = "All"; + ModifierFlags[ModifierFlags["Modifier"] = 125951] = "Modifier"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -292133,6 +292257,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; + NodeBuilderFlags[NodeBuilderFlags["OmitThisParameter"] = 33554432] = "OmitThisParameter"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; NodeBuilderFlags[NodeBuilderFlags["AllowQualifiedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifiedNameInPlaceOfIdentifier"; @@ -292173,6 +292298,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; + TypeFormatFlags[TypeFormatFlags["OmitThisParameter"] = 33554432] = "OmitThisParameter"; // Error Handling TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; // TypeFormatFlags exclusive @@ -292184,7 +292310,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 848330091] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -292573,6 +292699,11 @@ var ts; // Flags that require TypeFlags.Union /* @internal */ ObjectFlags[ObjectFlags["ContainsIntersections"] = 16777216] = "ContainsIntersections"; + /* @internal */ + ObjectFlags[ObjectFlags["IsUnknownLikeUnionComputed"] = 33554432] = "IsUnknownLikeUnionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsUnknownLikeUnion"] = 67108864] = "IsUnknownLikeUnion"; + /* @internal */ // Flags that require TypeFlags.Intersection /* @internal */ ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 16777216] = "IsNeverIntersectionComputed"; @@ -292658,9 +292789,10 @@ var ts; (function (TypeMapKind) { TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple"; TypeMapKind[TypeMapKind["Array"] = 1] = "Array"; - TypeMapKind[TypeMapKind["Function"] = 2] = "Function"; - TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite"; - TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged"; + TypeMapKind[TypeMapKind["Deferred"] = 2] = "Deferred"; + TypeMapKind[TypeMapKind["Function"] = 3] = "Function"; + TypeMapKind[TypeMapKind["Composite"] = 4] = "Composite"; + TypeMapKind[TypeMapKind["Merged"] = 5] = "Merged"; })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {})); var InferencePriority; (function (InferencePriority) { @@ -293039,25 +293171,24 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 4096] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 16384] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 32768] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 65536] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 131072] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 262144] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 524288] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsAwait"] = 1048576] = "ContainsAwait"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 2097152] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 4194304] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["ContainsClassFields"] = 8388608] = "ContainsClassFields"; - TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 16777216] = "ContainsPossibleTopLevelAwait"; - TransformFlags[TransformFlags["ContainsLexicalSuper"] = 33554432] = "ContainsLexicalSuper"; - TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 67108864] = "ContainsUpdateExpressionForIdentifier"; - // Please leave this as 1 << 29. - // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. - // It is a good reminder of how much room we have left - TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 8192] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 32768] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 65536] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 131072] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 262144] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 524288] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 1048576] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsAwait"] = 2097152] = "ContainsAwait"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 4194304] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 8388608] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["ContainsClassFields"] = 16777216] = "ContainsClassFields"; + TransformFlags[TransformFlags["ContainsDecorators"] = 33554432] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 67108864] = "ContainsPossibleTopLevelAwait"; + TransformFlags[TransformFlags["ContainsLexicalSuper"] = 134217728] = "ContainsLexicalSuper"; + TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 268435456] = "ContainsUpdateExpressionForIdentifier"; + TransformFlags[TransformFlags["ContainsPrivateIdentifierInExpression"] = 536870912] = "ContainsPrivateIdentifierInExpression"; + TransformFlags[TransformFlags["HasComputedFlags"] = -2147483648] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; @@ -293076,27 +293207,27 @@ var ts; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 557748224] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 591310848] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 591306752] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 574529536] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["PropertyExcludes"] = 570433536] = "PropertyExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 536940544] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 589443072] = "ModuleExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = -2147483648] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = -2147483648] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = -2147483648] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = -2072174592] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = -1937940480] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = -1937948672] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = -2005057536] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = -2013249536] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = -2147344384] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = -1941676032] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536973312] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536887296] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537165824] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 536903680] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 536887296] = "BindingPatternExcludes"; - TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 33562624] = "ContainsLexicalThisOrSuper"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = -2147278848] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = -2147450880] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = -2146893824] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = -2147483648] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = -2147418112] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = -2147450880] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 134234112] = "ContainsLexicalThisOrSuper"; // Propagating flags // - Bitmasks for flags that should propagate from a child - TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 33562624] = "PropertyNamePropagatingFlags"; + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 134234112] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); @@ -293269,7 +293400,7 @@ var ts; ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList"; // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["Modifiers"] = 2359808] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; @@ -293664,7 +293795,7 @@ var ts; }; } function createDirectoryWatcher(dirName, dirPath, fallbackOptions) { - var watcher = fsWatch(dirName, 1 /* FileSystemEntryKind.Directory */, function (_eventName, relativeFileName) { + var watcher = fsWatch(dirName, 1 /* FileSystemEntryKind.Directory */, function (_eventName, relativeFileName, modifiedTime) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" if (!ts.isString(relativeFileName)) return; @@ -293674,7 +293805,7 @@ var ts; if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; - fileCallback(fileName, FileWatcherEventKind.Changed); + fileCallback(fileName, FileWatcherEventKind.Changed, modifiedTime); } } }, @@ -293728,7 +293859,7 @@ var ts; } else { cache.set(path, { - watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options), + watcher: watchFile(fileName, function (fileName, eventKind, modifiedTime) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind, modifiedTime); }); }, pollingInterval, options), refCount: 1 }); } @@ -293756,7 +293887,8 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); + // Pass modified times so tsc --build can use it + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime), modifiedTime); return true; } return false; @@ -293791,7 +293923,7 @@ var ts; */ /*@internal*/ function createDirectoryWatcherSupportingRecursive(_a) { - var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, directoryExists = _a.directoryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; + var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, fileSystemEntryExists = _a.fileSystemEntryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; var cache = new ts.Map(); var callbackCache = ts.createMultiMap(); var cacheToUpdateChildWatches = new ts.Map(); @@ -293891,7 +294023,7 @@ var ts; function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) { // Iterate through existing children and update the watches if needed var parentWatcher = cache.get(dirPath); - if (parentWatcher && directoryExists(dirName)) { + if (parentWatcher && fileSystemEntryExists(dirName, 1 /* FileSystemEntryKind.Directory */)) { // Schedule the update and postpone invoke for callbacks scheduleUpdateChildWatches(dirName, dirPath, fileName, options); return; @@ -293964,7 +294096,7 @@ var ts; if (!parentWatcher) return false; var newChildWatches; - var hasChanges = ts.enumerateInsertsAndDeletes(directoryExists(parentDir) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { + var hasChanges = ts.enumerateInsertsAndDeletes(fileSystemEntryExists(parentDir, 1 /* FileSystemEntryKind.Directory */) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); // Filter our the symbolic link directories since those arent included in recursive watch // which is same behaviour when recursive: true is passed to fs.watch @@ -294007,17 +294139,19 @@ var ts; })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {})); /*@internal*/ function createFileWatcherCallback(callback) { - return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + return function (_fileName, eventKind, modifiedTime) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", "", modifiedTime); }; } ts.createFileWatcherCallback = createFileWatcherCallback; - function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) { - return function (eventName) { + function createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime) { + return function (eventName, _relativeFileName, modifiedTime) { if (eventName === "rename") { - callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + // Check time stamps rather than file system entry checks + modifiedTime || (modifiedTime = getModifiedTime(fileName) || ts.missingFileModifiedTime); + callback(fileName, modifiedTime !== ts.missingFileModifiedTime ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted, modifiedTime); } else { // Change - callback(fileName, FileWatcherEventKind.Changed); + callback(fileName, FileWatcherEventKind.Changed, modifiedTime); } }; } @@ -294041,11 +294175,12 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind; + var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; var dynamicPollingWatchFile; var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; var hostRecursiveDirectoryWatcher; + var hitSystemWatcherLimit = false; return { watchFile: watchFile, watchDirectory: watchDirectory @@ -294063,7 +294198,7 @@ var ts; case ts.WatchFileKind.FixedChunkSizePolling: return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined, /*options*/ undefined); case ts.WatchFileKind.UseFsEvents: - return fsWatch(fileName, 0 /* FileSystemEntryKind.File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), + return fsWatch(fileName, 0 /* FileSystemEntryKind.File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime), /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options)); case ts.WatchFileKind.UseFsEventsOnParentDirectory: if (!nonPollingWatchFile) { @@ -294124,7 +294259,7 @@ var ts; hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - directoryExists: directoryExists, + fileSystemEntryExists: fileSystemEntryExists, getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories, watchDirectory: nonRecursiveWatchDirectory, realpath: realpath, @@ -294175,6 +294310,124 @@ var ts; }; } } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { + var lastDirectoryPartWithDirectorySeparator; + var lastDirectoryPart; + if (inodeWatching) { + lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substring(fileOrDirectory.lastIndexOf(ts.directorySeparator)); + lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); + } + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); + return { + close: function () { + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) + if (watcher) { + watcher.close(); + watcher = undefined; + } + } + }; + function updateWatcher(createWatcher) { + // If watcher is not closed, update it + if (watcher) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { + if (hitSystemWatcherLimit) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + try { + var presentWatcher = fsWatchWorker(fileOrDirectory, recursive, inodeWatching ? + callbackChangingToMissingFileSystemEntry : + callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { + callback("rename", ""); + updateWatcher(watchMissingFileSystemEntry); + }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + function callbackChangingToMissingFileSystemEntry(event, relativeName) { + // In some scenarios, file save operation fires event with fileName.ext~ instead of fileName.ext + // To ensure we see the file going missing and coming back up (file delete and then recreated) + // and watches being updated correctly we are calling back with fileName.ext as well as fileName.ext~ + // The worst is we have fired event that was not needed but we wont miss any changes + // especially in cases where file goes missing and watches wrong inode + var originalRelativeName; + if (relativeName && ts.endsWith(relativeName, "~")) { + originalRelativeName = relativeName; + relativeName = relativeName.slice(0, relativeName.length - 1); + } + // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations + // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path + if (event === "rename" && + (!relativeName || + relativeName === lastDirectoryPart || + ts.endsWith(relativeName, lastDirectoryPartWithDirectorySeparator))) { + var modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime; + if (originalRelativeName) + callback(event, originalRelativeName, modifiedTime); + callback(event, relativeName, modifiedTime); + if (inodeWatching) { + // If this was rename event, inode has changed means we need to update watcher + updateWatcher(modifiedTime === ts.missingFileModifiedTime ? watchMissingFileSystemEntry : watchPresentFileSystemEntry); + } + else if (modifiedTime === ts.missingFileModifiedTime) { + updateWatcher(watchMissingFileSystemEntry); + } + } + else { + if (originalRelativeName) + callback(event, originalRelativeName); + callback(event, relativeName); + } + } + /** + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + */ + function watchPresentFileSystemEntryWithFsWatchFile() { + return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return watchFile(fileOrDirectory, function (_fileName, eventKind, modifiedTime) { + if (eventKind === FileWatcherEventKind.Created) { + modifiedTime || (modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime); + if (modifiedTime !== ts.missingFileModifiedTime) { + callback("rename", "", modifiedTime); + // Call the callback for current file or directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + updateWatcher(watchPresentFileSystemEntry); + } + } + }, fallbackPollingInterval, fallbackOptions); + } + } } ts.createSystemWatchFunctions = createSystemWatchFunctions; /** @@ -294212,7 +294465,6 @@ var ts; // not actually work. var byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { - var _a; var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/; var _fs = __nccwpck_require__(57147); var _path = __nccwpck_require__(71017); @@ -294222,41 +294474,41 @@ var ts; try { _crypto = __nccwpck_require__(6113); } - catch (_b) { + catch (_a) { _crypto = undefined; } var activeSession; var profilePath = "./profile.cpuprofile"; - var hitSystemWatcherLimit = false; var Buffer = (__nccwpck_require__(14300).Buffer); var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); - var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync; + var fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); - var _c = createSystemWatchFunctions({ + var _b = createSystemWatchFunctions({ pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames), getModifiedTime: getModifiedTime, setTimeout: setTimeout, clearTimeout: clearTimeout, - fsWatch: fsWatch, + fsWatchWorker: fsWatchWorker, useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - fileExists: fileExists, + fileSystemEntryExists: fileSystemEntryExists, // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch, - directoryExists: directoryExists, getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, realpath: realpath, tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, - }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory; + inodeWatching: isLinuxOrMacOs, + sysLog: sysLog, + }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -294505,110 +294757,14 @@ var ts; // File changed eventKind = FileWatcherEventKind.Changed; } - callback(fileName, eventKind); + callback(fileName, eventKind, curr.mtime); } } - function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { - var options; - var lastDirectoryPartWithDirectorySeparator; - var lastDirectoryPart; - if (isLinuxOrMacOs) { - lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator)); - lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); - } - /** Watcher for the file system entry depending on whether it is missing or present */ - var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? - watchMissingFileSystemEntry() : - watchPresentFileSystemEntry(); - return { - close: function () { - // Close the watcher (either existing file system entry watcher or missing file system entry watcher) - watcher.close(); - watcher = undefined; - } - }; - /** - * Invoke the callback with rename and update the watcher if not closed - * @param createWatcher - */ - function invokeCallbackAndUpdateWatcher(createWatcher) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); - // Call the callback for current directory - callback("rename", ""); - // If watcher is not closed, update it - if (watcher) { - watcher.close(); - watcher = createWatcher(); - } - } - /** - * Watch the file or directory that is currently present - * and when the watched file or directory is deleted, switch to missing file system entry watcher - */ - function watchPresentFileSystemEntry() { - // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows - // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) - if (options === undefined) { - if (fsSupportsRecursiveFsWatch) { - options = { persistent: true, recursive: !!recursive }; - } - else { - options = { persistent: true }; - } - } - if (hitSystemWatcherLimit) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - try { - var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ? - callbackChangingToMissingFileSystemEntry : - callback); - // Watch the missing file or directory or error - presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); - return presentWatcher; - } - catch (e) { - // Catch the exception and use polling instead - // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point - // so instead of throwing error, use fs.watchFile - hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - } - function callbackChangingToMissingFileSystemEntry(event, relativeName) { - // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations - // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path - return event === "rename" && - (!relativeName || - relativeName === lastDirectoryPart || - (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && - !fileSystemEntryExists(fileOrDirectory, entryKind) ? - invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : - callback(event, relativeName); - } - /** - * Watch the file or directory using fs.watchFile since fs.watch threw exception - * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point - */ - function watchPresentFileSystemEntryWithFsWatchFile() { - return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); - } - /** - * Watch the file or directory that is missing - * and switch to existing file or directory when the missing filesystem entry is created - */ - function watchMissingFileSystemEntry() { - return watchFile(fileOrDirectory, function (_fileName, eventKind) { - if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { - // Call the callback for current file or directory - // For now it could be callback for the inner directory creation, - // but just return current directory, better than current no-op - invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); - } - }, fallbackPollingInterval, fallbackOptions); - } + function fsWatchWorker(fileOrDirectory, recursive, callback) { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + return _fs.watch(fileOrDirectory, fsSupportsRecursiveFsWatch ? + { persistent: true, recursive: !!recursive } : { persistent: true }, callback); } function readFileWorker(fileName, _encoding) { var buffer; @@ -294745,9 +294901,12 @@ var ts; function getDirectories(path) { return getAccessibleFileSystemEntries(path).directories.slice(); } + function fsRealPathHandlingLongPath(path) { + return path.length < 260 ? _fs.realpathSync.native(path) : _fs.realpathSync(path); + } function realpath(path) { try { - return realpathSync(path); + return fsRealpath(path); } catch (_a) { return path; @@ -294755,12 +294914,19 @@ var ts; } function getModifiedTime(path) { var _a; + // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve + // the CPU time performance. + var originalStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; try { return (_a = statSync(path)) === null || _a === void 0 ? void 0 : _a.mtime; } catch (e) { return undefined; } + finally { + Error.stackTraceLimit = originalStackTraceLimit; + } } function setModifiedTime(path, time) { try { @@ -295615,6 +295781,7 @@ var ts; String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + or_JSX_element_expected: diag(1145, ts.DiagnosticCategory.Error, "or_JSX_element_expected_1145", "'{' or JSX element expected."), Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), @@ -295668,6 +295835,7 @@ var ts; Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), _0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module: diag(1208, ts.DiagnosticCategory.Error, "_0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_imp_1208", "'{0}' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module."), + Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0: diag(1209, ts.DiagnosticCategory.Error, "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209", "Invalid optional chain from new expression. Did you mean to call '{0}()'?"), Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode: diag(1210, ts.DiagnosticCategory.Error, "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210", "Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of '{0}'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode."), A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), @@ -295760,6 +295928,7 @@ var ts; infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Class_constructor_may_not_be_an_accessor: diag(1341, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_an_accessor_1341", "Class constructor may not be an accessor."), Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node16_or_nodenext: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), @@ -295778,6 +295947,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Class_constructor_may_not_be_a_generator: diag(1360, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_a_generator_1360", "Class constructor may not be a generator."), _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."), _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), @@ -295867,13 +296037,25 @@ var ts; resolution_mode_can_only_be_set_for_type_only_imports: diag(1454, ts.DiagnosticCategory.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, ts.DiagnosticCategory.Error, "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455", "`resolution-mode` is the only valid key for type import assertions."), Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require: diag(1456, ts.DiagnosticCategory.Error, "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456", "Type import assertions should have exactly one key - `resolution-mode` - with value `import` or `require`."), + Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk: diag(1457, ts.DiagnosticCategory.Message, "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457", "Matched by default include pattern '**/*'"), + File_is_ECMAScript_module_because_0_has_field_type_with_value_module: diag(1458, ts.DiagnosticCategory.Message, "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458", "File is ECMAScript module because '{0}' has field \"type\" with value \"module\""), + File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module: diag(1459, ts.DiagnosticCategory.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, ts.DiagnosticCategory.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, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_package_json_was_not_found_1461", "File is CommonJS module because 'package.json' was not found"), The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, ts.DiagnosticCategory.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_synchronously_Use_dynamic_import_instead: diag(1471, ts.DiagnosticCategory.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 synchronously. Use dynamic import instead."), + 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, ts.DiagnosticCategory.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, ts.DiagnosticCategory.Error, "catch_or_finally_expected_1472", "'catch' or 'finally' expected."), An_import_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1473, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473", "An import declaration can only be used at the top level of a module."), An_export_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1474, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474", "An export declaration can only be used at the top level of a module."), Control_what_method_is_used_to_detect_module_format_JS_files: diag(1475, ts.DiagnosticCategory.Message, "Control_what_method_is_used_to_detect_module_format_JS_files_1475", "Control what method is used to detect module-format JS files."), auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules: diag(1476, ts.DiagnosticCategory.Message, "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476", "\"auto\": Treat files with imports, exports, import.meta, jsx (with jsx: react-jsx), or esm format (with module: node16+) as modules."), + An_instantiation_expression_cannot_be_followed_by_a_property_access: diag(1477, ts.DiagnosticCategory.Error, "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477", "An instantiation expression cannot be followed by a property access."), + Identifier_or_string_literal_expected: diag(1478, ts.DiagnosticCategory.Error, "Identifier_or_string_literal_expected_1478", "Identifier or string literal expected."), + 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: diag(1479, ts.DiagnosticCategory.Error, "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479", "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."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module: diag(1480, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480", "To convert this file to an ECMAScript module, change its file extension to '{0}' or create a local package.json file with `{ \"type\": \"module\" }`."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1: diag(1481, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481", "To convert this file to an ECMAScript module, change its file extension to '{0}', or add the field `\"type\": \"module\"` to '{1}'."), + To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0: diag(1482, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482", "To convert this file to an ECMAScript module, add the field `\"type\": \"module\"` to '{0}'."), + To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module: diag(1483, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483", "To convert this file to an ECMAScript module, create a local package.json file with `{ \"type\": \"module\" }`."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -295882,8 +296064,11 @@ var ts; Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2205, ts.DiagnosticCategory.Error, "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement: diag(2206, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206", "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement."), The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement: diag(2207, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207", "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement."), + This_type_parameter_might_need_an_extends_0_constraint: diag(2208, ts.DiagnosticCategory.Error, "This_type_parameter_might_need_an_extends_0_constraint_2208", "This type parameter might need an `extends {0}` constraint."), The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2209, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209", "The project root is ambiguous, but is required to resolve export map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2210, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210", "The project root is ambiguous, but is required to resolve import map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), + Add_extends_constraint: diag(2211, ts.DiagnosticCategory.Message, "Add_extends_constraint_2211", "Add `extends` constraint."), + Add_extends_constraint_to_all_type_parameters: diag(2212, ts.DiagnosticCategory.Message, "Add_extends_constraint_to_all_type_parameters_2212", "Add `extends` constraint to all type parameters"), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -296084,6 +296269,7 @@ var ts; Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + A_tuple_type_cannot_be_indexed_with_a_negative_value: diag(2514, ts.DiagnosticCategory.Error, "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514", "A tuple type cannot be indexed with a negative value."), Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), @@ -296153,7 +296339,7 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), - This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), + This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag_2594", "This module is declared with 'export =', and can only be used with a default import when using the '{0}' flag."), _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), _0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import: diag(2597, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597", "'{0}' can only be imported by using a 'require' call or by using a default import."), @@ -296366,7 +296552,12 @@ var ts; Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls: diag(2836, ts.DiagnosticCategory.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."), Import_assertion_values_must_be_string_literal_expressions: diag(2837, ts.DiagnosticCategory.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, ts.DiagnosticCategory.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, ts.DiagnosticCategory.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, ts.DiagnosticCategory.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, ts.DiagnosticCategory.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'."), + _0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation: diag(2842, ts.DiagnosticCategory.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, ts.DiagnosticCategory.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, ts.DiagnosticCategory.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."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -296777,8 +296968,8 @@ var ts; Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), Referenced_project_0_may_not_disable_emit: diag(6310, ts.DiagnosticCategory.Error, "Referenced_project_0_may_not_disable_emit_6310", "Referenced project '{0}' may not disable emit."), - Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), - Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_1_is_older_than_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350", "Project '{0}' is out of date because output '{1}' is older than input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than output '{2}'"), Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), @@ -296822,6 +297013,8 @@ var ts; Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: diag(6396, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: diag(6397, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}' with Package ID '{4}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6398, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was not resolved."), + Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted: diag(6399, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399", "Project '{0}' is out of date because buildinfo file '{1}' indicates that some of the changes were not emitted"), + Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files: diag(6400, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400", "Project '{0}' is up to date but needs to update timestamps of output files that are older than input files"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -297062,6 +297255,8 @@ var ts; Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags: diag(8033, ts.DiagnosticCategory.Error, "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033", "A JSDoc '@typedef' comment may not contain multiple '@type' tags."), The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."), + You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder: diag(8035, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035", "You cannot rename elements that are defined in a 'node_modules' folder."), + You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -297332,6 +297527,9 @@ var ts; For_await_loops_cannot_be_used_inside_a_class_static_block: diag(18038, ts.DiagnosticCategory.Error, "For_await_loops_cannot_be_used_inside_a_class_static_block_18038", "'For await' loops cannot be used inside a class static block."), Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block: diag(18039, ts.DiagnosticCategory.Error, "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039", "Invalid use of '{0}'. It cannot be used inside a class static block."), A_return_statement_cannot_be_used_inside_a_class_static_block: diag(18041, ts.DiagnosticCategory.Error, "A_return_statement_cannot_be_used_inside_a_class_static_block_18041", "A 'return' statement cannot be used inside a class static block."), + _0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation: diag(18042, ts.DiagnosticCategory.Error, "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042", "'{0}' is a type and cannot be imported in JavaScript files. Use '{1}' in a JSDoc type annotation."), + Types_cannot_appear_in_export_declarations_in_JavaScript_files: diag(18043, ts.DiagnosticCategory.Error, "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043", "Types cannot appear in export declarations in JavaScript files."), + _0_is_automatically_exported_here: diag(18044, ts.DiagnosticCategory.Message, "_0_is_automatically_exported_here_18044", "'{0}' is automatically exported here."), }; })(ts || (ts = {})); var ts; @@ -300219,6 +300417,18 @@ var ts; } } ts.getAssignedName = getAssignedName; + function getDecorators(node) { + if (ts.hasDecorators(node)) { + return ts.filter(node.modifiers, ts.isDecorator); + } + } + ts.getDecorators = getDecorators; + function getModifiers(node) { + if (ts.hasSyntacticModifier(node, 125951 /* ModifierFlags.Modifier */)) { + return ts.filter(node.modifiers, isModifier); + } + } + ts.getModifiers = getModifiers; function getJSDocParameterTagsWorker(param, noCache) { if (param.name) { if (ts.isIdentifier(param.name)) { @@ -300489,6 +300699,12 @@ var ts; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + * + * This does *not* return type parameters from a jsdoc reference to a generic type, eg + * + * type Id = (x: T) => T + * /** @type {Id} / + * function id(x) { return x } */ function getEffectiveTypeParameterDeclarations(node) { if (ts.isJSDocSignature(node)) { @@ -300501,6 +300717,9 @@ var ts; if (node.typeParameters) { return node.typeParameters; } + if (ts.canHaveIllegalTypeParameters(node) && node.typeParameters) { + return node.typeParameters; + } if (ts.isInJSFile(node)) { var decls = ts.getJSDocTypeParameterDeclarations(node); if (decls.length) { @@ -300677,6 +300896,19 @@ var ts; return isLiteralKind(node.kind); } ts.isLiteralExpression = isLiteralExpression; + /** @internal */ + function isLiteralExpressionOfObject(node) { + switch (node.kind) { + case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 13 /* SyntaxKind.RegularExpressionLiteral */: + case 213 /* SyntaxKind.FunctionExpression */: + case 226 /* SyntaxKind.ClassExpression */: + return true; + } + return false; + } + ts.isLiteralExpressionOfObject = isLiteralExpressionOfObject; // Pseudo-literals /* @internal */ function isTemplateLiteralKind(kind) { @@ -300886,6 +301118,10 @@ var ts; } ts.isMethodOrAccessor = isMethodOrAccessor; // Type members + function isModifierLike(node) { + return isModifier(node) || ts.isDecorator(node); + } + ts.isModifierLike = isModifierLike; function isTypeElement(node) { var kind = node.kind; return kind === 175 /* SyntaxKind.ConstructSignature */ @@ -301495,7 +301731,6 @@ var ts; case 254 /* SyntaxKind.VariableDeclaration */: case 164 /* SyntaxKind.Parameter */: case 203 /* SyntaxKind.BindingElement */: - case 166 /* SyntaxKind.PropertySignature */: case 167 /* SyntaxKind.PropertyDeclaration */: case 296 /* SyntaxKind.PropertyAssignment */: case 299 /* SyntaxKind.EnumMember */: @@ -301547,6 +301782,16 @@ var ts; return node.kind === 324 /* SyntaxKind.JSDocLink */ || node.kind === 325 /* SyntaxKind.JSDocLinkCode */ || node.kind === 326 /* SyntaxKind.JSDocLinkPlain */; } ts.isJSDocLinkLike = isJSDocLinkLike; + function hasRestParameter(s) { + var last = ts.lastOrUndefined(s.parameters); + return !!last && isRestParameter(last); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 318 /* SyntaxKind.JSDocVariadicType */; + } + ts.isRestParameter = isRestParameter; // #endregion })(ts || (ts = {})); /* @internal */ @@ -302027,10 +302272,11 @@ var ts; } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { - if (nodeIsMissing(node) || !node.decorators) { + var lastDecorator = !nodeIsMissing(node) && ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + if (!lastDecorator) { return getTokenPosOfNode(node, sourceFile); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, lastDecorator.end); } ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { @@ -303416,7 +303662,7 @@ var ts; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node, parent, grandparent) { - return node.decorators !== undefined + return hasDecorators(node) && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 } ts.nodeIsDecorated = nodeIsDecorated; @@ -304316,16 +304562,6 @@ var ts; return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; - function hasRestParameter(s) { - var last = ts.lastOrUndefined(s.parameters); - return !!last && isRestParameter(last); - } - ts.hasRestParameter = hasRestParameter; - function isRestParameter(node) { - var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 318 /* SyntaxKind.JSDocVariadicType */; - } - ts.isRestParameter = isRestParameter; function hasTypeArguments(node) { return !!node.typeArguments; } @@ -304447,6 +304683,12 @@ var ts; return [child, node]; } ts.walkUpParenthesizedTypesAndGetParentAndChild = walkUpParenthesizedTypesAndGetParentAndChild; + function skipTypeParentheses(node) { + while (ts.isParenthesizedTypeNode(node)) + node = node.type; + return node; + } + ts.skipTypeParentheses = skipTypeParentheses; function skipParentheses(node, excludeJSDocTypeAssertions) { var flags = excludeJSDocTypeAssertions ? 1 /* OuterExpressionKinds.Parentheses */ | 16 /* OuterExpressionKinds.ExcludeJSDocTypeAssertion */ : @@ -306193,6 +306435,10 @@ var ts; return hasEffectiveModifier(node, 64 /* ModifierFlags.Readonly */); } ts.hasEffectiveReadonlyModifier = hasEffectiveReadonlyModifier; + function hasDecorators(node) { + return hasSyntacticModifier(node, 131072 /* ModifierFlags.Decorator */); + } + ts.hasDecorators = hasDecorators; function getSelectedEffectiveModifierFlags(node, flags) { return getEffectiveModifierFlags(node) & flags; } @@ -306270,7 +306516,7 @@ var ts; * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc. */ function getSyntacticModifierFlagsNoCache(node) { - var flags = modifiersToFlags(node.modifiers); + var flags = ts.canHaveModifiers(node) ? modifiersToFlags(node.modifiers) : 0 /* ModifierFlags.None */; if (node.flags & 4 /* NodeFlags.NestedNamespace */ || (node.kind === 79 /* SyntaxKind.Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* ModifierFlags.Export */; } @@ -306304,6 +306550,7 @@ var ts; case 159 /* SyntaxKind.OverrideKeyword */: return 16384 /* ModifierFlags.Override */; case 101 /* SyntaxKind.InKeyword */: return 32768 /* ModifierFlags.In */; case 144 /* SyntaxKind.OutKeyword */: return 65536 /* ModifierFlags.Out */; + case 165 /* SyntaxKind.Decorator */: return 131072 /* ModifierFlags.Decorator */; } return 0 /* ModifierFlags.None */; } @@ -306681,8 +306928,9 @@ var ts; * Moves the start position of a range past any decorators. */ function moveRangePastDecorators(node) { - return node.decorators && node.decorators.length > 0 - ? moveRangePos(node, node.decorators.end) + var lastDecorator = ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + return lastDecorator && !positionIsSynthesized(lastDecorator.end) + ? moveRangePos(node, lastDecorator.end) : node; } ts.moveRangePastDecorators = moveRangePastDecorators; @@ -306690,8 +306938,9 @@ var ts; * Moves the start position of a range past any decorators or modifiers. */ function moveRangePastModifiers(node) { - return node.modifiers && node.modifiers.length > 0 - ? moveRangePos(node, node.modifiers.end) + var lastModifier = ts.canHaveModifiers(node) ? ts.lastOrUndefined(node.modifiers) : undefined; + return lastModifier && !positionIsSynthesized(lastModifier.end) + ? moveRangePos(node, lastModifier.end) : moveRangePastDecorators(node); } ts.moveRangePastModifiers = moveRangePastModifiers; @@ -306813,7 +307062,8 @@ var ts; function getDeclarationModifierFlagsFromSymbol(s, isWrite) { if (isWrite === void 0) { isWrite = false; } if (s.valueDeclaration) { - var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 173 /* SyntaxKind.SetAccessor */; })) || s.valueDeclaration; + var declaration = (isWrite && s.declarations && ts.find(s.declarations, ts.isSetAccessorDeclaration)) + || (s.flags & 32768 /* SymbolFlags.GetAccessor */ && ts.find(s.declarations, ts.isGetAccessorDeclaration)) || s.valueDeclaration; var flags = ts.getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 /* SymbolFlags.Class */ ? flags : flags & ~28 /* ModifierFlags.AccessibilityModifier */; } @@ -307488,7 +307738,7 @@ var ts; // Excludes declaration files - they still require an explicit `export {}` or the like // for back compat purposes. The only non-declaration files _not_ forced to be a module are `.js` files // that aren't esm-mode (meaning not in a `type: module` scope). - return (file.impliedNodeFormat === ts.ModuleKind.ESNext || (ts.fileExtensionIsOneOf(file.fileName, [".cjs" /* Extension.Cjs */, ".cts" /* Extension.Cts */]))) && !file.isDeclarationFile ? true : undefined; + return (file.impliedNodeFormat === ts.ModuleKind.ESNext || (ts.fileExtensionIsOneOf(file.fileName, [".cjs" /* Extension.Cjs */, ".cts" /* Extension.Cts */, ".mjs" /* Extension.Mjs */, ".mts" /* Extension.Mts */]))) && !file.isDeclarationFile ? true : undefined; } function getSetExternalModuleIndicator(options) { // TODO: Should this callback be cached? @@ -307511,10 +307761,7 @@ var ts; if (options.jsx === 4 /* JsxEmit.ReactJSX */ || options.jsx === 5 /* JsxEmit.ReactJSXDev */) { checks.push(isFileModuleFromUsingJSXTag); } - var moduleKind = getEmitModuleKind(options); - if (moduleKind === ts.ModuleKind.Node16 || moduleKind === ts.ModuleKind.NodeNext) { - checks.push(isFileForcedToBeModuleByFormat); - } + checks.push(isFileForcedToBeModuleByFormat); var combined_1 = ts.or.apply(void 0, checks); var callback = function (file) { return void (file.externalModuleIndicator = combined_1(file)); }; return callback; @@ -307640,6 +307887,10 @@ var ts; return optionsHaveChanges(oldOptions, newOptions, ts.affectsEmitOptionDeclarations); } ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit; + function compilerOptionsAffectDeclarationPath(newOptions, oldOptions) { + return optionsHaveChanges(oldOptions, newOptions, ts.affectsDeclarationPathOptionDeclarations); + } + ts.compilerOptionsAffectDeclarationPath = compilerOptionsAffectDeclarationPath; function getCompilerOptionValue(options, option) { return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; } @@ -308580,8 +308831,12 @@ var ts; return node.parent.templateSpans; case 233 /* SyntaxKind.TemplateSpan */: return node.parent.templateSpans; - case 165 /* SyntaxKind.Decorator */: - return node.parent.decorators; + case 165 /* SyntaxKind.Decorator */: { + var parent_2 = node.parent; + return ts.canHaveDecorators(parent_2) ? parent_2.modifiers : + ts.canHaveIllegalDecorators(parent_2) ? parent_2.illegalDecorators : + undefined; + } case 291 /* SyntaxKind.HeritageClause */: return node.parent.heritageClauses; } @@ -309095,7 +309350,7 @@ var ts; * Wraps an expression in parentheses if it is needed in order to use the expression for * property or element access. */ - function parenthesizeLeftSideOfAccess(expression) { + function parenthesizeLeftSideOfAccess(expression, optionalChain) { // isLeftHandSideExpression is almost the correct criterion for when it is not necessary // to parenthesize the expression before a dot. The known exception is: // @@ -309104,7 +309359,8 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 209 /* SyntaxKind.NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 209 /* SyntaxKind.NewExpression */ || emittedExpression.arguments) + && (optionalChain || !ts.isOptionalChain(emittedExpression))) { // TODO(rbuckton): Verify whether this assertion holds. return expression; } @@ -310051,13 +310307,8 @@ var ts; function createBaseNode(kind) { return baseFactory.createBaseNode(kind); } - function createBaseDeclaration(kind, decorators, modifiers) { + function createBaseDeclaration(kind) { var node = createBaseNode(kind); - node.decorators = asNodeArray(decorators); - node.modifiers = asNodeArray(modifiers); - node.transformFlags |= - propagateChildrenFlags(node.decorators) | - propagateChildrenFlags(node.modifiers); // NOTE: The following properties are commonly set by the binder and are added here to // ensure declarations have a stable shape. node.symbol = undefined; // initialized by binder @@ -310066,10 +310317,15 @@ var ts; node.nextContainer = undefined; // initialized by binder return node; } - function createBaseNamedDeclaration(kind, decorators, modifiers, name) { - var node = createBaseDeclaration(kind, decorators, modifiers); + function createBaseNamedDeclaration(kind, modifiers, name) { + var node = createBaseDeclaration(kind); name = asName(name); node.name = name; + if (ts.canHaveModifiers(node)) { + node.modifiers = asNodeArray(modifiers); + node.transformFlags |= propagateChildrenFlags(node.modifiers); + // node.decorators = filter(node.modifiers, isDecorator); + } // The PropertyName of a member is allowed to be `await`. // We don't need to exclude `await` for type signatures since types // don't propagate child flags. @@ -310092,16 +310348,16 @@ var ts; } return node; } - function createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.typeParameters = asNodeArray(typeParameters); node.transformFlags |= propagateChildrenFlags(node.typeParameters); if (typeParameters) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; return node; } - function createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.parameters = createNodeArray(parameters); node.type = type; node.transformFlags |= @@ -310109,50 +310365,45 @@ var ts; propagateChildFlags(node.type); if (type) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used for quick info + node.typeArguments = undefined; return node; } - function updateBaseSignatureDeclaration(updated, original) { - // copy children used only for error reporting - if (original.typeArguments) + function finishUpdateBaseSignatureDeclaration(updated, original) { + if (updated !== original) { + // copy children used for quick info updated.typeArguments = original.typeArguments; + } return update(updated, original); } - function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) { - var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type); + function createBaseFunctionLikeDeclaration(kind, modifiers, name, typeParameters, parameters, type, body) { + var node = createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type); node.body = body; - node.transformFlags |= propagateChildFlags(node.body) & ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + node.transformFlags |= propagateChildFlags(node.body) & ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; if (!body) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateBaseFunctionLikeDeclaration(updated, original) { - // copy children used only for error reporting - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - if (original.typeArguments) - updated.typeArguments = original.typeArguments; - return updateBaseSignatureDeclaration(updated, original); - } - function createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.heritageClauses = asNodeArray(heritageClauses); node.transformFlags |= propagateChildrenFlags(node.heritageClauses); return node; } - function createBaseClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses); + function createBaseClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members); return node; } - function createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseBindingLikeDeclaration(kind, modifiers, name, initializer) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.initializer = initializer; node.transformFlags |= propagateChildFlags(node.initializer); return node; } - function createBaseVariableLikeDeclaration(kind, decorators, modifiers, name, type, initializer) { - var node = createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer); + function createBaseVariableLikeDeclaration(kind, modifiers, name, type, initializer) { + var node = createBaseBindingLikeDeclaration(kind, modifiers, name, initializer); node.type = type; node.transformFlags |= propagateChildFlags(type); if (type) @@ -310248,7 +310499,7 @@ var ts; node.typeArguments = createNodeArray(typeArguments); } if (node.originalKeywordKind === 132 /* SyntaxKind.AwaitKeyword */) { - node.transformFlags |= 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + node.transformFlags |= 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } return node; } @@ -310300,7 +310551,7 @@ var ts; ts.Debug.fail("First character of private identifier must be #: " + text); var node = baseFactory.createBasePrivateIdentifierNode(80 /* SyntaxKind.PrivateIdentifier */); node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 8388608 /* TransformFlags.ContainsClassFields */; + node.transformFlags |= 16777216 /* TransformFlags.ContainsClassFields */; return node; } // @@ -310347,14 +310598,14 @@ var ts; transformFlags = 1 /* TransformFlags.ContainsTypeScript */; break; case 106 /* SyntaxKind.SuperKeyword */: - transformFlags = 1024 /* TransformFlags.ContainsES2015 */ | 33554432 /* TransformFlags.ContainsLexicalSuper */; + transformFlags = 1024 /* TransformFlags.ContainsES2015 */ | 134217728 /* TransformFlags.ContainsLexicalSuper */; break; case 124 /* SyntaxKind.StaticKeyword */: transformFlags = 1024 /* TransformFlags.ContainsES2015 */; break; case 108 /* SyntaxKind.ThisKeyword */: // 'this' indicates a lexical 'this' - transformFlags = 8192 /* TransformFlags.ContainsLexicalThis */; + transformFlags = 16384 /* TransformFlags.ContainsLexicalThis */; break; } if (transformFlags) { @@ -310452,7 +310703,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* TransformFlags.ContainsES2015 */ | - 65536 /* TransformFlags.ContainsComputedPropertyName */; + 131072 /* TransformFlags.ContainsComputedPropertyName */; return node; } // @api @@ -310461,41 +310712,19 @@ var ts; ? update(createComputedPropertyName(expression), node) : node; } - function createTypeParameterDeclaration(modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } - var node = createBaseNamedDeclaration(163 /* SyntaxKind.TypeParameter */, - /*decorators*/ undefined, modifiers, name); + // + // Signature elements + // + // @api + function createTypeParameterDeclaration(modifiers, name, constraint, defaultType) { + var node = createBaseNamedDeclaration(163 /* SyntaxKind.TypeParameter */, modifiers, name); node.constraint = constraint; node.default = defaultType; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateTypeParameterDeclaration(node, modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } + // @api + function updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType) { return node.modifiers !== modifiers || node.name !== name || node.constraint !== constraint @@ -310504,8 +310733,8 @@ var ts; : node; } // @api - function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(164 /* SyntaxKind.Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + function createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(164 /* SyntaxKind.Parameter */, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -310518,32 +310747,32 @@ var ts; if (questionToken) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; if (ts.modifiersToFlags(node.modifiers) & 16476 /* ModifierFlags.ParameterPropertyModifier */) - node.transformFlags |= 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + node.transformFlags |= 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; } return node; } // @api - function updateParameterDeclaration(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? update(createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + ? update(createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } // @api function createDecorator(expression) { var node = createBaseNode(165 /* SyntaxKind.Decorator */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */ | - 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */ | + 33554432 /* TransformFlags.ContainsDecorators */; return node; } // @api @@ -310557,11 +310786,12 @@ var ts; // // @api function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(166 /* SyntaxKind.PropertySignature */, - /*decorators*/ undefined, modifiers, name); + var node = createBaseNamedDeclaration(166 /* SyntaxKind.PropertySignature */, modifiers, name); node.type = type; node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.initializer = undefined; return node; } // @api @@ -310570,20 +310800,27 @@ var ts; || node.name !== name || node.questionToken !== questionToken || node.type !== type - ? update(createPropertySignature(modifiers, name, questionToken, type), node) + ? finishUpdatePropertySignature(createPropertySignature(modifiers, name, questionToken, type), node) : node; } + function finishUpdatePropertySignature(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.initializer = original.initializer; + } + return update(updated, original); + } // @api - function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(167 /* SyntaxKind.PropertyDeclaration */, decorators, modifiers, name, type, initializer); + function createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(167 /* SyntaxKind.PropertyDeclaration */, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= propagateChildFlags(node.questionToken) | propagateChildFlags(node.exclamationToken) | - 8388608 /* TransformFlags.ContainsClassFields */; + 16777216 /* TransformFlags.ContainsClassFields */; if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { - node.transformFlags |= 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + node.transformFlags |= 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */; } if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; @@ -310591,21 +310828,19 @@ var ts; return node; } // @api - function updatePropertyDeclaration(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.modifiers !== modifiers || node.name !== name || node.questionToken !== (questionOrExclamationToken !== undefined && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.exclamationToken !== (questionOrExclamationToken !== undefined && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.type !== type || node.initializer !== initializer - ? update(createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) + ? update(createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer), node) : node; } // @api function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(168 /* SyntaxKind.MethodSignature */, - /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(168 /* SyntaxKind.MethodSignature */, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -310618,12 +310853,12 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) : node; } // @api - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(169 /* SyntaxKind.MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + function createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(169 /* SyntaxKind.MethodDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= @@ -310644,12 +310879,13 @@ var ts; else if (asteriskToken) { node.transformFlags |= 2048 /* TransformFlags.ContainsGenerator */; } + // The following properties are used only to report grammar errors + node.exclamationToken = undefined; return node; } // @api - function updateMethodDeclaration(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.questionToken !== questionToken @@ -310657,80 +310893,123 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? finishUpdateMethodDeclaration(createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } + function finishUpdateMethodDeclaration(updated, original) { + if (updated !== original) { + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api - function createClassStaticBlockDeclaration(decorators, modifiers, body) { - var node = createBaseGenericNamedDeclaration(170 /* SyntaxKind.ClassStaticBlockDeclaration */, decorators, modifiers, + function createClassStaticBlockDeclaration(body) { + var node = createBaseGenericNamedDeclaration(170 /* SyntaxKind.ClassStaticBlockDeclaration */, + /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined); node.body = body; - node.transformFlags = propagateChildFlags(body) | 8388608 /* TransformFlags.ContainsClassFields */; + node.transformFlags = propagateChildFlags(body) | 16777216 /* TransformFlags.ContainsClassFields */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } // @api - function updateClassStaticBlockDeclaration(node, decorators, modifiers, body) { - return node.decorators !== decorators - || node.modifier !== modifiers - || node.body !== body - ? update(createClassStaticBlockDeclaration(decorators, modifiers, body), node) + function updateClassStaticBlockDeclaration(node, body) { + return node.body !== body + ? finishUpdateClassStaticBlockDeclaration(createClassStaticBlockDeclaration(body), node) : node; } + function finishUpdateClassStaticBlockDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } // @api - function createConstructorDeclaration(decorators, modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.Constructor */, decorators, modifiers, + function createConstructorDeclaration(modifiers, parameters, body) { + var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.Constructor */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.typeParameters = undefined; + node.type = undefined; return node; } // @api - function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateConstructorDeclaration(node, modifiers, parameters, body) { + return node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createConstructorDeclaration(decorators, modifiers, parameters, body), node) + ? finishUpdateConstructorDeclaration(createConstructorDeclaration(modifiers, parameters, body), node) : node; } + function finishUpdateConstructorDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) { - return createBaseFunctionLikeDeclaration(172 /* SyntaxKind.GetAccessor */, decorators, modifiers, name, + function createGetAccessorDeclaration(modifiers, name, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(172 /* SyntaxKind.GetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, type, body); + // The following properties are used only to report grammar errors + node.typeParameters = undefined; + return node; } // @api - function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body), node) + ? finishUpdateGetAccessorDeclaration(createGetAccessorDeclaration(modifiers, name, parameters, type, body), node) : node; } + function finishUpdateGetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) { - return createBaseFunctionLikeDeclaration(173 /* SyntaxKind.SetAccessor */, decorators, modifiers, name, + function createSetAccessorDeclaration(modifiers, name, parameters, body) { + var node = createBaseFunctionLikeDeclaration(173 /* SyntaxKind.SetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); + // The following properties are used only to report grammar errors + node.typeParameters = undefined; + node.type = undefined; + return node; } // @api - function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateSetAccessorDeclaration(node, modifiers, name, parameters, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createSetAccessorDeclaration(decorators, modifiers, name, parameters, body), node) + ? finishUpdateSetAccessorDeclaration(createSetAccessorDeclaration(modifiers, name, parameters, body), node) : node; } + function finishUpdateSetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api function createCallSignature(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(174 /* SyntaxKind.CallSignature */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -310741,13 +311020,12 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) : node; } // @api function createConstructSignature(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(175 /* SyntaxKind.ConstructSignature */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -310758,24 +311036,23 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) : node; } // @api - function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(176 /* SyntaxKind.IndexSignature */, decorators, modifiers, + function createIndexSignature(modifiers, parameters, type) { + var node = createBaseSignatureDeclaration(176 /* SyntaxKind.IndexSignature */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } // @api - function updateIndexSignature(node, decorators, modifiers, parameters, type) { + function updateIndexSignature(node, modifiers, parameters, type) { return node.parameters !== parameters || node.type !== type - || node.decorators !== decorators || node.modifiers !== modifiers - ? updateBaseSignatureDeclaration(createIndexSignature(decorators, modifiers, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createIndexSignature(modifiers, parameters, type), node) : node; } // @api @@ -310835,10 +311112,11 @@ var ts; // @api function createFunctionTypeNode(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(179 /* SyntaxKind.FunctionType */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.modifiers = undefined; return node; } // @api @@ -310846,9 +311124,15 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createFunctionTypeNode(typeParameters, parameters, type), node) + ? finishUpdateFunctionTypeNode(createFunctionTypeNode(typeParameters, parameters, type), node) : node; } + function finishUpdateFunctionTypeNode(updated, original) { + if (updated !== original) { + updated.modifiers = original.modifiers; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api function createConstructorTypeNode() { var args = []; @@ -310860,8 +311144,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(180 /* SyntaxKind.ConstructorType */, - /*decorators*/ undefined, modifiers, + var node = createBaseSignatureDeclaration(180 /* SyntaxKind.ConstructorType */, modifiers, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -310885,7 +311168,7 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) : node; } /** @deprecated */ @@ -311065,33 +311348,27 @@ var ts; ? update(createTemplateLiteralType(head, templateSpans), node) : node; } - function createImportTypeNode(argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */ ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : false; + // @api + function createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = false; } var node = createBaseNode(200 /* SyntaxKind.ImportType */); node.argument = argument; - node.assertions = assertion; + node.assertions = assertions; node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.isTypeOf = isTypeOf; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateImportTypeNode(node, argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */ ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : node.isTypeOf; + // @api + function updateImportTypeNode(node, argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = node.isTypeOf; } return node.argument !== argument - || node.assertions !== assertion + || node.assertions !== assertions || node.qualifier !== qualifier || node.typeArguments !== typeArguments || node.isTypeOf !== isTypeOf - ? update(createImportTypeNode(argument, assertion, qualifier, typeArguments, isTypeOf), node) + ? update(createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf), node) : node; } // @api @@ -311190,11 +311467,11 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* TransformFlags.ContainsES2015 */ | - 262144 /* TransformFlags.ContainsBindingPattern */; - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */) { + 524288 /* TransformFlags.ContainsBindingPattern */; + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */ | - 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + 65536 /* TransformFlags.ContainsObjectRestOrSpread */; } return node; } @@ -311211,7 +311488,7 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* TransformFlags.ContainsES2015 */ | - 262144 /* TransformFlags.ContainsBindingPattern */; + 524288 /* TransformFlags.ContainsBindingPattern */; return node; } // @api @@ -311223,7 +311500,6 @@ var ts; // @api function createBindingElement(dotDotDotToken, propertyName, name, initializer) { var node = createBaseBindingLikeDeclaration(203 /* SyntaxKind.BindingElement */, - /*decorators*/ undefined, /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; @@ -311236,7 +311512,7 @@ var ts; propagateChildFlags(node.propertyName); } if (dotDotDotToken) - node.transformFlags |= 16384 /* TransformFlags.ContainsRestOrSpread */; + node.transformFlags |= 32768 /* TransformFlags.ContainsRestOrSpread */; return node; } // @api @@ -311292,13 +311568,13 @@ var ts; // @api function createPropertyAccessExpression(expression, name) { var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.name = asName(name); node.transformFlags = propagateChildFlags(node.expression) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); if (ts.isSuperKeyword(expression)) { // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators @@ -311322,7 +311598,7 @@ var ts; function createPropertyAccessChain(expression, questionDotToken, name) { var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= @@ -311331,7 +311607,7 @@ var ts; propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); return node; } // @api @@ -311348,7 +311624,7 @@ var ts; // @api function createElementAccessExpression(expression, index) { var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.argumentExpression = asExpression(index); node.transformFlags |= propagateChildFlags(node.expression) | @@ -311376,7 +311652,7 @@ var ts; function createElementAccessChain(expression, questionDotToken, index) { var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.argumentExpression = asExpression(index); node.transformFlags |= @@ -311400,7 +311676,7 @@ var ts; // @api function createCallExpression(expression, typeArguments, argumentsArray) { var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); node.transformFlags |= @@ -311411,10 +311687,10 @@ var ts; node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } if (ts.isImportKeyword(node.expression)) { - node.transformFlags |= 4194304 /* TransformFlags.ContainsDynamicImport */; + node.transformFlags |= 8388608 /* TransformFlags.ContainsDynamicImport */; } else if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -311433,7 +311709,7 @@ var ts; function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -311447,7 +311723,7 @@ var ts; node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -311488,7 +311764,7 @@ var ts; // @api function createTaggedTemplateExpression(tag, typeArguments, template) { var node = createBaseExpression(210 /* SyntaxKind.TaggedTemplateExpression */); - node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag); + node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.template = template; node.transformFlags |= @@ -311545,8 +311821,7 @@ var ts; } // @api function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(213 /* SyntaxKind.FunctionExpression */, - /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(213 /* SyntaxKind.FunctionExpression */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); if (node.typeParameters) { @@ -311574,20 +311849,19 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateBaseSignatureDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } // @api function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(214 /* SyntaxKind.ArrowFunction */, - /*decorators*/ undefined, modifiers, + var node = createBaseFunctionLikeDeclaration(214 /* SyntaxKind.ArrowFunction */, modifiers, /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* SyntaxKind.EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | 1024 /* TransformFlags.ContainsES2015 */; if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { - node.transformFlags |= 256 /* TransformFlags.ContainsES2017 */ | 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 256 /* TransformFlags.ContainsES2017 */ | 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -311599,7 +311873,7 @@ var ts; || node.type !== type || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body - ? updateBaseFunctionLikeDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + ? finishUpdateBaseSignatureDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } // @api @@ -311649,7 +311923,7 @@ var ts; propagateChildFlags(node.expression) | 256 /* TransformFlags.ContainsES2017 */ | 128 /* TransformFlags.ContainsES2018 */ | - 1048576 /* TransformFlags.ContainsAwait */; + 2097152 /* TransformFlags.ContainsAwait */; return node; } // @api @@ -311670,7 +311944,7 @@ var ts; ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; + node.transformFlags |= 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; } return node; } @@ -311691,7 +311965,7 @@ var ts; if (ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; + node.transformFlags |= 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; } return node; } @@ -311737,11 +312011,14 @@ var ts; else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { node.transformFlags |= 16 /* TransformFlags.ContainsES2021 */; } + if (operatorKind === 101 /* SyntaxKind.InKeyword */ && ts.isPrivateIdentifier(node.left)) { + node.transformFlags |= 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */; + } return node; } function propagateAssignmentPatternFlags(node) { - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) - return 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) + return 65536 /* TransformFlags.ContainsObjectRestOrSpread */; if (node.transformFlags & 128 /* TransformFlags.ContainsES2018 */) { // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c' // will not be correctly interpreted by the ES2018 transformer @@ -311749,8 +312026,8 @@ var ts; var element = _a[_i]; var target = ts.getTargetOfBindingOrAssignmentElement(element); if (target && ts.isAssignmentPattern(target)) { - if (target.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { - return 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + if (target.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { + return 65536 /* TransformFlags.ContainsObjectRestOrSpread */; } if (target.transformFlags & 128 /* TransformFlags.ContainsES2018 */) { var flags_1 = propagateAssignmentPatternFlags(target); @@ -311876,7 +312153,7 @@ var ts; propagateChildFlags(node.asteriskToken) | 1024 /* TransformFlags.ContainsES2015 */ | 128 /* TransformFlags.ContainsES2018 */ | - 524288 /* TransformFlags.ContainsYield */; + 1048576 /* TransformFlags.ContainsYield */; return node; } // @api @@ -311893,7 +312170,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* TransformFlags.ContainsES2015 */ | - 16384 /* TransformFlags.ContainsRestOrSpread */; + 32768 /* TransformFlags.ContainsRestOrSpread */; return node; } // @api @@ -311903,20 +312180,19 @@ var ts; : node; } // @api - function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(226 /* SyntaxKind.ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(226 /* SyntaxKind.ClassExpression */, modifiers, name, typeParameters, heritageClauses, members); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; return node; } // @api - function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) : node; } // @api @@ -311926,7 +312202,7 @@ var ts; // @api function createExpressionWithTypeArguments(expression, typeArguments) { var node = createBaseNode(228 /* SyntaxKind.ExpressionWithTypeArguments */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | @@ -311962,7 +312238,7 @@ var ts; // @api function createNonNullExpression(expression) { var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */; @@ -311981,7 +312257,7 @@ var ts; function createNonNullChain(expression) { var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */; @@ -312064,10 +312340,12 @@ var ts; } // @api function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(237 /* SyntaxKind.VariableStatement */, /*decorators*/ undefined, modifiers); + var node = createBaseDeclaration(237 /* SyntaxKind.VariableStatement */); + node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= - propagateChildFlags(node.declarationList); + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.declarationList); if (ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; } @@ -312226,7 +312504,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -312241,7 +312519,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -312258,7 +312536,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 128 /* TransformFlags.ContainsES2018 */ | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -312358,7 +312636,6 @@ var ts; // @api function createVariableDeclaration(name, exclamationToken, type, initializer) { var node = createBaseVariableLikeDeclaration(254 /* SyntaxKind.VariableDeclaration */, - /*decorators*/ undefined, /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; node.transformFlags |= propagateChildFlags(node.exclamationToken); @@ -312384,11 +312661,11 @@ var ts; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; if (flags & 3 /* NodeFlags.BlockScoped */) { node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */ | - 131072 /* TransformFlags.ContainsBlockScopedBinding */; + 262144 /* TransformFlags.ContainsBlockScopedBinding */; } return node; } @@ -312399,8 +312676,8 @@ var ts; : node; } // @api - function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(256 /* SyntaxKind.FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + function createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(256 /* SyntaxKind.FunctionDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -312408,7 +312685,7 @@ var ts; else { node.transformFlags |= propagateChildFlags(node.asteriskToken) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { if (node.asteriskToken) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */; @@ -312421,104 +312698,133 @@ var ts; node.transformFlags |= 2048 /* TransformFlags.ContainsGenerator */; } } + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateFunctionDeclaration(createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } + function finishUpdateFunctionDeclaration(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.illegalDecorators = original.illegalDecorators; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(257 /* SyntaxKind.ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); + function createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(257 /* SyntaxKind.ClassDeclaration */, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; } else { node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; - if (node.transformFlags & 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */) { + if (node.transformFlags & 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } } return node; } // @api - function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } // @api - function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(258 /* SyntaxKind.InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); + function createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(258 /* SyntaxKind.InterfaceDeclaration */, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? finishUpdateInterfaceDeclaration(createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } + function finishUpdateInterfaceDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(259 /* SyntaxKind.TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); + function createTypeAliasDeclaration(modifiers, name, typeParameters, type) { + var node = createBaseGenericNamedDeclaration(259 /* SyntaxKind.TypeAliasDeclaration */, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.type !== type - ? update(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + ? finishUpdateTypeAliasDeclaration(createTypeAliasDeclaration(modifiers, name, typeParameters, type), node) : node; } + function finishUpdateTypeAliasDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createBaseNamedDeclaration(260 /* SyntaxKind.EnumDeclaration */, decorators, modifiers, name); + function createEnumDeclaration(modifiers, name, members) { + var node = createBaseNamedDeclaration(260 /* SyntaxKind.EnumDeclaration */, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | 1 /* TransformFlags.ContainsTypeScript */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateEnumDeclaration(node, decorators, modifiers, name, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateEnumDeclaration(node, modifiers, name, members) { + return node.modifiers !== modifiers || node.name !== name || node.members !== members - ? update(createEnumDeclaration(decorators, modifiers, name, members), node) + ? finishUpdateEnumDeclaration(createEnumDeclaration(modifiers, name, members), node) : node; } + function finishUpdateEnumDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createModuleDeclaration(decorators, modifiers, name, body, flags) { + function createModuleDeclaration(modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* NodeFlags.None */; } - var node = createBaseDeclaration(261 /* SyntaxKind.ModuleDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(261 /* SyntaxKind.ModuleDeclaration */); + node.modifiers = asNodeArray(modifiers); node.flags |= flags & (16 /* NodeFlags.Namespace */ | 4 /* NodeFlags.NestedNamespace */ | 1024 /* NodeFlags.GlobalAugmentation */); node.name = name; node.body = body; @@ -312527,22 +312833,30 @@ var ts; } else { node.transformFlags |= - propagateChildFlags(node.name) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.name) | propagateChildFlags(node.body) | 1 /* TransformFlags.ContainsTypeScript */; } - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateModuleDeclaration(node, decorators, modifiers, name, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateModuleDeclaration(node, modifiers, name, body) { + return node.modifiers !== modifiers || node.name !== name || node.body !== body - ? update(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node) + ? finishUpdateModuleDeclaration(createModuleDeclaration(modifiers, name, body, node.flags), node) : node; } + function finishUpdateModuleDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createModuleBlock(statements) { var node = createBaseNode(262 /* SyntaxKind.ModuleBlock */); @@ -312572,60 +312886,84 @@ var ts; // @api function createNamespaceExportDeclaration(name) { var node = createBaseNamedDeclaration(264 /* SyntaxKind.NamespaceExportDeclaration */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } // @api function updateNamespaceExportDeclaration(node, name) { return node.name !== name - ? update(createNamespaceExportDeclaration(name), node) + ? finishUpdateNamespaceExportDeclaration(createNamespaceExportDeclaration(name), node) : node; } + function finishUpdateNamespaceExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } // @api - function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(265 /* SyntaxKind.ImportEqualsDeclaration */, decorators, modifiers, name); + function createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference) { + var node = createBaseNamedDeclaration(265 /* SyntaxKind.ImportEqualsDeclaration */, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); if (!ts.isExternalModuleReference(node.moduleReference)) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateImportEqualsDeclaration(node, decorators, modifiers, isTypeOnly, name, moduleReference) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.name !== name || node.moduleReference !== moduleReference - ? update(createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference), node) + ? finishUpdateImportEqualsDeclaration(createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node) : node; } + function finishUpdateImportEqualsDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(266 /* SyntaxKind.ImportDeclaration */, decorators, modifiers); + function createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(266 /* SyntaxKind.ImportDeclaration */); + node.modifiers = asNodeArray(modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause), node) + ? finishUpdateImportDeclaration(createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateImportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createImportClause(isTypeOnly, name, namedBindings) { var node = createBaseNode(267 /* SyntaxKind.ImportClause */); @@ -312638,7 +312976,7 @@ var ts; if (isTypeOnly) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -312698,7 +313036,7 @@ var ts; var node = createBaseNode(268 /* SyntaxKind.NamespaceImport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -312714,7 +313052,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.name) | 4 /* TransformFlags.ContainsESNext */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -312728,7 +313066,7 @@ var ts; var node = createBaseNode(269 /* SyntaxKind.NamedImports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -312746,7 +313084,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -312758,54 +313096,71 @@ var ts; : node; } // @api - function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(271 /* SyntaxKind.ExportAssignment */, decorators, modifiers); + function createExportAssignment(modifiers, isExportEquals, expression) { + var node = createBaseDeclaration(271 /* SyntaxKind.ExportAssignment */); + node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(63 /* SyntaxKind.EqualsToken */, /*leftSide*/ undefined, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); - node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.expression); + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateExportAssignment(node, decorators, modifiers, expression) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportAssignment(node, modifiers, expression) { + return node.modifiers !== modifiers || node.expression !== expression - ? update(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node) + ? finishUpdateExportAssignment(createExportAssignment(modifiers, node.isExportEquals, expression), node) : node; } + function finishUpdateExportAssignment(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(272 /* SyntaxKind.ExportDeclaration */, decorators, modifiers); + function createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(272 /* SyntaxKind.ExportDeclaration */); + node.modifiers = asNodeArray(modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= - propagateChildFlags(node.exportClause) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) + ? finishUpdateExportDeclaration(createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createNamedExports(elements) { var node = createBaseNode(273 /* SyntaxKind.NamedExports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -312823,7 +313178,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -312836,9 +313191,7 @@ var ts; } // @api function createMissingDeclaration() { - var node = createBaseDeclaration(276 /* SyntaxKind.MissingDeclaration */, - /*decorators*/ undefined, - /*modifiers*/ undefined); + var node = createBaseDeclaration(276 /* SyntaxKind.MissingDeclaration */); return node; } // @@ -312849,7 +313202,7 @@ var ts; var node = createBaseNode(277 /* SyntaxKind.ExternalModuleReference */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -312905,7 +313258,6 @@ var ts; // @api function createJSDocFunctionType(parameters, type) { var node = createBaseSignatureDeclaration(317 /* SyntaxKind.JSDocFunctionType */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); @@ -313557,26 +313909,18 @@ var ts; // @api function createPropertyAssignment(name, initializer) { var node = createBaseNamedDeclaration(296 /* SyntaxKind.PropertyAssignment */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer); + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdatePropertyAssignment(updated, original) { - // copy children used only for error reporting - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } // @api function updatePropertyAssignment(node, name, initializer) { return node.name !== name @@ -313584,31 +313928,32 @@ var ts; ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node) : node; } + function finishUpdatePropertyAssignment(updated, original) { + // copy children used only for error reporting + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { var node = createBaseNamedDeclaration(297 /* SyntaxKind.ShorthandPropertyAssignment */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | 1024 /* TransformFlags.ContainsES2015 */; + // The following properties are used only to report grammar errors + node.equalsToken = undefined; + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdateShorthandPropertyAssignment(updated, original) { - // copy children used only for error reporting - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.equalsToken) - updated.equalsToken = original.equalsToken; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } // @api function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { return node.name !== name @@ -313616,6 +313961,17 @@ var ts; ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) : node; } + function finishUpdateShorthandPropertyAssignment(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.equalsToken = original.equalsToken; + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api function createSpreadAssignment(expression) { var node = createBaseNode(298 /* SyntaxKind.SpreadAssignment */); @@ -313623,7 +313979,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 128 /* TransformFlags.ContainsES2018 */ | - 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + 65536 /* TransformFlags.ContainsObjectRestOrSpread */; return node; } // @api @@ -313943,13 +314299,11 @@ var ts; } function createExportDefault(expression) { return createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); } function createExternalModuleExport(exportName) { return createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, createNamedExports([ createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, exportName) @@ -314107,7 +314461,7 @@ var ts; } else if (ts.getEmitFlags(callee) & 4096 /* EmitFlags.HelperName */) { thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee, /*optionalChain*/ false); } else if (ts.isPropertyAccessExpression(callee)) { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { @@ -314136,7 +314490,7 @@ var ts; else { // for `a()` target is `a` and thisArg is `void 0` thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); } return { target: target, thisArg: thisArg }; } @@ -314145,9 +314499,7 @@ var ts; // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560) createParenthesizedExpression(createObjectLiteralExpression([ createSetAccessorDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, "value", [createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, paramName, /*questionToken*/ undefined, @@ -314449,30 +314801,32 @@ var ts; else { modifierArray = modifiers; } - return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : - ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : - ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : - ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : - ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : - ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifierArray, node.parameters, node.body) : - ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.type, node.body) : - ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.body) : - ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifierArray, node.parameters, node.type) : - ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : - ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : - ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.type) : - ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifierArray, node.name, node.members) : - ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifierArray, node.name, node.body) : - ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : - ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : - ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifierArray, node.expression) : - ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : - ts.Debug.assertNever(node); + return ts.isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : + ts.isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : + ts.isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : + ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : + ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : + ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : + ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : + ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : + ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : + ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : + ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : + ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : + ts.isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : + ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : + ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : + ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : + ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : + ts.isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : + ts.isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : + ts.isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : + ts.Debug.assertNever(node); } function asNodeArray(array) { return array ? createNodeArray(array) : undefined; @@ -314580,10 +314934,10 @@ var ts; } function propagateIdentifierNameFlags(node) { // An IdentifierName is allowed to be `await` - return propagateChildFlags(node) & ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + return propagateChildFlags(node) & ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } function propagatePropertyNameFlagsOfChild(node, transformFlags) { - return transformFlags | (node.transformFlags & 33562624 /* TransformFlags.PropertyNamePropagatingFlags */); + return transformFlags | (node.transformFlags & 134234112 /* TransformFlags.PropertyNamePropagatingFlags */); } function propagateChildFlags(child) { if (!child) @@ -314614,29 +314968,29 @@ var ts; case 208 /* SyntaxKind.CallExpression */: case 209 /* SyntaxKind.NewExpression */: case 204 /* SyntaxKind.ArrayLiteralExpression */: - return 536887296 /* TransformFlags.ArrayLiteralOrCallOrNewExcludes */; + return -2147450880 /* TransformFlags.ArrayLiteralOrCallOrNewExcludes */; case 261 /* SyntaxKind.ModuleDeclaration */: - return 589443072 /* TransformFlags.ModuleExcludes */; + return -1941676032 /* TransformFlags.ModuleExcludes */; case 164 /* SyntaxKind.Parameter */: - return 536870912 /* TransformFlags.ParameterExcludes */; + return -2147483648 /* TransformFlags.ParameterExcludes */; case 214 /* SyntaxKind.ArrowFunction */: - return 557748224 /* TransformFlags.ArrowFunctionExcludes */; + return -2072174592 /* TransformFlags.ArrowFunctionExcludes */; case 213 /* SyntaxKind.FunctionExpression */: case 256 /* SyntaxKind.FunctionDeclaration */: - return 591310848 /* TransformFlags.FunctionExcludes */; + return -1937940480 /* TransformFlags.FunctionExcludes */; case 255 /* SyntaxKind.VariableDeclarationList */: - return 537165824 /* TransformFlags.VariableDeclarationListExcludes */; + return -2146893824 /* TransformFlags.VariableDeclarationListExcludes */; case 257 /* SyntaxKind.ClassDeclaration */: case 226 /* SyntaxKind.ClassExpression */: - return 536940544 /* TransformFlags.ClassExcludes */; + return -2147344384 /* TransformFlags.ClassExcludes */; case 171 /* SyntaxKind.Constructor */: - return 591306752 /* TransformFlags.ConstructorExcludes */; + return -1937948672 /* TransformFlags.ConstructorExcludes */; case 167 /* SyntaxKind.PropertyDeclaration */: - return 570433536 /* TransformFlags.PropertyExcludes */; + return -2013249536 /* TransformFlags.PropertyExcludes */; case 169 /* SyntaxKind.MethodDeclaration */: case 172 /* SyntaxKind.GetAccessor */: case 173 /* SyntaxKind.SetAccessor */: - return 574529536 /* TransformFlags.MethodOrAccessorExcludes */; + return -2005057536 /* TransformFlags.MethodOrAccessorExcludes */; case 130 /* SyntaxKind.AnyKeyword */: case 147 /* SyntaxKind.NumberKeyword */: case 158 /* SyntaxKind.BigIntKeyword */: @@ -314656,23 +315010,23 @@ var ts; case 259 /* SyntaxKind.TypeAliasDeclaration */: return -2 /* TransformFlags.TypeExcludes */; case 205 /* SyntaxKind.ObjectLiteralExpression */: - return 536973312 /* TransformFlags.ObjectLiteralExcludes */; + return -2147278848 /* TransformFlags.ObjectLiteralExcludes */; case 292 /* SyntaxKind.CatchClause */: - return 536903680 /* TransformFlags.CatchClauseExcludes */; + return -2147418112 /* TransformFlags.CatchClauseExcludes */; case 201 /* SyntaxKind.ObjectBindingPattern */: case 202 /* SyntaxKind.ArrayBindingPattern */: - return 536887296 /* TransformFlags.BindingPatternExcludes */; + return -2147450880 /* TransformFlags.BindingPatternExcludes */; case 211 /* SyntaxKind.TypeAssertionExpression */: case 229 /* SyntaxKind.AsExpression */: case 350 /* SyntaxKind.PartiallyEmittedExpression */: case 212 /* SyntaxKind.ParenthesizedExpression */: case 106 /* SyntaxKind.SuperKeyword */: - return 536870912 /* TransformFlags.OuterExpressionExcludes */; + return -2147483648 /* TransformFlags.OuterExpressionExcludes */; case 206 /* SyntaxKind.PropertyAccessExpression */: case 207 /* SyntaxKind.ElementAccessExpression */: - return 536870912 /* TransformFlags.PropertyAccessExcludes */; + return -2147483648 /* TransformFlags.PropertyAccessExcludes */; default: - return 536870912 /* TransformFlags.NodeExcludes */; + return -2147483648 /* TransformFlags.NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -316082,6 +316436,11 @@ var ts; return node.kind === 126 /* SyntaxKind.AbstractKeyword */; } ts.isAbstractModifier = isAbstractModifier; + /* @internal */ + function isOverrideModifier(node) { + return node.kind === 159 /* SyntaxKind.OverrideKeyword */; + } + ts.isOverrideModifier = isOverrideModifier; /*@internal*/ function isSuperKeyword(node) { return node.kind === 106 /* SyntaxKind.SuperKeyword */; @@ -316878,7 +317237,7 @@ var ts; (function (ts) { // Compound nodes function createEmptyExports(factory) { - return factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); + return factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); } ts.createEmptyExports = createEmptyExports; function createMemberAccessForPropertyName(factory, target, memberName, location) { @@ -317028,13 +317387,13 @@ var ts; return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({ enumerable: factory.createFalse(), configurable: true, - get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers, + get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(getAccessor), /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, getAccessor.parameters, /*type*/ undefined, getAccessor.body // TODO: GH#18217 ), getAccessor), getAccessor), - set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers, + set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(setAccessor), /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, setAccessor.parameters, @@ -317053,7 +317412,7 @@ var ts; /*original*/ property); } function createExpressionForMethodDeclaration(factory, method, receiver) { - return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(method.modifiers, method.asteriskToken, + return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(ts.getModifiers(method), method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, method.parameters, /*type*/ undefined, method.body // TODO: GH#18217 @@ -317286,7 +317645,6 @@ var ts; } if (namedBindings) { var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText), /*assertClause*/ undefined); ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* EmitFlags.NeverApplyImportHelper */); @@ -317605,33 +317963,50 @@ var ts; } } ts.getJSDocTypeAliasName = getJSDocTypeAliasName; - function canHaveModifiers(node) { + function canHaveIllegalType(node) { var kind = node.kind; - return kind === 164 /* SyntaxKind.Parameter */ - || kind === 166 /* SyntaxKind.PropertySignature */ - || kind === 167 /* SyntaxKind.PropertyDeclaration */ - || kind === 168 /* SyntaxKind.MethodSignature */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 171 /* SyntaxKind.Constructor */ + return kind === 171 /* SyntaxKind.Constructor */ + || kind === 173 /* SyntaxKind.SetAccessor */; + } + ts.canHaveIllegalType = canHaveIllegalType; + function canHaveIllegalTypeParameters(node) { + var kind = node.kind; + return kind === 171 /* SyntaxKind.Constructor */ || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */; + } + ts.canHaveIllegalTypeParameters = canHaveIllegalTypeParameters; + function canHaveIllegalDecorators(node) { + var kind = node.kind; + return kind === 296 /* SyntaxKind.PropertyAssignment */ + || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 256 /* SyntaxKind.FunctionDeclaration */ + || kind === 171 /* SyntaxKind.Constructor */ || kind === 176 /* SyntaxKind.IndexSignature */ - || kind === 213 /* SyntaxKind.FunctionExpression */ - || kind === 214 /* SyntaxKind.ArrowFunction */ - || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 276 /* SyntaxKind.MissingDeclaration */ || kind === 237 /* SyntaxKind.VariableStatement */ - || kind === 256 /* SyntaxKind.FunctionDeclaration */ - || kind === 257 /* SyntaxKind.ClassDeclaration */ || kind === 258 /* SyntaxKind.InterfaceDeclaration */ || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ || kind === 260 /* SyntaxKind.EnumDeclaration */ || kind === 261 /* SyntaxKind.ModuleDeclaration */ || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ || kind === 266 /* SyntaxKind.ImportDeclaration */ - || kind === 271 /* SyntaxKind.ExportAssignment */ - || kind === 272 /* SyntaxKind.ExportDeclaration */; + || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */ + || kind === 272 /* SyntaxKind.ExportDeclaration */ + || kind === 271 /* SyntaxKind.ExportAssignment */; } - ts.canHaveModifiers = canHaveModifiers; + ts.canHaveIllegalDecorators = canHaveIllegalDecorators; + function canHaveIllegalModifiers(node) { + var kind = node.kind; + return kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 296 /* SyntaxKind.PropertyAssignment */ + || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 179 /* SyntaxKind.FunctionType */ + || kind === 276 /* SyntaxKind.MissingDeclaration */ + || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */; + } + ts.canHaveIllegalModifiers = canHaveIllegalModifiers; ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken); ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode); @@ -317895,6 +318270,14 @@ var ts; } } ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline; + function elideNodes(factory, nodes) { + if (nodes === undefined) + return undefined; + if (nodes.length === 0) + return nodes; + return ts.setTextRange(factory.createNodeArray([], nodes.hasTrailingComma), nodes); + } + ts.elideNodes = elideNodes; })(ts || (ts = {})); var ts; (function (ts) { @@ -317902,6 +318285,46 @@ var ts; return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range; } ts.setTextRange = setTextRange; + function canHaveModifiers(node) { + var kind = node.kind; + return kind === 163 /* SyntaxKind.TypeParameter */ + || kind === 164 /* SyntaxKind.Parameter */ + || kind === 166 /* SyntaxKind.PropertySignature */ + || kind === 167 /* SyntaxKind.PropertyDeclaration */ + || kind === 168 /* SyntaxKind.MethodSignature */ + || kind === 169 /* SyntaxKind.MethodDeclaration */ + || kind === 171 /* SyntaxKind.Constructor */ + || kind === 172 /* SyntaxKind.GetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 176 /* SyntaxKind.IndexSignature */ + || kind === 180 /* SyntaxKind.ConstructorType */ + || kind === 213 /* SyntaxKind.FunctionExpression */ + || kind === 214 /* SyntaxKind.ArrowFunction */ + || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 237 /* SyntaxKind.VariableStatement */ + || kind === 256 /* SyntaxKind.FunctionDeclaration */ + || kind === 257 /* SyntaxKind.ClassDeclaration */ + || kind === 258 /* SyntaxKind.InterfaceDeclaration */ + || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ + || kind === 260 /* SyntaxKind.EnumDeclaration */ + || kind === 261 /* SyntaxKind.ModuleDeclaration */ + || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ + || kind === 266 /* SyntaxKind.ImportDeclaration */ + || kind === 271 /* SyntaxKind.ExportAssignment */ + || kind === 272 /* SyntaxKind.ExportDeclaration */; + } + ts.canHaveModifiers = canHaveModifiers; + function canHaveDecorators(node) { + var kind = node.kind; + return kind === 164 /* SyntaxKind.Parameter */ + || kind === 167 /* SyntaxKind.PropertyDeclaration */ + || kind === 169 /* SyntaxKind.MethodDeclaration */ + || kind === 172 /* SyntaxKind.GetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 257 /* SyntaxKind.ClassDeclaration */; + } + ts.canHaveDecorators = canHaveDecorators; })(ts || (ts = {})); var ts; (function (ts) { @@ -317971,7 +318394,7 @@ var ts; } ts.isFileProbablyExternalModule = isFileProbablyExternalModule; function isAnExternalModuleIndicatorNode(node) { - return hasModifierOfKind(node, 93 /* SyntaxKind.ExportKeyword */) + return ts.canHaveModifiers(node) && hasModifierOfKind(node, 93 /* SyntaxKind.ExportKeyword */) || ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference) || ts.isImportDeclaration(node) || ts.isExportAssignment(node) @@ -318020,7 +318443,7 @@ var ts; visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || @@ -318030,79 +318453,128 @@ var ts; case 298 /* SyntaxKind.SpreadAssignment */: return visitNode(cbNode, node.expression); case 164 /* SyntaxKind.Parameter */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 167 /* SyntaxKind.PropertyDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 166 /* SyntaxKind.PropertySignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 296 /* SyntaxKind.PropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.initializer); case 254 /* SyntaxKind.VariableDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || + return visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 203 /* SyntaxKind.BindingElement */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.dotDotDotToken) || + return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: case 176 /* SyntaxKind.IndexSignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); + case 180 /* SyntaxKind.ConstructorType */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 179 /* SyntaxKind.FunctionType */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 174 /* SyntaxKind.CallSignature */: + case 175 /* SyntaxKind.ConstructSignature */: + return visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 169 /* SyntaxKind.MethodDeclaration */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 168 /* SyntaxKind.MethodSignature */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 171 /* SyntaxKind.Constructor */: + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 172 /* SyntaxKind.GetAccessor */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 173 /* SyntaxKind.SetAccessor */: - case 213 /* SyntaxKind.FunctionExpression */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 256 /* SyntaxKind.FunctionDeclaration */: - case 214 /* SyntaxKind.ArrowFunction */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 213 /* SyntaxKind.FunctionExpression */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 214 /* SyntaxKind.ArrowFunction */: + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.body); case 178 /* SyntaxKind.TypeReference */: @@ -318230,7 +318702,7 @@ var ts; return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); case 237 /* SyntaxKind.VariableStatement */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); case 255 /* SyntaxKind.VariableDeclarationList */: @@ -318295,27 +318767,26 @@ var ts; return visitNode(cbNode, node.expression); case 257 /* SyntaxKind.ClassDeclaration */: case 226 /* SyntaxKind.ClassExpression */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 258 /* SyntaxKind.InterfaceDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 259 /* SyntaxKind.TypeAliasDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); case 260 /* SyntaxKind.EnumDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); @@ -318323,17 +318794,17 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); case 261 /* SyntaxKind.ModuleDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); case 266 /* SyntaxKind.ImportDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -318347,7 +318818,8 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.value); case 264 /* SyntaxKind.NamespaceExportDeclaration */: - return visitNode(cbNode, node.name); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNode(cbNode, node.name); case 268 /* SyntaxKind.NamespaceImport */: return visitNode(cbNode, node.name); case 274 /* SyntaxKind.NamespaceExport */: @@ -318356,7 +318828,7 @@ var ts; case 273 /* SyntaxKind.NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); case 272 /* SyntaxKind.ExportDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -318366,17 +318838,21 @@ var ts; return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); case 271 /* SyntaxKind.ExportAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); case 223 /* SyntaxKind.TemplateExpression */: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 233 /* SyntaxKind.TemplateSpan */: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.literal); case 198 /* SyntaxKind.TemplateLiteralType */: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 199 /* SyntaxKind.TemplateLiteralTypeSpan */: - return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.literal); case 162 /* SyntaxKind.ComputedPropertyName */: return visitNode(cbNode, node.expression); case 291 /* SyntaxKind.HeritageClause */: @@ -318387,7 +318863,8 @@ var ts; case 277 /* SyntaxKind.ExternalModuleReference */: return visitNode(cbNode, node.expression); case 276 /* SyntaxKind.MissingDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers); case 351 /* SyntaxKind.CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 278 /* SyntaxKind.JsxElement */: @@ -318503,6 +318980,7 @@ var ts; case 335 /* SyntaxKind.JSDocProtectedTag */: case 336 /* SyntaxKind.JSDocReadonlyTag */: case 331 /* SyntaxKind.JSDocDeprecatedTag */: + case 337 /* SyntaxKind.JSDocOverrideTag */: return visitNode(cbNode, node.tagName) || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); case 350 /* SyntaxKind.PartiallyEmittedExpression */: @@ -319066,7 +319544,7 @@ var ts; return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { return !(node.flags & 32768 /* NodeFlags.AwaitContext */) - && !!(node.transformFlags & 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */); + && !!(node.transformFlags & 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */); } function findNextStatementWithAwait(statements, start) { for (var i = start; i < statements.length; i++) { @@ -319107,7 +319585,7 @@ var ts; ts.setTextRangePosWidth(sourceFile, 0, sourceText.length); setFields(sourceFile); // If we parsed this as an external module, it may contain top-level await - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */) { + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */) { sourceFile = reparseTopLevelAwait(sourceFile); setFields(sourceFile); } @@ -320035,7 +320513,7 @@ var ts; } return parseElement(); } - function currentNode(parsingContext) { + function currentNode(parsingContext, pos) { // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse. // // If there is an outstanding parse error that we've encountered, but not attached to @@ -320048,7 +320526,7 @@ var ts; if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } - var node = syntaxCursor.currentNode(scanner.getStartPos()); + var node = syntaxCursor.currentNode(pos !== null && pos !== void 0 ? pos : scanner.getStartPos()); // Can't reuse a missing node. // Can't reuse a node that intersected the change range. // Can't reuse a node that contains a parse error. This is necessary so that we @@ -320323,7 +320801,9 @@ var ts; case 23 /* ParsingContext.ImportOrExportSpecifiers */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 13 /* ParsingContext.JsxAttributes */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 14 /* ParsingContext.JsxChildren */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - default: return [undefined]; // TODO: GH#18217 `default: Debug.assertNever(context);` + case 24 /* ParsingContext.AssertEntries */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_or_string_literal_expected); // AssertionKey. + case 25 /* ParsingContext.Count */: return ts.Debug.fail("ParsingContext.Count used as a context"); // Not a real context, only a marker. + default: ts.Debug.assertNever(context); } } function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { @@ -320639,7 +321119,6 @@ var ts; parseExpected(58 /* SyntaxKind.ColonToken */); } return finishNode(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier? @@ -320765,10 +321244,9 @@ var ts; // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : doOutsideOfAwaitContext(parseDecorators); if (token() === 108 /* SyntaxKind.ThisKeyword */) { var node_1 = factory.createParameterDeclaration(decorators, - /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); @@ -320779,12 +321257,12 @@ var ts; } var savedTopLevel = topLevel; topLevel = false; - var modifiers = parseModifiers(); + var modifiers = combineDecoratorsAndModifiers(decorators, parseModifiers()); var dotDotDotToken = parseOptionalToken(25 /* SyntaxKind.DotDotDotToken */); if (!allowAmbiguity && !isParameterNameStart()) { return undefined; } - var node = withJSDoc(finishNode(factory.createParameterDeclaration(decorators, modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57 /* SyntaxKind.QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createParameterDeclaration(modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57 /* SyntaxKind.QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); topLevel = savedTopLevel; return node; } @@ -320936,7 +321414,8 @@ var ts; var parameters = parseBracketedList(16 /* ParsingContext.Parameters */, function () { return parseParameter(/*inOuterAwaitContext*/ false); }, 22 /* SyntaxKind.OpenBracketToken */, 23 /* SyntaxKind.CloseBracketToken */); var type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - var node = factory.createIndexSignature(decorators, modifiers, parameters, type); + var node = factory.createIndexSignature(modifiers, parameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) { @@ -321009,10 +321488,10 @@ var ts; var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SyntaxKind.GetAccessor */, 4 /* SignatureFlags.Type */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 173 /* SyntaxKind.SetAccessor */, 4 /* SignatureFlags.Type */); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers); @@ -321650,10 +322129,10 @@ var ts; setDecoratorContext(/*val*/ false); } var pos = getNodePos(); - var expr = parseAssignmentExpressionOrHigher(); + var expr = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); var operatorToken; while ((operatorToken = parseOptionalToken(27 /* SyntaxKind.CommaToken */))) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(), pos); + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true), pos); } if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -321661,9 +322140,9 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(63 /* SyntaxKind.EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(63 /* SyntaxKind.EqualsToken */) ? parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true) : undefined; } - function parseAssignmentExpressionOrHigher() { + function parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) { // AssignmentExpression[in,yield]: // 1) ConditionalExpression[?in,?yield] // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] @@ -321689,7 +322168,7 @@ var ts; // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. - var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + var arrowExpression = tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) || tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction); if (arrowExpression) { return arrowExpression; } @@ -321708,7 +322187,7 @@ var ts; // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. if (expr.kind === 79 /* SyntaxKind.Identifier */ && token() === 38 /* SyntaxKind.EqualsGreaterThanToken */) { - return parseSimpleArrowFunctionExpression(pos, expr, /*asyncModifier*/ undefined); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, /*asyncModifier*/ undefined); } // Now see if we might be in cases '2' or '3'. // If the expression was a LHS expression, and we have an assignment operator, then @@ -321717,10 +322196,10 @@ var ts; // Note: we call reScanGreaterToken so that we get an appropriately merged token // for cases like `> > =` becoming `>>=` if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(), pos); + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction), pos); } // It wasn't an assignment or a lambda. This is a conditional expression: - return parseConditionalExpressionRest(expr, pos); + return parseConditionalExpressionRest(expr, pos, allowReturnTypeInArrowFunction); } function isYieldExpression() { if (token() === 125 /* SyntaxKind.YieldKeyword */) { @@ -321760,7 +322239,7 @@ var ts; nextToken(); if (!scanner.hasPrecedingLineBreak() && (token() === 41 /* SyntaxKind.AsteriskToken */ || isStartOfExpression())) { - return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* SyntaxKind.AsteriskToken */), parseAssignmentExpressionOrHigher()), pos); + return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* SyntaxKind.AsteriskToken */), parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)), pos); } else { // if the next token is not on the same line as yield. or we don't have an '*' or @@ -321768,10 +322247,9 @@ var ts; return finishNode(factory.createYieldExpression(/*asteriskToken*/ undefined, /*expression*/ undefined), pos); } } - function parseSimpleArrowFunctionExpression(pos, identifier, asyncModifier) { + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, asyncModifier) { ts.Debug.assert(token() === 38 /* SyntaxKind.EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var parameter = factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, identifier, /*questionToken*/ undefined, @@ -321780,11 +322258,11 @@ var ts; finishNode(parameter, identifier.pos); var parameters = createNodeArray([parameter], parameter.pos, parameter.end); var equalsGreaterThanToken = parseExpectedToken(38 /* SyntaxKind.EqualsGreaterThanToken */); - var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); + var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier, allowReturnTypeInArrowFunction); var node = factory.createArrowFunction(asyncModifier, /*typeParameters*/ undefined, parameters, /*type*/ undefined, equalsGreaterThanToken, body); return addJSDocComment(finishNode(node, pos)); } - function tryParseParenthesizedArrowFunctionExpression() { + function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var triState = isParenthesizedArrowFunctionExpression(); if (triState === 0 /* Tristate.False */) { // It's definitely not a parenthesized arrow function expression. @@ -321795,8 +322273,8 @@ var ts; // it out, but don't allow any ambiguity, and return 'undefined' if this could be an // expression instead. return triState === 1 /* Tristate.True */ ? - parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true) : - tryParse(parsePossibleParenthesizedArrowFunctionExpression); + parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true, /*allowReturnTypeInArrowFunction*/ true) : + tryParse(function () { return parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction); }); } // True -> We definitely expect a parenthesized arrow function here. // False -> There *cannot* be a parenthesized arrow function here. @@ -321861,7 +322339,7 @@ var ts; // isn't actually allowed, but we want to treat it as a lambda so we can provide // a good error message. if (ts.isModifierKind(second) && second !== 131 /* SyntaxKind.AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { - if (lookAhead(function () { return nextToken() === 127 /* SyntaxKind.AsKeyword */; })) { + if (nextToken() === 127 /* SyntaxKind.AsKeyword */) { // https://github.com/microsoft/TypeScript/issues/44466 return 0 /* Tristate.False */; } @@ -321930,25 +322408,25 @@ var ts; return 2 /* Tristate.Unknown */; } } - function parsePossibleParenthesizedArrowFunctionExpression() { + function parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var tokenPos = scanner.getTokenPos(); if (notParenthesizedArrow === null || notParenthesizedArrow === void 0 ? void 0 : notParenthesizedArrow.has(tokenPos)) { return undefined; } - var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false); + var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false, allowReturnTypeInArrowFunction); if (!result) { (notParenthesizedArrow || (notParenthesizedArrow = new ts.Set())).add(tokenPos); } return result; } - function tryParseAsyncSimpleArrowFunctionExpression() { + function tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction) { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" if (token() === 131 /* SyntaxKind.AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* Tristate.True */) { var pos = getNodePos(); var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(0 /* OperatorPrecedence.Lowest */); - return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, asyncModifier); } } return undefined; @@ -321972,7 +322450,7 @@ var ts; } return 0 /* Tristate.False */; } - function parseParenthesizedArrowFunctionExpression(allowAmbiguity) { + function parseParenthesizedArrowFunctionExpression(allowAmbiguity, allowReturnTypeInArrowFunction) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiersForArrowFunction(); @@ -322007,6 +322485,7 @@ var ts; return undefined; } } + var hasReturnColon = token() === 58 /* SyntaxKind.ColonToken */; var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) { return undefined; @@ -322035,12 +322514,37 @@ var ts; var lastToken = token(); var equalsGreaterThanToken = parseExpectedToken(38 /* SyntaxKind.EqualsGreaterThanToken */); var body = (lastToken === 38 /* SyntaxKind.EqualsGreaterThanToken */ || lastToken === 18 /* SyntaxKind.OpenBraceToken */) - ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier)) + ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier), allowReturnTypeInArrowFunction) : parseIdentifier(); + // Given: + // x ? y => ({ y }) : z => ({ z }) + // We try to parse the body of the first arrow function by looking at: + // ({ y }) : z => ({ z }) + // This is a valid arrow function with "z" as the return type. + // + // But, if we're in the true side of a conditional expression, this colon + // terminates the expression, so we cannot allow a return type if we aren't + // certain whether or not the preceding text was parsed as a parameter list. + // + // For example, + // a() ? (b: number, c?: string): void => d() : e + // is determined by isParenthesizedArrowFunctionExpression to unambiguously + // be an arrow expression, so we allow a return type. + if (!allowReturnTypeInArrowFunction && hasReturnColon) { + // However, if the arrow function we were able to parse is followed by another colon + // as in: + // a ? (x): string => x : null + // Then allow the arrow function, and treat the second colon as terminating + // the conditional expression. It's okay to do this because this code would + // be a syntax error in JavaScript (as the second colon shouldn't be there). + if (token() !== 58 /* SyntaxKind.ColonToken */) { + return undefined; + } + } var node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseArrowFunctionExpressionBody(isAsync) { + function parseArrowFunctionExpressionBody(isAsync, allowReturnTypeInArrowFunction) { if (token() === 18 /* SyntaxKind.OpenBraceToken */) { return parseFunctionBlock(isAsync ? 2 /* SignatureFlags.Await */ : 0 /* SignatureFlags.None */); } @@ -322068,12 +322572,12 @@ var ts; var savedTopLevel = topLevel; topLevel = false; var node = isAsync - ? doInAwaitContext(parseAssignmentExpressionOrHigher) - : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + ? doInAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }) + : doOutsideOfAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }); topLevel = savedTopLevel; return node; } - function parseConditionalExpressionRest(leftOperand, pos) { + function parseConditionalExpressionRest(leftOperand, pos, allowReturnTypeInArrowFunction) { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. var questionToken = parseOptionalToken(57 /* SyntaxKind.QuestionToken */); if (!questionToken) { @@ -322082,8 +322586,8 @@ var ts; // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. var colonToken; - return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher), colonToken = parseExpectedToken(58 /* SyntaxKind.ColonToken */), ts.nodeIsPresent(colonToken) - ? parseAssignmentExpressionOrHigher() + return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ false); }), colonToken = parseExpectedToken(58 /* SyntaxKind.ColonToken */), ts.nodeIsPresent(colonToken) + ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) : createMissingNode(79 /* SyntaxKind.Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* SyntaxKind.ColonToken */))), pos); } function parseBinaryExpressionOrHigher(precedence) { @@ -322468,6 +322972,9 @@ var ts; var typeArguments = tryParse(parseTypeArgumentsInExpression); if (typeArguments !== undefined) { parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments); + if (!isTemplateStartOfTaggedTemplate()) { + expression = factory.createExpressionWithTypeArguments(expression, typeArguments); + } } } if (token() === 20 /* SyntaxKind.OpenParenToken */ || token() === 24 /* SyntaxKind.DotToken */ || token() === 22 /* SyntaxKind.OpenBracketToken */) { @@ -322680,9 +323187,22 @@ var ts; } scanJsxIdentifier(); var pos = getNodePos(); - return finishNode(factory.createJsxAttribute(parseIdentifierName(), token() !== 63 /* SyntaxKind.EqualsToken */ ? undefined : - scanJsxAttributeValue() === 10 /* SyntaxKind.StringLiteral */ ? parseLiteralNode() : - parseJsxExpression(/*inExpressionContext*/ true)), pos); + return finishNode(factory.createJsxAttribute(parseIdentifierName(), parseJsxAttributeValue()), pos); + } + function parseJsxAttributeValue() { + if (token() === 63 /* SyntaxKind.EqualsToken */) { + if (scanJsxAttributeValue() === 10 /* SyntaxKind.StringLiteral */) { + return parseLiteralNode(); + } + if (token() === 18 /* SyntaxKind.OpenBraceToken */) { + return parseJsxExpression(/*inExpressionContext*/ true); + } + if (token() === 29 /* SyntaxKind.LessThanToken */) { + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + } + parseErrorAtCurrentToken(ts.Diagnostics.or_JSX_element_expected); + } + return undefined; } function parseJsxSpreadAttribute() { var pos = getNodePos(); @@ -322772,6 +323292,11 @@ var ts; if (isOptionalChain && ts.isPrivateIdentifier(propertyAccess.name)) { parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers); } + if (ts.isExpressionWithTypeArguments(expression) && expression.typeArguments) { + var pos_2 = expression.typeArguments.pos - 1; + var end = ts.skipTrivia(sourceText, expression.typeArguments.end) + 1; + parseErrorAt(pos_2, end, ts.Diagnostics.An_instantiation_expression_cannot_be_followed_by_a_property_access); + } return finishNode(propertyAccess, pos); } function parseElementAccessExpressionRest(pos, expression, questionDotToken) { @@ -322915,9 +323440,18 @@ var ts; case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: // foo `...` case 15 /* SyntaxKind.TemplateHead */: // foo `...${100}...` return true; + // A type argument list followed by `<` never makes sense, and a type argument list followed + // by `>` is ambiguous with a (re-scanned) `>>` operator, so we disqualify both. Also, in + // this context, `+` and `-` are unary operators, not binary operators. + case 29 /* SyntaxKind.LessThanToken */: + case 31 /* SyntaxKind.GreaterThanToken */: + case 39 /* SyntaxKind.PlusToken */: + case 40 /* SyntaxKind.MinusToken */: + return false; } - // Consider something a type argument list only if the following token can't start an expression. - return !isStartOfExpression(); + // We favor the type argument list interpretation when it is immediately followed by + // a line break, a binary operator, or something that can't start an expression. + return scanner.hasPrecedingLineBreak() || isBinaryOperator() || !isStartOfExpression(); } function parsePrimaryExpression() { switch (token()) { @@ -322976,13 +323510,13 @@ var ts; function parseSpreadElement() { var pos = getNodePos(); parseExpected(25 /* SyntaxKind.DotDotDotToken */); - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory.createSpreadElement(expression), pos); } function parseArgumentOrArrayLiteralElement() { return token() === 25 /* SyntaxKind.DotDotDotToken */ ? parseSpreadElement() : token() === 27 /* SyntaxKind.CommaToken */ ? finishNode(factory.createOmittedExpression(), getNodePos()) : - parseAssignmentExpressionOrHigher(); + parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); @@ -323000,16 +323534,16 @@ var ts; var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); if (parseOptionalToken(25 /* SyntaxKind.DotDotDotToken */)) { - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc); } var decorators = parseDecorators(); var modifiers = parseModifiers(); if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } var asteriskToken = parseOptionalToken(41 /* SyntaxKind.AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -323029,7 +323563,7 @@ var ts; var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* SyntaxKind.ColonToken */); if (isShorthandPropertyAssignment) { var equalsToken = parseOptionalToken(63 /* SyntaxKind.EqualsToken */); - var objectAssignmentInitializer = equalsToken ? allowInAnd(parseAssignmentExpressionOrHigher) : undefined; + var objectAssignmentInitializer = equalsToken ? allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }) : undefined; node = factory.createShorthandPropertyAssignment(name, objectAssignmentInitializer); // Save equals token for error reporting. // TODO(rbuckton): Consider manufacturing this when we need to report an error as it is otherwise not useful. @@ -323037,11 +323571,11 @@ var ts; } else { parseExpected(58 /* SyntaxKind.ColonToken */); - var initializer = allowInAnd(parseAssignmentExpressionOrHigher); + var initializer = allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }); node = factory.createPropertyAssignment(name, initializer); } // Decorators, Modifiers, questionToken, and exclamationToken are not supported by property assignments and are reported in the grammar checker - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; node.questionToken = questionToken; node.exclamationToken = exclamationToken; @@ -323101,6 +323635,9 @@ var ts; typeArguments = expression.typeArguments; expression = expression.expression; } + if (token() === 28 /* SyntaxKind.QuestionDotToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, ts.getTextOfNodeFromSourceText(sourceText, expression)); + } var argumentList = token() === 20 /* SyntaxKind.OpenParenToken */ ? parseArgumentList() : undefined; return finishNode(factory.createNewExpression(expression, typeArguments, argumentList), pos); } @@ -323211,7 +323748,7 @@ var ts; } var node; if (awaitToken ? parseExpected(160 /* SyntaxKind.OfKeyword */) : parseOptional(160 /* SyntaxKind.OfKeyword */)) { - var expression = allowInAnd(parseAssignmentExpressionOrHigher); + var expression = allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }); parseExpected(21 /* SyntaxKind.CloseParenToken */); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); } @@ -323616,24 +324153,19 @@ var ts; return modifier.kind === 135 /* SyntaxKind.DeclareKeyword */; } function parseDeclaration() { - // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner - // if we can't reuse the declaration, so that we don't do this work twice? - // // `parseListElement` attempted to get the reused node at this position, // but the ambient context flag was not yet set, so the node appeared // not reusable in that context. - var isAmbient = ts.some(lookAhead(function () { return (parseDecorators(), parseModifiers()); }), isDeclareModifier); - if (isAmbient) { - var node = tryReuseAmbientDeclaration(); - if (node) { - return node; - } - } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var decorators = parseDecorators(); var modifiers = parseModifiers(); + var isAmbient = ts.some(modifiers, isDeclareModifier); if (isAmbient) { + var node = tryReuseAmbientDeclaration(pos); + if (node) { + return node; + } for (var _i = 0, _a = modifiers; _i < _a.length; _i++) { var m = _a[_i]; m.flags |= 16777216 /* NodeFlags.Ambient */; @@ -323644,9 +324176,9 @@ var ts; return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); } } - function tryReuseAmbientDeclaration() { + function tryReuseAmbientDeclaration(pos) { return doInsideOfContext(16777216 /* NodeFlags.Ambient */, function () { - var node = currentNode(parsingContext); + var node = currentNode(parsingContext, pos); if (node) { return consumeNode(node); } @@ -323691,7 +324223,7 @@ var ts; // would follow. For recovery and error reporting purposes, return an incomplete declaration. var missing = createMissingNode(276 /* SyntaxKind.MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); - missing.decorators = decorators; + missing.illegalDecorators = decorators; missing.modifiers = modifiers; return missing; } @@ -323703,9 +324235,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* SyntaxKind.StringLiteral */); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 18 /* SyntaxKind.OpenBraceToken */ && canParseSemicolon()) { - parseSemicolon(); - return; + if (token() !== 18 /* SyntaxKind.OpenBraceToken */) { + if (flags & 4 /* SignatureFlags.Type */) { + parseTypeMemberSemicolon(); + return; + } + if (canParseSemicolon()) { + parseSemicolon(); + return; + } } return parseFunctionBlock(flags, diagnosticMessage); } @@ -323828,7 +324366,7 @@ var ts; parseSemicolon(); var node = factory.createVariableStatement(modifiers, declarationList); // Decorators are not allowed on a variable statement, so we keep track of them to report them in the grammar checker. - node.decorators = decorators; + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -323847,7 +324385,8 @@ var ts; var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); setAwaitContext(savedAwaitContext); - var node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + var node = factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseConstructorName() { @@ -323868,8 +324407,9 @@ var ts; var parameters = parseParameters(0 /* SignatureFlags.None */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(0 /* SignatureFlags.None */, ts.Diagnostics.or_expected); - var node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body); - // Attach `typeParameters` and `type` if they exist so that we can report them in the grammar checker. + var node = factory.createConstructorDeclaration(modifiers, parameters, body); + // Attach invalid nodes if they exist so that we can report them in the grammar checker. + node.illegalDecorators = decorators; node.typeParameters = typeParameters; node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -323883,7 +324423,7 @@ var ts; var parameters = parseParameters(isGenerator | isAsync); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - var node = factory.createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + var node = factory.createMethodDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); // An exclamation token on a method is invalid syntax and will be handled by the grammar checker node.exclamationToken = exclamationToken; return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -323893,7 +324433,7 @@ var ts; var type = parseTypeAnnotation(); var initializer = doOutsideOfContext(8192 /* NodeFlags.YieldContext */ | 32768 /* NodeFlags.AwaitContext */ | 4096 /* NodeFlags.DisallowInContext */, parseInitializer); parseSemicolonAfterPropertyName(name, type, initializer); - var node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer); + var node = factory.createPropertyDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, questionToken || exclamationToken, type, initializer); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -323907,18 +324447,18 @@ var ts; } return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken); } - function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind) { + function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind, flags) { var name = parsePropertyName(); var typeParameters = parseTypeParameters(); var parameters = parseParameters(0 /* SignatureFlags.None */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); - var body = parseFunctionBlockOrSemicolon(0 /* SignatureFlags.None */); + var body = parseFunctionBlockOrSemicolon(flags); var node = kind === 172 /* SyntaxKind.GetAccessor */ - ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) - : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); + ? factory.createGetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, type, body) + : factory.createSetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, body); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors node.typeParameters = typeParameters; - if (type && node.kind === 173 /* SyntaxKind.SetAccessor */) + if (ts.isSetAccessorDeclaration(node)) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -323984,7 +324524,10 @@ var ts; function parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers) { parseExpectedToken(124 /* SyntaxKind.StaticKeyword */); var body = parseClassStaticBlockBody(); - return withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(decorators, modifiers, body), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(body), pos), hasJSDoc); + node.illegalDecorators = decorators; + node.modifiers = modifiers; + return node; } function parseClassStaticBlockBody() { var savedYieldContext = inYieldContext(); @@ -324047,6 +324590,15 @@ var ts; } return finishNode(factory.createToken(kind), pos); } + function combineDecoratorsAndModifiers(decorators, modifiers) { + if (!decorators) + return modifiers; + if (!modifiers) + return decorators; + var decoratorsAndModifiers = factory.createNodeArray(ts.concatenate(decorators, modifiers)); + ts.setTextRangePosEnd(decoratorsAndModifiers, decorators.pos, modifiers.end); + return decoratorsAndModifiers; + } /* * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect @@ -324087,10 +324639,10 @@ var ts; return parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers); } if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } if (token() === 134 /* SyntaxKind.ConstructorKeyword */ || token() === 10 /* SyntaxKind.StringLiteral */) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -324155,8 +324707,8 @@ var ts; } setAwaitContext(savedAwaitContext); var node = kind === 257 /* SyntaxKind.ClassDeclaration */ - ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) - : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); + ? factory.createClassDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members) + : factory.createClassExpression(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseNameOfClassDeclarationOrExpression() { @@ -324213,7 +324765,8 @@ var ts; var typeParameters = parseTypeParameters(); var heritageClauses = parseHeritageClauses(); var members = parseObjectTypeMembers(); - var node = factory.createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members); + var node = factory.createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -324223,7 +324776,8 @@ var ts; parseExpected(63 /* SyntaxKind.EqualsToken */); var type = token() === 138 /* SyntaxKind.IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType(); parseSemicolon(); - var node = factory.createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type); + var node = factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } // In an ambient declaration, the grammar only allows integer literals as initializers. @@ -324248,7 +324802,8 @@ var ts; else { members = createMissingList(); } - var node = factory.createEnumDeclaration(decorators, modifiers, name, members); + var node = factory.createEnumDeclaration(modifiers, name, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleBlock() { @@ -324271,7 +324826,8 @@ var ts; var body = parseOptional(24 /* SyntaxKind.DotToken */) ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NodeFlags.NestedNamespace */ | namespaceFlag) : parseModuleBlock(); - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -324293,7 +324849,8 @@ var ts; else { parseSemicolon(); } - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -324333,7 +324890,7 @@ var ts; parseSemicolon(); var node = factory.createNamespaceExportDeclaration(name); // NamespaceExportDeclaration nodes cannot have decorators or modifiers, so we attach them here so we can report them in the grammar checker - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -324372,14 +324929,15 @@ var ts; assertClause = parseAssertClause(); } parseSemicolon(); - var node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause); + var node = factory.createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAssertEntry() { var pos = getNodePos(); var name = ts.tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(10 /* SyntaxKind.StringLiteral */); parseExpected(58 /* SyntaxKind.ColonToken */); - var value = parseAssignmentExpressionOrHigher(); + var value = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory.createAssertEntry(name, value), pos); } function parseAssertClause(skipAssertKeyword) { @@ -324416,7 +324974,8 @@ var ts; parseExpected(63 /* SyntaxKind.EqualsToken */); var moduleReference = parseModuleReference(); parseSemicolon(); - var node = factory.createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, identifier, moduleReference); + var node = factory.createImportEqualsDeclaration(modifiers, isTypeOnly, identifier, moduleReference); + node.illegalDecorators = decorators; var finished = withJSDoc(finishNode(node, pos), hasJSDoc); return finished; } @@ -324605,7 +325164,8 @@ var ts; } parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + var node = factory.createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseExportAssignment(pos, hasJSDoc, decorators, modifiers) { @@ -324618,10 +325178,11 @@ var ts; else { parseExpected(88 /* SyntaxKind.DefaultKeyword */); } - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportAssignment(decorators, modifiers, isExportEquals, expression); + var node = factory.createExportAssignment(modifiers, isExportEquals, expression); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } var ParsingContext; @@ -325412,7 +325973,6 @@ var ts; if (parseOptional(24 /* SyntaxKind.DotToken */)) { var body = parseJSDocTypeNameWithNamespace(/*nested*/ true); var jsDocNamespaceNode = factory.createModuleDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, typeNameOrNamespaceName, body, nested ? 4 /* NodeFlags.NestedNamespace */ : undefined); return finishNode(jsDocNamespaceNode, pos); } @@ -325849,10 +326409,10 @@ var ts; } function checkNodePositions(node, aggressiveChecks) { if (aggressiveChecks) { - var pos_2 = node.pos; + var pos_3 = node.pos; var visitNode_1 = function (child) { - ts.Debug.assert(child.pos >= pos_2); - pos_2 = child.end; + ts.Debug.assert(child.pos >= pos_3); + pos_3 = child.end; }; if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { @@ -325861,7 +326421,7 @@ var ts; } } forEachChild(node, visitNode_1); - ts.Debug.assert(pos_2 <= node.end); + ts.Debug.assert(pos_3 <= node.end); } } function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { @@ -326459,6 +327019,7 @@ var ts; ["es2022.error", "lib.es2022.error.d.ts"], ["es2022.intl", "lib.es2022.intl.d.ts"], ["es2022.object", "lib.es2022.object.d.ts"], + ["es2022.sharedmemory", "lib.es2022.sharedmemory.d.ts"], ["es2022.string", "lib.es2022.string.d.ts"], ["esnext.array", "lib.es2022.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], @@ -326672,6 +327233,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, defaultValueDescription: false, @@ -326706,12 +327268,40 @@ var ts; affectsSourceFile: true, affectsModuleResolution: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations, defaultValueDescription: 0 /* ScriptTarget.ES3 */, }; + /*@internal*/ + ts.moduleOptionDeclaration = { + name: "module", + shortName: "m", + type: new ts.Map(ts.getEntries({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + es2020: ts.ModuleKind.ES2020, + es2022: ts.ModuleKind.ES2022, + esnext: ts.ModuleKind.ESNext, + node16: ts.ModuleKind.Node16, + nodenext: ts.ModuleKind.NodeNext, + })), + affectsModuleResolution: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Modules, + description: ts.Diagnostics.Specify_what_module_code_is_generated, + defaultValueDescription: undefined, + }; var commandOptionsWithoutBuild = [ // CommandLine only options { @@ -326773,37 +327363,14 @@ var ts; category: ts.Diagnostics.Command_line_Options, affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, isCommandLineOnly: true, description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, defaultValueDescription: false, }, // Basic ts.targetOptionDeclaration, - { - name: "module", - shortName: "m", - type: new ts.Map(ts.getEntries({ - none: ts.ModuleKind.None, - commonjs: ts.ModuleKind.CommonJS, - amd: ts.ModuleKind.AMD, - system: ts.ModuleKind.System, - umd: ts.ModuleKind.UMD, - es6: ts.ModuleKind.ES2015, - es2015: ts.ModuleKind.ES2015, - es2020: ts.ModuleKind.ES2020, - es2022: ts.ModuleKind.ES2022, - esnext: ts.ModuleKind.ESNext, - node16: ts.ModuleKind.Node16, - nodenext: ts.ModuleKind.NodeNext, - })), - affectsModuleResolution: true, - affectsEmit: true, - paramType: ts.Diagnostics.KIND, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Modules, - description: ts.Diagnostics.Specify_what_module_code_is_generated, - defaultValueDescription: undefined, - }, + ts.moduleOptionDeclaration, { name: "lib", type: "list", @@ -326840,6 +327407,7 @@ var ts; type: jsxOptionMap, affectsSourceFile: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -326852,6 +327420,7 @@ var ts; shortName: "d", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -326862,6 +327431,7 @@ var ts; name: "declarationMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -326872,6 +327442,7 @@ var ts; name: "emitDeclarationOnly", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files, @@ -326882,6 +327453,7 @@ var ts; name: "sourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -326891,6 +327463,9 @@ var ts; name: "outFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, showInSimplifiedHelpView: true, @@ -326902,6 +327477,8 @@ var ts; name: "outDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, showInSimplifiedHelpView: true, @@ -326912,6 +327489,8 @@ var ts; name: "rootDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Modules, @@ -326922,6 +327501,8 @@ var ts; name: "composite", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isTSConfigOnly: true, category: ts.Diagnostics.Projects, transpileOptionValue: undefined, @@ -326932,6 +327513,8 @@ var ts; name: "tsBuildInfoFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, category: ts.Diagnostics.Projects, @@ -326943,6 +327526,7 @@ var ts; name: "removeComments", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -326961,6 +327545,7 @@ var ts; name: "importHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file, defaultValueDescription: false, @@ -326974,6 +327559,7 @@ var ts; })), affectsEmit: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types, defaultValueDescription: 0 /* ImportsNotUsedAsValues.Remove */, @@ -326982,6 +327568,7 @@ var ts; name: "downlevelIteration", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration, defaultValueDescription: false, @@ -327000,6 +327587,9 @@ var ts; type: "boolean", // Though this affects semantic diagnostics, affectsSemanticDiagnostics is not set here // The value of each strictFlag depends on own strictFlag value or this and never accessed directly. + // But we need to store `strict` in builf info, even though it won't be examined directly, so that the + // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_all_strict_type_checking_options, @@ -327009,6 +327599,7 @@ var ts; name: "noImplicitAny", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type, @@ -327018,6 +327609,7 @@ var ts; name: "strictNullChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_type_checking_take_into_account_null_and_undefined, @@ -327026,6 +327618,8 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible, @@ -327034,6 +327628,8 @@ var ts; { name: "strictBindCallApply", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function, @@ -327043,6 +327639,7 @@ var ts; name: "strictPropertyInitialization", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor, @@ -327052,6 +327649,7 @@ var ts; name: "noImplicitThis", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any, @@ -327061,6 +327659,7 @@ var ts; name: "useUnknownInCatchVariables", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, @@ -327070,6 +327669,8 @@ var ts; name: "alwaysStrict", type: "boolean", affectsSourceFile: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_use_strict_is_always_emitted, @@ -327080,6 +327681,7 @@ var ts; name: "noUnusedLocals", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_local_variables_aren_t_read, defaultValueDescription: false, @@ -327088,6 +327690,7 @@ var ts; name: "noUnusedParameters", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read, defaultValueDescription: false, @@ -327096,6 +327699,7 @@ var ts; name: "exactOptionalPropertyTypes", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, defaultValueDescription: false, @@ -327104,6 +327708,7 @@ var ts; name: "noImplicitReturns", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function, defaultValueDescription: false, @@ -327113,6 +327718,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, defaultValueDescription: false, @@ -327121,6 +327727,7 @@ var ts; name: "noUncheckedIndexedAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Add_undefined_to_a_type_when_accessed_using_an_index, defaultValueDescription: false, @@ -327129,6 +327736,7 @@ var ts; name: "noImplicitOverride", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, defaultValueDescription: false, @@ -327136,6 +327744,8 @@ var ts; { name: "noPropertyAccessFromIndexSignature", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: false, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type, @@ -327221,6 +327831,7 @@ var ts; name: "allowSyntheticDefaultImports", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export, defaultValueDescription: ts.Diagnostics.module_system_or_esModuleInterop @@ -327230,6 +327841,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility, @@ -327246,6 +327858,7 @@ var ts; name: "allowUmdGlobalAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Modules, description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules, defaultValueDescription: false, @@ -327267,6 +327880,7 @@ var ts; name: "sourceRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code, @@ -327275,6 +327889,7 @@ var ts; name: "mapRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, @@ -327283,6 +327898,7 @@ var ts; name: "inlineSourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -327291,6 +327907,7 @@ var ts; name: "inlineSources", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -327300,6 +327917,7 @@ var ts; name: "experimentalDecorators", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, defaultValueDescription: false, @@ -327309,6 +327927,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, defaultValueDescription: false, @@ -327333,6 +327952,7 @@ var ts; type: "string", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk, @@ -327350,6 +327970,9 @@ var ts; name: "out", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: false, // for correct behaviour, please use outFile category: ts.Diagnostics.Backwards_Compatibility, @@ -327361,6 +327984,7 @@ var ts; name: "reactNamespace", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit, defaultValueDescription: "`React`", @@ -327368,6 +327992,8 @@ var ts; { name: "skipDefaultLibCheck", type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript, defaultValueDescription: false, @@ -327383,6 +328009,7 @@ var ts; name: "emitBOM", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files, defaultValueDescription: false, @@ -327394,6 +328021,7 @@ var ts; lf: 1 /* NewLineKind.LineFeed */ })), affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.NEWLINE, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Set_the_newline_character_for_emitting_files, @@ -327403,6 +328031,7 @@ var ts; name: "noErrorTruncation", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_truncating_types_in_error_messages, defaultValueDescription: false, @@ -327433,6 +328062,7 @@ var ts; name: "stripInternal", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, defaultValueDescription: false, @@ -327473,6 +328103,7 @@ var ts; name: "noImplicitUseStrict", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files, defaultValueDescription: false, @@ -327481,6 +328112,7 @@ var ts; name: "noEmitHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output, defaultValueDescription: false, @@ -327489,6 +328121,7 @@ var ts; name: "noEmitOnError", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported, @@ -327498,6 +328131,7 @@ var ts; name: "preserveConstEnums", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, defaultValueDescription: false, @@ -327506,6 +328140,8 @@ var ts; name: "declarationDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, category: ts.Diagnostics.Emit, @@ -327515,6 +328151,8 @@ var ts; { name: "skipLibCheck", type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_all_d_ts_files, defaultValueDescription: false, @@ -327524,6 +328162,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unused_labels, defaultValueDescription: undefined, @@ -327533,6 +328172,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unreachable_code, defaultValueDescription: undefined, @@ -327541,6 +328181,7 @@ var ts; name: "suppressExcessPropertyErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals, defaultValueDescription: false, @@ -327549,6 +328190,7 @@ var ts; name: "suppressImplicitAnyIndexErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures, defaultValueDescription: false, @@ -327573,6 +328215,7 @@ var ts; name: "noStrictGenericChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, defaultValueDescription: false, @@ -327582,6 +328225,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_ECMAScript_standard_compliant_class_fields, defaultValueDescription: ts.Diagnostics.true_for_ES2022_and_above_including_ESNext @@ -327590,6 +328234,7 @@ var ts; name: "preserveValueImports", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, defaultValueDescription: false, @@ -327633,6 +328278,8 @@ var ts; /* @internal */ ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; }); /* @internal */ + ts.affectsDeclarationPathOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsDeclarationPath; }); + /* @internal */ ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); /* @internal */ ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { @@ -328455,7 +329102,7 @@ var ts; return undefined; if (ts.length(specs) !== 1) return specs; - if (specs[0] === "**/*") + if (specs[0] === ts.defaultIncludeSpec) return undefined; return specs; } @@ -328488,6 +329135,7 @@ var ts; return optionDefinition.type; } } + /* @internal */ function getNameOfCompilerOptionValue(value, customTypeMap) { // There is a typeMap associated with this command-line option so use it to map value back to its name return ts.forEachEntry(customTypeMap, function (mapValue, key) { @@ -328496,6 +329144,7 @@ var ts; } }); } + ts.getNameOfCompilerOptionValue = getNameOfCompilerOptionValue; function serializeCompilerOptions(options, pathOptions) { return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions); } @@ -328733,6 +329382,8 @@ var ts; // until consistent casing errors are reported return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } + /*@internal*/ + ts.defaultIncludeSpec = "**/*"; /** * Parse the contents of a config file from json or json source file (tsconfig.json). * @param json The contents of the config file to parse @@ -328798,6 +329449,7 @@ var ts; } var includeSpecs = toPropValue(getSpecsFromRaw("include")); var excludeOfRaw = getSpecsFromRaw("exclude"); + var isDefaultIncludeSpec = false; var excludeSpecs = toPropValue(excludeOfRaw); if (excludeOfRaw === "no-prop" && raw.compilerOptions) { var outDir = raw.compilerOptions.outDir; @@ -328807,7 +329459,8 @@ var ts; } } if (filesSpecs === undefined && includeSpecs === undefined) { - includeSpecs = ["**/*"]; + includeSpecs = [ts.defaultIncludeSpec]; + isDefaultIncludeSpec = true; } var validatedIncludeSpecs, validatedExcludeSpecs; // The exclude spec list is converted into a regular expression, which allows us to quickly @@ -328826,7 +329479,8 @@ var ts; validatedFilesSpec: ts.filter(filesSpecs, ts.isString), validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, - pathPatterns: undefined, // Initialized on first use + pathPatterns: undefined, + isDefaultIncludeSpec: isDefaultIncludeSpec, }; } function getFileNames(basePath) { @@ -329615,7 +330269,7 @@ var ts; function withPackageId(packageInfo, r) { var packageId; if (r && packageInfo) { - var packageJsonContent = packageInfo.packageJsonContent; + var packageJsonContent = packageInfo.contents.packageJsonContent; if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") { packageId = { name: packageJsonContent.name, @@ -329656,16 +330310,18 @@ var ts; ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, diagnostics, resultFromCache) { - var _a; + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, resultFromCache) { + var _a, _b; if (resultFromCache) { (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = resultFromCache.affectingLocations).push.apply(_b, affectingLocations); return resultFromCache; } return { resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations, - resolutionDiagnostics: diagnostics + affectingLocations: affectingLocations, + resolutionDiagnostics: diagnostics, }; } function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { @@ -329854,6 +330510,7 @@ var ts; } } var failedLookupLocations = []; + var affectingLocations = []; var features = getDefaultNodeResolutionFeatures(options); // Unlike `import` statements, whose mode-calculating APIs are all guaranteed to return `undefined` if we're in an un-mode-ed module resolution // setting, type references will return their target mode regardless of options because of how the parser works, so we guard against the mode being @@ -329872,6 +330529,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -329888,15 +330546,17 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); + var pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host); resolvedTypeReferenceDirective = { primary: primary, - resolvedFileName: resolvedFileName, - originalPath: arePathsEqual(fileName, resolvedFileName, host) ? undefined : fileName, + // If the fileName and realpath are differing only in casing prefer fileName so that we can issue correct errors for casing under forceConsistentCasingInFileNames + resolvedFileName: pathsAreEqual ? fileName : resolvedFileName, + originalPath: pathsAreEqual ? undefined : fileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName), }; } - result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, resolutionDiagnostics: diagnostics }; + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, affectingLocations: affectingLocations, resolutionDiagnostics: diagnostics }; perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, /*mode*/ resolutionMode, result); if (traceEnabled) traceResult(result); @@ -329971,17 +330631,7 @@ var ts; * Does not try `@types/${packageName}` - use a second pass if needed. */ function resolvePackageNameToPackageJson(packageName, containingDirectory, options, host, cache) { - var moduleResolutionState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ts.emptyArray, - features: NodeResolutionFeatures.None, - requestContainingDirectory: containingDirectory, - reportDiagnostic: ts.noop - }; + var moduleResolutionState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); return ts.forEachAncestorDirectory(containingDirectory, function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { var nodeModulesFolder = ts.combinePaths(ancestorDirectory, "node_modules"); @@ -330078,7 +330728,7 @@ var ts; ts.createCacheWithRedirects = createCacheWithRedirects; function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { var cache; - return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries }; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries, getInternalMap: getInternalMap }; function getPackageJsonInfo(packageJsonPath) { return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); } @@ -330092,6 +330742,9 @@ var ts; var iter = cache === null || cache === void 0 ? void 0 : cache.entries(); return iter ? ts.arrayFrom(iter) : []; } + function getInternalMap() { + return cache; + } } function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); @@ -330195,15 +330848,18 @@ var ts; } ts.zipToModeAwareCache = zipToModeAwareCache; function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options)); var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; }, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); - moduleNameToDirectoryMap.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + } function update(options) { updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); } @@ -330279,13 +330935,16 @@ var ts; } ts.createModuleResolutionCache = createModuleResolutionCache; function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { clear: clear, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + } } ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) { @@ -330630,6 +331289,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; // conditions are only used by the node16/nodenext resolver - there's no priority order in the list, //it's essentially a set (priority is determined by object insertion order in the object we look at). var conditions = features & NodeResolutionFeatures.EsmMode ? ["node", "import", "types"] : ["node", "require", "types"]; @@ -330642,6 +331302,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -330649,7 +331310,7 @@ var ts; reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); - return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); @@ -330675,8 +331336,10 @@ var ts; var resolvedValue = resolved_1.value; if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { var path = realPath(resolvedValue.path, host, traceEnabled); - var originalPath = arePathsEqual(path, resolvedValue.path, host) ? undefined : resolvedValue.path; - resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath }); + var pathsAreEqual = arePathsEqual(path, resolvedValue.path, host); + var originalPath = pathsAreEqual ? undefined : resolvedValue.path; + // If the path and realpath are differing only in casing prefer path so that we can issue correct errors for casing under forceConsistentCasingInFileNames + resolvedValue = __assign(__assign({}, resolvedValue), { path: pathsAreEqual ? resolvedValue.path : path, originalPath: originalPath }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; @@ -330925,39 +331588,31 @@ var ts; function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined; - var packageJsonContent = packageInfo && packageInfo.packageJsonContent; - var versionPaths = packageInfo && packageInfo.versionPaths; + var packageJsonContent = packageInfo && packageInfo.contents.packageJsonContent; + var versionPaths = packageInfo && packageInfo.contents.versionPaths; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } /* @internal */ function getEntrypointsFromPackageJsonInfo(packageJsonInfo, options, host, cache, resolveJs) { - if (!resolveJs && packageJsonInfo.resolvedEntrypoints !== undefined) { + if (!resolveJs && packageJsonInfo.contents.resolvedEntrypoints !== undefined) { // Cached value excludes resolutions to JS files - those could be // cached separately, but they're used rarely. - return packageJsonInfo.resolvedEntrypoints; + return packageJsonInfo.contents.resolvedEntrypoints; } var entrypoints; var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript; var features = getDefaultNodeResolutionFeatures(options); - var requireState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ["node", "require", "types"], - features: features, - requestContainingDirectory: packageJsonInfo.packageDirectory, - reportDiagnostic: ts.noop - }; + var requireState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); + requireState.conditions = ["node", "require", "types"]; + requireState.requestContainingDirectory = packageJsonInfo.packageDirectory; var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory, - /*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths); + /*onlyRecordFailures*/ false, requireState, packageJsonInfo.contents.packageJsonContent, packageJsonInfo.contents.versionPaths); entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path); - if (features & NodeResolutionFeatures.Exports && packageJsonInfo.packageJsonContent.exports) { + if (features & NodeResolutionFeatures.Exports && packageJsonInfo.contents.packageJsonContent.exports) { for (var _i = 0, _a = [["node", "import", "types"], ["node", "require", "types"]]; _i < _a.length; _i++) { var conditions = _a[_i]; var exportState = __assign(__assign({}, requireState), { failedLookupLocations: [], conditions: conditions }); - var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.packageJsonContent.exports, exportState, extensions); + var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, exportState, extensions); if (exportResolutions) { for (var _b = 0, exportResolutions_1 = exportResolutions; _b < exportResolutions_1.length; _b++) { var resolution = exportResolutions_1[_b]; @@ -330966,7 +331621,7 @@ var ts; } } } - return packageJsonInfo.resolvedEntrypoints = entrypoints || false; + return packageJsonInfo.contents.resolvedEntrypoints = entrypoints || false; } ts.getEntrypointsFromPackageJsonInfo = getEntrypointsFromPackageJsonInfo; function loadEntrypointsFromExportMap(scope, exports, state, extensions) { @@ -331022,22 +331677,27 @@ var ts; } } } - /** - * A function for locating the package.json scope for a given path - */ /*@internal*/ - function getPackageScopeForPath(fileName, packageJsonInfoCache, host, options) { - var state = { + function getTemporaryModuleResolutionState(packageJsonInfoCache, host, options) { + return { host: host, compilerOptions: options, traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], + failedLookupLocations: ts.noopPush, + affectingLocations: ts.noopPush, packageJsonInfoCache: packageJsonInfoCache, - features: 0, - conditions: [], + features: NodeResolutionFeatures.None, + conditions: ts.emptyArray, requestContainingDirectory: undefined, reportDiagnostic: ts.noop }; + } + ts.getTemporaryModuleResolutionState = getTemporaryModuleResolutionState; + /** + * A function for locating the package.json scope for a given path + */ + /*@internal*/ + function getPackageScopeForPath(fileName, state) { var parts = ts.getPathComponents(fileName); parts.pop(); while (parts.length > 0) { @@ -331064,7 +331724,10 @@ var ts; if (typeof existing !== "boolean") { if (traceEnabled) trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); - return existing; + state.affectingLocations.push(packageJsonPath); + return existing.packageDirectory === packageDirectory ? + existing : + { packageDirectory: packageDirectory, contents: existing.contents }; } else { if (existing && traceEnabled) @@ -331080,8 +331743,9 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined }; + var result = { packageDirectory: packageDirectory, contents: { packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined } }; (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + state.affectingLocations.push(packageJsonPath); return result; } else { @@ -331204,17 +331868,16 @@ var ts; } function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) { var _a, _b; - var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; - var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); - if (!scope || !scope.packageJsonContent.exports) { + var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a)); + var scope = getPackageScopeForPath(directoryPath, state); + if (!scope || !scope.contents.packageJsonContent.exports) { return undefined; } - if (typeof scope.packageJsonContent.name !== "string") { + if (typeof scope.contents.packageJsonContent.name !== "string") { return undefined; } var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry - var nameParts = ts.getPathComponents(scope.packageJsonContent.name); + var nameParts = ts.getPathComponents(scope.contents.packageJsonContent.name); if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) { return undefined; } @@ -331222,30 +331885,30 @@ var ts; return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : ".".concat(ts.directorySeparator).concat(trailingParts.join(ts.directorySeparator)), state, cache, redirectedReference); } function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) { - if (!scope.packageJsonContent.exports) { + if (!scope.contents.packageJsonContent.exports) { return undefined; } if (subpath === ".") { var mainExport = void 0; - if (typeof scope.packageJsonContent.exports === "string" || Array.isArray(scope.packageJsonContent.exports) || (typeof scope.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.packageJsonContent.exports))) { - mainExport = scope.packageJsonContent.exports; + if (typeof scope.contents.packageJsonContent.exports === "string" || Array.isArray(scope.contents.packageJsonContent.exports) || (typeof scope.contents.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.contents.packageJsonContent.exports))) { + mainExport = scope.contents.packageJsonContent.exports; } - else if (ts.hasProperty(scope.packageJsonContent.exports, ".")) { - mainExport = scope.packageJsonContent.exports["."]; + else if (ts.hasProperty(scope.contents.packageJsonContent.exports, ".")) { + mainExport = scope.contents.packageJsonContent.exports["."]; } if (mainExport) { var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false); return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false); } } - else if (allKeysStartWithDot(scope.packageJsonContent.exports)) { - if (typeof scope.packageJsonContent.exports !== "object") { + else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) { + if (typeof scope.contents.packageJsonContent.exports !== "object") { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory); } return toSearchResult(/*value*/ undefined); } - var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.packageJsonContent.exports, scope, /*isImports*/ false); + var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.contents.packageJsonContent.exports, scope, /*isImports*/ false); if (result) { return result; } @@ -331263,22 +331926,21 @@ var ts; } return toSearchResult(/*value*/ undefined); } - var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; - var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); + var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a)); + var scope = getPackageScopeForPath(directoryPath, state); if (!scope) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath); } return toSearchResult(/*value*/ undefined); } - if (!scope.packageJsonContent.imports) { + if (!scope.contents.packageJsonContent.imports) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory); } return toSearchResult(/*value*/ undefined); } - var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.packageJsonContent.imports, scope, /*isImports*/ true); + var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.contents.packageJsonContent.imports, scope, /*isImports*/ true); if (result) { return result; } @@ -331288,6 +331950,7 @@ var ts; return toSearchResult(/*value*/ undefined); } /** + * @internal * From https://github.com/nodejs/node/blob/8f39f51cbbd3b2de14b9ee896e26421cc5b20121/lib/internal/modules/esm/resolve.js#L722 - * "longest" has some nuance as to what "longest" means in the presence of pattern trailers */ @@ -331310,6 +331973,7 @@ var ts; return 1; return 0; } + ts.comparePatternKeys = comparePatternKeys; function loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) { var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); if (!ts.endsWith(moduleName, ts.directorySeparator) && moduleName.indexOf("*") === -1 && ts.hasProperty(lookupTable, moduleName)) { @@ -331437,7 +332101,7 @@ var ts; var _a, _b; if (path === undefined) return path; - return ts.hostGetCanonicalFileName({ useCaseSensitiveFileNames: useCaseSensitiveFileNames })(ts.getNormalizedAbsolutePath(path, (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a))); + return ts.getNormalizedAbsolutePath(path, (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a)); } function combineDirectoryPath(root, dir) { return ts.ensureTrailingDirectorySeparator(ts.combinePaths(root, dir)); @@ -331457,7 +332121,7 @@ var ts; if ((extensions === Extensions.TypeScript || extensions === Extensions.JavaScript || extensions === Extensions.Json) && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 - && (state.compilerOptions.configFile ? ts.startsWith(toAbsolutePath(state.compilerOptions.configFile.fileName), scope.packageDirectory) : true)) { + && (state.compilerOptions.configFile ? ts.containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames()) : true)) { // So that all means we'll only try these guesses for files outside `node_modules` in a directory where the `package.json` and `tsconfig.json` are siblings. // Even with all that, we still don't know if the root of the output file structure will be (relative to the package file) // `.`, `./src` or any other deeper directory structure. (If project references are used, it's definitely `.` by fiat, so that should be pretty common.) @@ -331513,7 +332177,7 @@ var ts; var candidateDirectories = getOutputDirectoriesForBaseDirectory(commonSourceDirGuess); for (var _e = 0, candidateDirectories_1 = candidateDirectories; _e < candidateDirectories_1.length; _e++) { var candidateDir = candidateDirectories_1[_e]; - if (ts.startsWith(finalPath, candidateDir)) { + if (ts.containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames())) { // The matched export is looking up something in either the out declaration or js dir, now map the written path back into the source dir and source extension var pathFragment = finalPath.slice(candidateDir.length + 1); // +1 to also remove directory seperator var possibleInputBase = ts.combinePaths(commonSourceDirGuess, pathFragment); @@ -331621,7 +332285,7 @@ var ts; if (fromFile) { return noPackageId(fromFile); } - var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths); + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.contents.packageJsonContent, packageInfo.contents.versionPaths); return withPackageId(packageInfo, fromDirectory); } } @@ -331629,14 +332293,14 @@ var ts; var loader = function (extensions, candidate, onlyRecordFailures, state) { var _a; // package exports are higher priority than file/directory lookups (and, if there's exports present, blocks them) - if (packageInfo && packageInfo.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) { + if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) { return (_a = loadModuleFromExports(packageInfo, extensions, ts.combinePaths(".", rest), state, cache, redirectedReference)) === null || _a === void 0 ? void 0 : _a.value; } var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths); + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.contents.packageJsonContent, packageInfo && packageInfo.contents.versionPaths); if (!pathAndExtension && packageInfo // eslint-disable-next-line no-null/no-null - && (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null) + && (packageInfo.contents.packageJsonContent.exports === undefined || packageInfo.contents.packageJsonContent.exports === null) && state.features & NodeResolutionFeatures.EsmMode) { // EsmMode disables index lookup in `loadNodeModuleFromDirectoryWorker` generally, however non-relative package resolutions still assume // a default `index.js` entrypoint if no `main` or `exports` are present @@ -331648,12 +332312,12 @@ var ts; var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state); - if (packageInfo && packageInfo.versionPaths) { + if (packageInfo && packageInfo.contents.versionPaths) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, ts.version, rest); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.contents.versionPaths.version, ts.version, rest); } var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); - var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.contents.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state); if (fromPaths) { return fromPaths.value; } @@ -331745,12 +332409,25 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: cache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: containingDirectory, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, + /*isExternalLibraryImport*/ false, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { @@ -331793,10 +332470,23 @@ var ts; trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } var failedLookupLocations = []; + var affectingLocations = []; var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: undefined, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: packageJsonInfoCache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: undefined, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false, /*cache*/ undefined, /*redirectedReference*/ undefined); - return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved, + /*isExternalLibraryImport*/ true, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -332162,7 +332852,7 @@ var ts; case 164 /* SyntaxKind.Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind, ", expected JSDocFunctionType"); }); + ts.Debug.assert(node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind), ", expected JSDocFunctionType"); }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -333346,8 +334036,6 @@ var ts; // - `BindingElement: BindingPattern Initializer?` // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization // - `BindingElement: BindingPattern Initializer?` - bindEach(node.decorators); - bindEach(node.modifiers); bind(node.dotDotDotToken); bind(node.propertyName); bind(node.initializer); @@ -333688,37 +334376,6 @@ var ts; typeLiteralSymbol.members.set(symbol.escapedName, symbol); } function bindObjectLiteralExpression(node) { - var ElementKind; - (function (ElementKind) { - ElementKind[ElementKind["Property"] = 1] = "Property"; - ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; - })(ElementKind || (ElementKind = {})); - if (inStrictMode && !ts.isAssignmentTarget(node)) { - var seen = new ts.Map(); - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (prop.kind === 298 /* SyntaxKind.SpreadAssignment */ || prop.name.kind !== 79 /* SyntaxKind.Identifier */) { - continue; - } - var identifier = prop.name; - // ECMA-262 11.1.5 Object Initializer - // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true - // a.This production is contained in strict code and IsDataDescriptor(previous) is true and - // IsDataDescriptor(propId.descriptor) is true. - // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. - // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. - // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true - // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 296 /* SyntaxKind.PropertyAssignment */ || prop.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ || prop.kind === 169 /* SyntaxKind.MethodDeclaration */ - ? 1 /* ElementKind.Property */ - : 2 /* ElementKind.Accessor */; - var existingKind = seen.get(identifier.escapedText); - if (!existingKind) { - seen.set(identifier.escapedText, currentKind); - continue; - } - } - } return bindAnonymousDeclaration(node, 4096 /* SymbolFlags.ObjectLiteral */, "__object" /* InternalSymbolName.Object */); } function bindJsxAttributes(node) { @@ -334375,7 +335032,7 @@ var ts; } } function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { + if (ts.some(node.modifiers)) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level @@ -335027,10 +335684,11 @@ var ts; } function isExportsOrModuleExportsOrAlias(sourceFile, node) { var i = 0; - var q = [node]; - while (q.length && i < 100) { + var q = ts.createQueue(); + q.enqueue(node); + while (!q.isEmpty() && i < 100) { i++; - node = q.shift(); + node = q.dequeue(); if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) { return true; } @@ -335038,10 +335696,10 @@ var ts; var symbol = lookupSymbolForName(sourceFile, node.escapedText); if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) { var init = symbol.valueDeclaration.initializer; - q.push(init); + q.enqueue(init); if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) { - q.push(init.left); - q.push(init.right); + q.enqueue(init.left); + q.enqueue(init.right); } } } @@ -335301,7 +335959,10 @@ var ts; TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; - TypeFacts[TypeFacts["All"] = 16777215] = "All"; + TypeFacts[TypeFacts["IsUndefined"] = 16777216] = "IsUndefined"; + TypeFacts[TypeFacts["IsNull"] = 33554432] = "IsNull"; + TypeFacts[TypeFacts["IsUndefinedOrNull"] = 50331648] = "IsUndefinedOrNull"; + TypeFacts[TypeFacts["All"] = 134217727] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. @@ -335343,25 +336004,17 @@ var ts; TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; - TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; - TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; - TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["VoidFacts"] = 9830144] = "VoidFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 26607360] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 42917664] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 83427327] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 83886079] = "EmptyObjectFacts"; + TypeFacts[TypeFacts["UnknownFacts"] = 83886079] = "UnknownFacts"; TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE"; - TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; // Masks TypeFacts[TypeFacts["OrFactsMask"] = 8256] = "OrFactsMask"; - TypeFacts[TypeFacts["AndFactsMask"] = 16768959] = "AndFactsMask"; - })(TypeFacts || (TypeFacts = {})); - var typeofEQFacts = new ts.Map(ts.getEntries({ - string: 1 /* TypeFacts.TypeofEQString */, - number: 2 /* TypeFacts.TypeofEQNumber */, - bigint: 4 /* TypeFacts.TypeofEQBigInt */, - boolean: 8 /* TypeFacts.TypeofEQBoolean */, - symbol: 16 /* TypeFacts.TypeofEQSymbol */, - undefined: 65536 /* TypeFacts.EQUndefined */, - object: 32 /* TypeFacts.TypeofEQObject */, - function: 64 /* TypeFacts.TypeofEQFunction */ - })); + TypeFacts[TypeFacts["AndFactsMask"] = 134209471] = "AndFactsMask"; + })(TypeFacts = ts.TypeFacts || (ts.TypeFacts = {})); var typeofNEFacts = new ts.Map(ts.getEntries({ string: 256 /* TypeFacts.TypeofNEString */, number: 512 /* TypeFacts.TypeofNENumber */, @@ -335396,7 +336049,7 @@ var ts; CheckMode[CheckMode["RestBindingElement"] = 64] = "RestBindingElement"; // e.g. in `const { a, ...rest } = foo`, when checking the type of `foo` to determine the type of `rest`, // we need to preserve generic types instead of substituting them for constraints - })(CheckMode || (CheckMode = {})); + })(CheckMode = ts.CheckMode || (ts.CheckMode = {})); var SignatureCheckMode; (function (SignatureCheckMode) { SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback"; @@ -335404,7 +336057,7 @@ var ts; SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes"; SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity"; SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback"; - })(SignatureCheckMode || (SignatureCheckMode = {})); + })(SignatureCheckMode = ts.SignatureCheckMode || (ts.SignatureCheckMode = {})); var IntersectionState; (function (IntersectionState) { IntersectionState[IntersectionState["None"] = 0] = "None"; @@ -335738,7 +336391,7 @@ var ts; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); - return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + return node ? getContextualTypeForObjectLiteralElement(node, /*contextFlags*/ undefined) : undefined; }, getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -335746,7 +336399,7 @@ var ts; }, getContextualTypeForJsxAttribute: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); - return node && getContextualTypeForJsxAttribute(node); + return node && getContextualTypeForJsxAttribute(node, /*contextFlags*/ undefined); }, isContextSensitive: isContextSensitive, getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, @@ -335860,9 +336513,9 @@ var ts; return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true); }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, - tryGetThisTypeAt: function (nodeIn, includeGlobalThis) { + tryGetThisTypeAt: function (nodeIn, includeGlobalThis, container) { var node = ts.getParseTreeNode(nodeIn); - return node && tryGetThisTypeAt(node, includeGlobalThis); + return node && tryGetThisTypeAt(node, includeGlobalThis, container); }, getTypeArgumentConstraint: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); @@ -335952,6 +336605,7 @@ var ts; var stringMappingTypes = new ts.Map(); var substitutionTypes = new ts.Map(); var subtypeReductionCache = new ts.Map(); + var cachedTypes = new ts.Map(); var evolvingArrayTypes = []; var undefinedProperties = new ts.Map(); var markerTypes = new ts.Set(); @@ -335960,7 +336614,7 @@ var ts; var unresolvedSymbols = new ts.Map(); var errorTypes = new ts.Map(); var anyType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); - var autoType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); + var autoType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 262144 /* ObjectFlags.NonInferrableType */); var wildcardType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); var errorType = createIntrinsicType(1 /* TypeFlags.Any */, "error"); var unresolvedType = createIntrinsicType(1 /* TypeFlags.Any */, "unresolved"); @@ -335993,8 +336647,7 @@ var ts; var esSymbolType = createIntrinsicType(4096 /* TypeFlags.ESSymbol */, "symbol"); var voidType = createIntrinsicType(16384 /* TypeFlags.Void */, "void"); var neverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); - var silentNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* TypeFlags.Never */, "never", 262144 /* ObjectFlags.NonInferrableType */); + var silentNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never", 262144 /* ObjectFlags.NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* TypeFlags.NonPrimitive */, "object"); @@ -336004,16 +336657,30 @@ var ts; var numberOrBigIntType = getUnionType([numberType, bigintType]); var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]); var numericStringType = getTemplateLiteralType(["", ""], [numberType]); // The `${number}` type - var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? getRestrictiveTypeParameter(t) : t; }); - var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? wildcardType : t; }); + var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? getRestrictiveTypeParameter(t) : t; }, function () { return "(restrictive mapper)"; }); + var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? wildcardType : t; }, function () { return "(permissive mapper)"; }); var uniqueLiteralType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); // `uniqueLiteralType` is a special `never` flagged by union reduction to behave as a literal - var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? uniqueLiteralType : t; }); // replace all type parameters with the unique literal type (disregarding constraints) + var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? uniqueLiteralType : t; }, function () { return "(unique literal mapper)"; }); // replace all type parameters with the unique literal type (disregarding constraints) + var outofbandVarianceMarkerHandler; + var reportUnreliableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true); + } + return t; + }, function () { return "(unmeasurable reporter)"; }); + var reportUnmeasurableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false); + } + return t; + }, function () { return "(unreliable reporter)"; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyJsxObjectType.objectFlags |= 2048 /* ObjectFlags.JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* SymbolFlags.TypeLiteral */, "__type" /* InternalSymbolName.Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray)]) : unknownType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyGenericType.instantiations = new ts.Map(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); @@ -336027,6 +336694,9 @@ var ts; var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); + var markerSuperTypeForCheck = createTypeParameter(); + var markerSubTypeForCheck = createTypeParameter(); + markerSubTypeForCheck.constraint = markerSuperTypeForCheck; var noTypePredicate = createTypePredicate(1 /* TypePredicateKind.Identifier */, "<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* SignatureFlags.None */); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* SignatureFlags.None */); @@ -336156,21 +336826,13 @@ var ts; var potentialNewTargetCollisions = []; var potentialWeakMapSetCollisions = []; var potentialReflectCollisions = []; + var potentialUnusedRenamedBindingElementsInTypes = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createDiagnosticCollection(); - var typeofTypesByName = new ts.Map(ts.getEntries({ - string: stringType, - number: numberType, - bigint: bigintType, - boolean: booleanType, - symbol: esSymbolType, - undefined: undefinedType - })); var typeofType = createTypeofType(); var _jsxNamespace; var _jsxFactoryEntity; - var outofbandVarianceMarkerHandler; var subtypeRelation = new ts.Map(); var strictSubtypeRelation = new ts.Map(); var assignableRelation = new ts.Map(); @@ -336196,6 +336858,14 @@ var ts; ]; initializeTypeChecker(); return checker; + function getCachedType(key) { + return key ? cachedTypes.get(key) : undefined; + } + function setCachedType(key, type) { + if (key) + cachedTypes.set(key, type); + return type; + } function getJsxNamespace(location) { if (location) { var file = ts.getSourceFileOfNode(location); @@ -337060,6 +337730,7 @@ var ts; if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & 111551 /* SymbolFlags.Value */)) { // Remember the property node, it will be used later to report appropriate error + ts.Debug.assertNode(location, ts.isPropertyDeclaration); propertyWithInvalidInitializer = location; } } @@ -337249,11 +337920,27 @@ var ts; } } } + // The invalid initializer error is needed in two situation: + // 1. When result is undefined, after checking for a missing "this." + // 2. When result is defined + function checkAndReportErrorForInvalidInitializer() { + if (propertyWithInvalidInitializer && !(useDefineForClassFields && ts.getEmitScriptTarget(compilerOptions) >= 9 /* ScriptTarget.ES2022 */)) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed + // with ESNext+useDefineForClassFields because the scope semantics are different. + error(errorLocation, errorLocation && propertyWithInvalidInitializer.type && ts.textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) + ? ts.Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor + : ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyWithInvalidInitializer.name), diagnosticName(nameArg)); + return true; + } + return false; + } if (!result) { if (nameNotFoundMessage) { addLazyDiagnostic(function () { if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + !checkAndReportErrorForInvalidInitializer() && !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && @@ -337261,7 +337948,16 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { + var suggestedLib = void 0; + // Report missing lib first + if (nameArg) { + suggestedLib = getSuggestedLibForNonExistentName(nameArg); + if (suggestedLib) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), suggestedLib); + } + } + // then spelling suggestions + if (!suggestedLib && getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -337280,16 +337976,9 @@ var ts; } } } - if (!suggestion) { - if (nameArg) { - var lib = getSuggestedLibForNonExistentName(nameArg); - if (lib) { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib); - } - else { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); - } - } + // And then fall back to unspecified "not found" + if (!suggestion && !suggestedLib && nameArg) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); } suggestionCount++; } @@ -337297,12 +337986,7 @@ var ts; } return undefined; } - if (propertyWithInvalidInitializer && !(ts.getEmitScriptTarget(compilerOptions) === 99 /* ScriptTarget.ESNext */ && useDefineForClassFields)) { - // We have a match, but the reference occurred within a property initializer and the identifier also binds - // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed - // with ESNext+useDefineForClassFields because the scope semantics are different. - var propertyName = propertyWithInvalidInitializer.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + else if (checkAndReportErrorForInvalidInitializer()) { return undefined; } // Perform extra checks only if error reporting was requested @@ -337404,7 +338088,7 @@ var ts; if (decl.kind === 163 /* SyntaxKind.TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); } } } @@ -337513,7 +338197,12 @@ var ts; function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */)) { if (isPrimitiveTypeName(name)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + if (isExtendedByInterface(errorLocation)) { + error(errorLocation, ts.Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes, ts.unescapeLeadingUnderscores(name)); + } + else { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + } return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); @@ -337533,6 +338222,16 @@ var ts; } return false; } + function isExtendedByInterface(node) { + var grandparent = node.parent.parent; + var parentOfGrandparent = grandparent.parent; + if (grandparent && parentOfGrandparent) { + var isExtending = ts.isHeritageClause(grandparent) && grandparent.token === 94 /* SyntaxKind.ExtendsKeyword */; + var isInterface = ts.isInterfaceDeclaration(parentOfGrandparent); + return isExtending && isInterface; + } + return false; + } function maybeMappedType(node, symbol) { var container = ts.findAncestor(node.parent, function (n) { return ts.isComputedPropertyName(n) || ts.isPropertySignature(n) ? false : ts.isTypeLiteralNode(n) || "quit"; @@ -337761,41 +338460,61 @@ var ts; return typeof file.externalModuleIndicator !== "object" && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { - var _a; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = void 0; - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - exportDefaultSymbol = moduleSymbol; - } - else { - exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* InternalSymbolName.Default */, node, dontResolveAlias); - } - var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); - var hasDefaultOnly = isOnlyImportedAsDefault(node.parent.moduleSpecifier); - var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, node.parent.moduleSpecifier); - if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) { - if (hasExportAssignmentSymbol(moduleSymbol)) { - var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; - var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* InternalSymbolName.ExportEquals */); - var exportAssignment = exportEqualsSymbol.valueDeclaration; - var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); - if (exportAssignment) { - ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); - } - } - else { - reportNonDefaultExport(moduleSymbol, node); + return getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias); + } + } + function getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias) { + var _a; + var exportDefaultSymbol; + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + exportDefaultSymbol = moduleSymbol; + } + else { + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* InternalSymbolName.Default */, node, dontResolveAlias); + } + var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); + var specifier = getModuleSpecifierForImportOrExport(node); + if (!specifier) { + return exportDefaultSymbol; + } + var hasDefaultOnly = isOnlyImportedAsDefault(specifier); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, specifier); + if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) { + if (hasExportAssignmentSymbol(moduleSymbol)) { + var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; + var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* InternalSymbolName.ExportEquals */); + var exportAssignment = exportEqualsSymbol.valueDeclaration; + var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); + if (exportAssignment) { + ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } } - else if (hasSyntheticDefault || hasDefaultOnly) { - // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present - var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); - markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false); - return resolved; + else if (ts.isImportClause(node)) { + reportNonDefaultExport(moduleSymbol, node); } - markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false); - return exportDefaultSymbol; + else { + errorNoModuleMemberSymbol(moduleSymbol, moduleSymbol, node, ts.isImportOrExportSpecifier(node) && node.propertyName || node.name); + } + } + else if (hasSyntheticDefault || hasDefaultOnly) { + // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present + var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false); + return resolved; + } + markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false); + return exportDefaultSymbol; + } + function getModuleSpecifierForImportOrExport(node) { + switch (node.kind) { + case 267 /* SyntaxKind.ImportClause */: return node.parent.moduleSpecifier; + case 265 /* SyntaxKind.ImportEqualsDeclaration */: return ts.isExternalModuleReference(node.moduleReference) ? node.moduleReference.expression : undefined; + case 268 /* SyntaxKind.NamespaceImport */: return node.parent.parent.moduleSpecifier; + case 270 /* SyntaxKind.ImportSpecifier */: return node.parent.parent.parent.moduleSpecifier; + case 275 /* SyntaxKind.ExportSpecifier */: return node.parent.parent.moduleSpecifier; + default: return ts.Debug.assertNever(node); } } function reportNonDefaultExport(moduleSymbol, node) { @@ -337885,7 +338604,7 @@ var ts; } } function getExternalModuleMember(node, specifier, dontResolveAlias) { - var _a, _b; + var _a; if (dontResolveAlias === void 0) { dontResolveAlias = false; } var moduleSpecifier = ts.getExternalModuleRequireArgument(node) || node.moduleSpecifier; var moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); // TODO: GH#18217 @@ -337921,29 +338640,33 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol, node); - var declarationName = ts.declarationNameToString(name); - var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); - if (suggestion !== undefined) { - var suggestionName = symbolToString(suggestion); - var diagnostic = error(name, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName); - if (suggestion.valueDeclaration) { - ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); - } - } - else { - if ((_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* InternalSymbolName.Default */)) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); - } - else { - reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName); - } - } + errorNoModuleMemberSymbol(moduleSymbol, targetSymbol, node, name); } return symbol; } } } + function errorNoModuleMemberSymbol(moduleSymbol, targetSymbol, node, name) { + var _a; + var moduleName = getFullyQualifiedName(moduleSymbol, node); + var declarationName = ts.declarationNameToString(name); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); + if (suggestion !== undefined) { + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } + } + else { + if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* InternalSymbolName.Default */)) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); + } + else { + reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName); + } + } + } function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { var _a, _b; var localSymbol = (_b = (_a = moduleSymbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.locals) === null || _b === void 0 ? void 0 : _b.get(name.escapedText); @@ -337989,6 +338712,13 @@ var ts; } } function getTargetOfImportSpecifier(node, dontResolveAlias) { + if (ts.isImportSpecifier(node) && ts.idText(node.propertyName || node.name) === "default" /* InternalSymbolName.Default */) { + var specifier = getModuleSpecifierForImportOrExport(node); + var moduleSymbol = specifier && resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + return getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias); + } + } var root = ts.isBindingElement(node) ? ts.getRootDeclaration(node) : node.parent.parent.parent; var commonJSPropertyAccess = getCommonJSPropertyAccess(root); var resolved = getExternalModuleMember(root, commonJSPropertyAccess || node, dontResolveAlias); @@ -338010,6 +338740,13 @@ var ts; return resolved; } function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { + if (ts.idText(node.propertyName || node.name) === "default" /* InternalSymbolName.Default */) { + var specifier = getModuleSpecifierForImportOrExport(node); + var moduleSymbol = specifier && resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + return getTargetofModuleDefault(moduleSymbol, node, !!dontResolveAlias); + } + } var resolved = node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); @@ -338036,10 +338773,6 @@ var ts; checkExpressionCached(expression); return getNodeLinks(expression).resolvedSymbol; } - function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) { - var expression = node.initializer; - return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve); - } function getTargetOfAccessExpression(node, dontRecursivelyResolve) { if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */)) { return undefined; @@ -338071,7 +338804,7 @@ var ts; case 297 /* SyntaxKind.ShorthandPropertyAssignment */: return resolveEntityName(node.name, 111551 /* SymbolFlags.Value */ | 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve); case 296 /* SyntaxKind.PropertyAssignment */: - return getTargetOfPropertyAssignment(node, dontRecursivelyResolve); + return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve); case 207 /* SyntaxKind.ElementAccessExpression */: case 206 /* SyntaxKind.PropertyAccessExpression */: return getTargetOfAccessExpression(node, dontRecursivelyResolve); @@ -338476,7 +339209,40 @@ var ts; // An override clause will take effect for type-only imports and import types, and allows importing the types across formats, regardless of // normal mode restrictions if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext && !ts.getResolutionModeOverrideForClause(overrideClause)) { - error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference); + if (ts.findAncestor(location, ts.isImportEqualsDeclaration)) { + // ImportEquals in a ESM file resolving to another ESM file + error(errorNode, ts.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 { + // CJS file resolving to an ESM file + var diagnosticDetails = void 0; + var ext = ts.tryGetExtensionFromPath(currentSourceFile.fileName); + if (ext === ".ts" /* Extension.Ts */ || ext === ".js" /* Extension.Js */ || ext === ".tsx" /* Extension.Tsx */ || ext === ".jsx" /* Extension.Jsx */) { + var scope = currentSourceFile.packageJsonScope; + var targetExt = ext === ".ts" /* Extension.Ts */ ? ".mts" /* Extension.Mts */ : ext === ".js" /* Extension.Js */ ? ".mjs" /* Extension.Mjs */ : undefined; + if (scope && !scope.contents.packageJsonContent.type) { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json")); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0, ts.combinePaths(scope.packageDirectory, "package.json")); + } + } + else { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module, targetExt); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module); + } + } + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(diagnosticDetails, ts.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))); + } } } // merged symbol is module declaration symbol combined with all augmentations @@ -338985,8 +339751,9 @@ var ts; function getExportSymbolOfValueSymbolIfExported(symbol) { return getMergedSymbol(symbol && (symbol.flags & 1048576 /* SymbolFlags.ExportValue */) !== 0 && symbol.exportSymbol || symbol); } - function symbolIsValue(symbol) { - return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && !getTypeOnlyAliasDeclaration(symbol)); + function symbolIsValue(symbol, includeTypeOnlyMembers) { + return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || + symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; @@ -339026,7 +339793,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getStringLiteralType)); + return getUnionType(ts.arrayFrom(typeofNEFacts.keys(), getStringLiteralType)); } function createTypeParameter(symbol) { var type = createType(262144 /* TypeFlags.TypeParameter */); @@ -339435,13 +340202,25 @@ var ts; && isDeclarationVisible(declaration.parent)) { return addVisibleAlias(declaration, declaration); } - else if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isBindingElement(declaration) && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement - && ts.isVariableDeclaration(declaration.parent.parent) - && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) - && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* ModifierFlags.Export */) - && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file) - && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { - return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + else if (ts.isBindingElement(declaration)) { + if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement + && ts.isVariableDeclaration(declaration.parent.parent) + && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) + && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* ModifierFlags.Export */) + && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file) + && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + } + else if (symbol.flags & 2 /* SymbolFlags.BlockScopedVariable */) { + var variableStatement = ts.findAncestor(declaration, ts.isVariableStatement); + if (ts.hasSyntacticModifier(variableStatement, 1 /* ModifierFlags.Export */)) { + return true; + } + if (!isDeclarationVisible(variableStatement.parent)) { + return false; + } + return addVisibleAlias(declaration, variableStatement); + } } // Declaration is not visible return false; @@ -339483,6 +340262,9 @@ var ts; if (symbol && symbol.flags & 262144 /* SymbolFlags.TypeParameter */ && meaning & 788968 /* SymbolFlags.Type */) { return { accessibility: 0 /* SymbolAccessibility.Accessible */ }; } + if (!symbol && ts.isThisIdentifier(firstIdentifier) && isSymbolAccessible(getSymbolOfNode(ts.getThisContainer(firstIdentifier, /*includeArrowFunctions*/ false)), firstIdentifier, meaning, /*computeAliases*/ false).accessibility === 0 /* SymbolAccessibility.Accessible */) { + return { accessibility: 0 /* SymbolAccessibility.Accessible */ }; + } // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: 1 /* SymbolAccessibility.NotAccessible */, @@ -339571,7 +340353,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* TypeFormatFlags.None */; } - return flags & 814775659 /* TypeFormatFlags.NodeBuilderFlagsMask */; + return flags & 848330091 /* TypeFormatFlags.NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { return !!type.symbol && !!(type.symbol.flags & 32 /* SymbolFlags.Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* TypeFlags.Object */) && !!(ts.getObjectFlags(type) & 16777216 /* ObjectFlags.IsClassInstanceClone */))); @@ -339673,6 +340455,12 @@ var ts; return context.truncating = context.approximateLength > ((context.flags & 1 /* NodeBuilderFlags.NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength); } function typeToTypeNodeHelper(type, context) { + var savedFlags = context.flags; + var typeNode = typeToTypeNodeWorker(type, context); + context.flags = savedFlags; + return typeNode; + } + function typeToTypeNodeWorker(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); } @@ -339812,6 +340600,9 @@ var ts; var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* SymbolFlags.Class */)) return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""), typeArgumentNodes); + if (ts.length(typeArgumentNodes) === 1 && type.aliasSymbol === globalArrayType.symbol) { + return ts.factory.createArrayTypeNode(typeArgumentNodes[0]); + } return symbolToTypeNode(type.aliasSymbol, context, 788968 /* SymbolFlags.Type */, typeArgumentNodes); } var objectFlags = ts.getObjectFlags(type); @@ -339848,8 +340639,8 @@ var ts; if (type.symbol) { return symbolToTypeNode(type.symbol, context, 788968 /* SymbolFlags.Type */); } - var name = (type === markerSuperType || type === markerSubType) && varianceTypeParameter && varianceTypeParameter.symbol ? - (type === markerSubType ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; + var name = (type === markerSuperTypeForCheck || type === markerSubTypeForCheck) && varianceTypeParameter && varianceTypeParameter.symbol ? + (type === markerSubTypeForCheck ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(name), /*typeArguments*/ undefined); } if (type.flags & 1048576 /* TypeFlags.Union */ && type.origin) { @@ -339915,7 +340706,7 @@ var ts; var name = typeParameterToName(newParam, context); var newTypeVariable = ts.factory.createTypeReferenceNode(name); context.approximateLength += 37; // 15 each for two added conditionals, 7 for an added infer type - var newMapper = prependTypeMapping(type.root.checkType, newParam, type.combinedMapper || type.mapper); + var newMapper = prependTypeMapping(type.root.checkType, newParam, type.mapper); var saveInferTypeParameters_1 = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode_1 = typeToTypeNodeHelper(instantiateType(type.root.extendsType, newMapper), context); @@ -339956,6 +340747,10 @@ var ts; } return typeToTypeNodeHelper(type, context); } + function isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) { + return isMappedTypeWithKeyofConstraintDeclaration(type) + && !(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */); + } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 524288 /* TypeFlags.Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.factory.createToken(type.declaration.readonlyToken.kind) : undefined; @@ -339965,7 +340760,7 @@ var ts; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` - if (!(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { var newParam = createTypeParameter(createSymbol(262144 /* SymbolFlags.TypeParameter */, "T")); var name = typeParameterToName(newParam, context); newTypeVariable = ts.factory.createTypeReferenceNode(name); @@ -339981,11 +340776,12 @@ var ts; var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, /*members*/ undefined); context.approximateLength += 10; var result = ts.setEmitFlags(mappedTypeNode, 1 /* EmitFlags.SingleLine */); - if (isMappedTypeWithKeyofConstraintDeclaration(type) && !(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { // homomorphic mapped type with a non-homomorphic naive inlining // wrap it with a conditional like `SomeModifiersType extends infer U ? {..the mapped type...} : never` to ensure the resulting // type stays homomorphic - return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName))), result, ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); + var originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode(type.declaration.typeParameter.constraint.type)) || unknownType, type.mapper); + return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName), originalConstraint.flags & 2 /* TypeFlags.Unknown */ ? undefined : typeToTypeNodeHelper(originalConstraint, context))), result, ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); } return result; } @@ -340002,7 +340798,7 @@ var ts; // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* SymbolFlags.Class */ && !getBaseTypeVariableOfClass(symbol) - && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 226 /* SyntaxKind.ClassExpression */ && context.flags & 2048 /* NodeBuilderFlags.WriteClassExpressionAsTypeLiteral */) || + && !(symbol.valueDeclaration && ts.isClassLike(symbol.valueDeclaration) && context.flags & 2048 /* NodeBuilderFlags.WriteClassExpressionAsTypeLiteral */ && (!ts.isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(symbol, context.enclosingDeclaration, isInstanceType, /*computeAliases*/ false).accessibility !== 0 /* SymbolAccessibility.Accessible */)) || symbol.flags & (384 /* SymbolFlags.Enum */ | 512 /* SymbolFlags.ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -340268,7 +341064,7 @@ var ts; var id = ids_1[_i]; qualifier = qualifier ? ts.factory.createQualifiedName(qualifier, id) : id; } - return ts.factory.updateImportTypeNode(root, root.argument, qualifier, typeArguments, root.isTypeOf); + return ts.factory.updateImportTypeNode(root, root.argument, root.assertions, qualifier, typeArguments, root.isTypeOf); } else { // first shift type arguments @@ -340372,7 +341168,7 @@ var ts; anyType : getNonMissingTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* CheckFlags.Late */ && isLateBoundName(propertySymbol.escapedName)) { + if (context.tracker.trackSymbol && isLateBoundName(propertySymbol.escapedName)) { if (propertySymbol.declarations) { var decl = ts.first(propertySymbol.declarations); if (hasLateBindableName(decl)) { @@ -340517,7 +341313,6 @@ var ts; var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = typeToTypeNodeHelper(indexInfo.keyType, context); var indexingParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, @@ -340529,8 +341324,7 @@ var ts; context.encounteredError = true; } context.approximateLength += (name.length + 4); - return ts.factory.createIndexSignature( - /*decorators*/ undefined, indexInfo.isReadonly ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + return ts.factory.createIndexSignature(indexInfo.isReadonly ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { var _a, _b, _c, _d; @@ -340549,7 +341343,7 @@ var ts; var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* CheckFlags.RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 171 /* SyntaxKind.Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); - var thisParameter = tryGetThisParameterDeclaration(signature, context); + var thisParameter = context.flags & 33554432 /* NodeBuilderFlags.OmitThisParameter */ ? undefined : tryGetThisParameterDeclaration(signature, context); if (thisParameter) { parameters.unshift(thisParameter); } @@ -340582,15 +341376,15 @@ var ts; var node = kind === 174 /* SyntaxKind.CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 175 /* SyntaxKind.ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 168 /* SyntaxKind.MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 169 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 171 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : - kind === 172 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : - kind === 173 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : - kind === 176 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : + kind === 169 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 171 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(modifiers, parameters, /*body*/ undefined) : + kind === 172 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : + kind === 173 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : + kind === 176 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 317 /* SyntaxKind.JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 179 /* SyntaxKind.FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : kind === 180 /* SyntaxKind.ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 256 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 256 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : kind === 213 /* SyntaxKind.FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : kind === 214 /* SyntaxKind.ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); @@ -340607,7 +341401,6 @@ var ts; var thisTag = ts.getJSDocThisTag(signature.declaration); if (thisTag && thisTag.typeExpression) { return ts.factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "this", /* questionToken */ undefined, typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context)); @@ -340639,7 +341432,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); - var modifiers = !(context.flags & 8192 /* NodeBuilderFlags.OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.factory.cloneNode) : undefined; + var modifiers = !(context.flags & 8192 /* NodeBuilderFlags.OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && ts.canHaveModifiers(parameterDeclaration) ? ts.map(ts.getModifiers(parameterDeclaration), ts.factory.cloneNode) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* CheckFlags.RestParameter */; var dotDotDotToken = isRest ? ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -340650,8 +341443,7 @@ var ts; ts.symbolName(parameterSymbol); var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* CheckFlags.OptionalParameter */; var questionToken = isOptional ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined; - var parameterNode = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + var parameterNode = ts.factory.createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; @@ -341313,9 +342105,7 @@ var ts; } if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature( - /*decorators*/ undefined, /*modifiers*/ undefined, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdotToken*/ undefined, "x", /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); @@ -341323,14 +342113,13 @@ var ts; if (ts.isJSDocFunctionType(node)) { if (ts.isJSDocConstructSignature(node)) { var newTypeNode_1; - return ts.factory.createConstructorTypeNode(node.modifiers, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + return ts.factory.createConstructorTypeNode( + /*modifiers*/ undefined, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration( /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); } else { return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); } @@ -341349,7 +342138,7 @@ var ts; !(ts.length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) { return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); } - return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.assertions, node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { var _a = trackExistingEntityName(node, context, includePrivateSymbol), introducesError = _a.introducesError, result = _a.node; @@ -341401,7 +342190,7 @@ var ts; } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 169 /* SyntaxKind.MethodDeclaration */, /*useAcessors*/ true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of // declaration mapping // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration @@ -341462,8 +342251,7 @@ var ts; var name_3 = ns.name; var body = ns.body; if (ts.length(excessExports)) { - ns = ts.factory.updateModuleDeclaration(ns, ns.decorators, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration( - /*decorators*/ undefined, + ns = ts.factory.updateModuleDeclaration(ns, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration( /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, /*alias*/ undefined, id); })), /*moduleSpecifier*/ undefined)], false)))); @@ -341489,7 +342277,6 @@ var ts; if (ts.length(exports) > 1) { var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; }); statements = __spreadArray(__spreadArray([], nonExports, true), [ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), /*moduleSpecifier*/ undefined)], false); @@ -341504,7 +342291,6 @@ var ts; // remove group members from statements and then merge group members and add back to statements statements = __spreadArray(__spreadArray([], ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), true), [ ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier) ], false); @@ -341544,7 +342330,7 @@ var ts; } else { // some items filtered, others not - update the export declaration - statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); + statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); } } return statements; @@ -341609,12 +342395,11 @@ var ts; if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) { var oldContext = context; context = cloneNodeBuilderContext(context); - var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); + serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); if (context.reportedDiagnostic) { oldcontext.reportedDiagnostic = context.reportedDiagnostic; // hoist diagnostic result into outer context } context = oldContext; - return result; } } // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias @@ -341695,7 +342480,6 @@ var ts; && ((_d = type.symbol) === null || _d === void 0 ? void 0 : _d.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) { var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, alias, localName)])), 0 /* ModifierFlags.None */); context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* SymbolFlags.Value */); @@ -341728,7 +342512,6 @@ var ts; // ``` // To create an export named `g` that does _not_ shadow the local `g` addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name, localName)])), 0 /* ModifierFlags.None */); needsExportDeclaration = false; @@ -341777,16 +342560,15 @@ var ts; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); if (!resolvedModule) continue; - addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* ModifierFlags.None */); + addResult(ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* ModifierFlags.None */); } } } if (needsPostExportDefault) { - addResult(ts.factory.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* ModifierFlags.None */); + addResult(ts.factory.createExportAssignment(/*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* ModifierFlags.None */); } else if (needsExportDeclaration) { addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, getInternalSymbolName(symbol, symbolName), symbolName)])), 0 /* ModifierFlags.None */); } @@ -341854,7 +342636,7 @@ var ts; && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); - addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* SyntaxKind.MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); + addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* SyntaxKind.MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; context.enclosingDeclaration = oldEnclosingDecl; } @@ -341870,7 +342652,6 @@ var ts; var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(94 /* SyntaxKind.ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* SymbolFlags.Value */); }))]; addResult(ts.factory.createInterfaceDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), constructSignatures, true), callSignatures, true), members, true)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { @@ -341896,7 +342677,6 @@ var ts; var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); var nsBody = ts.factory.createModuleBlock([ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* InternalSymbolName.ExportEquals */; }), function (s) { var _a, _b; @@ -341913,13 +342693,11 @@ var ts; return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name === targetName ? undefined : targetName, name); })))]); addResult(ts.factory.createModuleDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), nsBody, 16 /* NodeFlags.Namespace */), 0 /* ModifierFlags.None */); } } function serializeEnum(symbol, symbolName, modifierFlags) { - addResult(ts.factory.createEnumDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* ModifierFlags.Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* SymbolFlags.EnumMember */); }), function (p) { + addResult(ts.factory.createEnumDeclaration(ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* ModifierFlags.Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* SymbolFlags.EnumMember */); }), function (p) { // TODO: Handle computed names // I hate that to get the initialized value we need to walk back to the declarations here; but there's no // other way to get the possible const value of an enum member that I'm aware of, as the value is cached @@ -341980,7 +342758,7 @@ var ts; // emit akin to the above would be needed. // Add a namespace // Create namespace as non-synthetic so it is usable as an enclosing declaration - var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); + var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); ts.setParent(fakespace, enclosingDeclaration); fakespace.locals = ts.createSymbolTable(props); fakespace.symbol = props[0].parent; @@ -341999,11 +342777,10 @@ var ts; results = oldResults; // replace namespace with synthetic version var defaultReplaced = ts.map(declarations, function (d) { return ts.isExportAssignment(d) && !d.isExportEquals && ts.isIdentifier(d.expression) ? ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, d.expression, ts.factory.createIdentifier("default" /* InternalSymbolName.Default */))])) : d; }); var exportModifierStripped = ts.every(defaultReplaced, function (d) { return ts.hasSyntacticModifier(d, 1 /* ModifierFlags.Export */); }) ? ts.map(defaultReplaced, removeExportModifier) : defaultReplaced; - fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.decorators, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); + fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); addResult(fakespace, modifierFlags); // namespaces can never be default exported } } @@ -342059,7 +342836,7 @@ var ts; ? getBaseConstructorTypeOfClass(staticType) : anyType; var heritageClauses = __spreadArray(__spreadArray([], !ts.length(baseTypes) ? [] : [ts.factory.createHeritageClause(94 /* SyntaxKind.ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], true), !ts.length(implementsExpressions) ? [] : [ts.factory.createHeritageClause(117 /* SyntaxKind.ImplementsKeyword */, implementsExpressions)], true); - var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); + var symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { // `valueDeclaration` could be undefined if inherited from // a union/intersection base type, but inherited properties @@ -342077,7 +342854,6 @@ var ts; // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? [ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createPrivateIdentifier("#private"), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, @@ -342094,12 +342870,11 @@ var ts; ts.isInJSFile(symbol.valueDeclaration) && !ts.some(getSignaturesOfType(staticType, 1 /* SignatureKind.Construct */)); var constructors = isNonConstructableClassLikeInJsFile ? - [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* ModifierFlags.Private */), [], /*body*/ undefined)] : + [ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(8 /* ModifierFlags.Private */), [], /*body*/ undefined)] : serializeSignatures(1 /* SignatureKind.Construct */, staticType, staticBaseType, 171 /* SyntaxKind.Constructor */); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(ts.setTextRange(ts.factory.createClassDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, localName, typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), staticMembers, true), constructors, true), publicProperties, true), privateProperties, true)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags); } function getSomeTargetNameFromDeclarations(declarations) { @@ -342151,7 +342926,6 @@ var ts; var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' var propertyName = node.propertyName; addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier( /*isTypeOnly*/ false, propertyName && ts.isIdentifier(propertyName) ? ts.factory.createIdentifier(ts.idText(propertyName)) : undefined, ts.factory.createIdentifier(localName))])), ts.factory.createStringLiteral(specifier_1), /*importClause*/ undefined), 0 /* ModifierFlags.None */); @@ -342175,12 +342949,10 @@ var ts; var specifier_2 = getSpecifierForModuleSymbol(target.parent || target, context); // 'y' // import _x = require('y'); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0 /* ModifierFlags.None */); // import x = _x.z addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags); break; @@ -342197,7 +342969,6 @@ var ts; // an external `import localName = require("whatever")` var isLocalImport = !(target.flags & 512 /* SymbolFlags.ValueModule */) && !ts.isVariableDeclaration(node); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), isLocalImport ? symbolToName(target, context, 67108863 /* SymbolFlags.All */, /*expectsIdentifier*/ false) @@ -342211,7 +342982,6 @@ var ts; break; case 267 /* SyntaxKind.ImportClause */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag @@ -342221,19 +342991,16 @@ var ts; break; case 268 /* SyntaxKind.NamespaceImport */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)), /*assertClause*/ undefined), 0 /* ModifierFlags.None */); break; case 274 /* SyntaxKind.NamespaceExport */: addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* ModifierFlags.None */); break; case 270 /* SyntaxKind.ImportSpecifier */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( /*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamedImports([ @@ -342272,7 +343039,6 @@ var ts; } function serializeExportSpecifier(localName, targetName, specifier) { addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* ModifierFlags.None */); } @@ -342313,7 +343079,6 @@ var ts; context.tracker.trackSymbol = function () { return false; }; if (isExportAssignmentCompatibleSymbolName) { results.push(ts.factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* SymbolFlags.All */))); } else { @@ -342328,7 +343093,6 @@ var ts; // serialize as `import _Ref = t.arg.et; export { _Ref as name }` var varName = getUnusedName(name, symbol); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* SymbolFlags.All */, /*expectsIdentifier*/ false)), 0 /* ModifierFlags.None */); serializeExportSpecifier(name, varName); @@ -342359,7 +343123,6 @@ var ts; } if (isExportAssignmentCompatibleSymbolName) { results.push(ts.factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.factory.createIdentifier(varName))); return true; } @@ -342409,9 +343172,7 @@ var ts; if (p.flags & 98304 /* SymbolFlags.Accessor */ && useAccessors) { var result = []; if (p.flags & 65536 /* SymbolFlags.SetAccessor */) { - result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], @@ -342419,8 +343180,7 @@ var ts; } if (p.flags & 32768 /* SymbolFlags.GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* ModifierFlags.Private */; - result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); } return result; @@ -342428,8 +343188,7 @@ var ts; // This is an else/if as accessors and properties can't merge in TS, but might in JS // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (4 /* SymbolFlags.Property */ | 3 /* SymbolFlags.Variable */ | 98304 /* SymbolFlags.Accessor */)) { - return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(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*/ undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); @@ -342438,8 +343197,7 @@ var ts; var type = getTypeOfSymbol(p); var signatures = getSignaturesOfType(type, 0 /* SignatureKind.Call */); if (flag & 8 /* ModifierFlags.Private */) { - return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, /*type*/ undefined, /*initializer*/ undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } @@ -342497,8 +343255,7 @@ var ts; } } if (privateProtected) { - return [ts.setTextRange(ts.factory.createConstructorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(privateProtected), + return [ts.setTextRange(ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(privateProtected), /*parameters*/ [], /*body*/ undefined), signatures[0].declaration)]; } @@ -343197,7 +343954,7 @@ var ts; if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)) & 32768 /* TypeFlags.Undefined */) ? getNonUndefinedType(type) : type; + return strictNullChecks && !(getTypeFacts(checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)) & 16777216 /* TypeFacts.IsUndefined */) ? getNonUndefinedType(type) : type; } return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)], 2 /* UnionReduction.Subtype */)); } @@ -343598,7 +344355,7 @@ var ts; (resolvedSymbol || symbol).exports.forEach(function (s, name) { var _a; var exportedMember = members_4.get(name); - if (exportedMember && exportedMember !== s) { + if (exportedMember && exportedMember !== s && !(s.flags & 2097152 /* SymbolFlags.Alias */)) { if (s.flags & 111551 /* SymbolFlags.Value */ && exportedMember.flags & 111551 /* SymbolFlags.Value */) { // If the member has an additional value-like declaration, union the types from the two declarations, // but issue an error if they occurred in two different files. The purpose is to support a JS file with @@ -343632,6 +344389,17 @@ var ts; }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, // Only set the type's symbol if it looks to be the same as the original type members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.indexInfos); + if (initialSize === members_4.size) { + if (type.aliasSymbol) { + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = type.aliasTypeArguments; + } + if (ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */) { + result.aliasSymbol = type.symbol; + var args = getTypeArguments(type); + result.aliasTypeArguments = ts.length(args) ? args : undefined; + } + } result.objectFlags |= (ts.getObjectFlags(type) & 4096 /* ObjectFlags.JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* SymbolFlags.Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { result.objectFlags |= 16777216 /* ObjectFlags.IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type @@ -343684,7 +344452,7 @@ var ts; reportImplicitAny(element, anyType); } // When we're including the pattern in the type (an indication we're obtaining a contextual type), we - // use the non-inferrable any type. Inference will never directly infer this type, but it is possible + // use a non-inferrable any type. Inference will never directly infer this type, but it is possible // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases, // widening of the binding pattern type substitutes a regular any for the non-inferrable any. return includePatternInType ? nonInferrableAnyType : anyType; @@ -344688,7 +345456,7 @@ var ts; error(declaration.typeExpression.type, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } else { - error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + error(ts.isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } } links.declaredType = type; @@ -345788,6 +346556,12 @@ var ts; return mapType(type, getLowerBoundOfKeyType); } if (type.flags & 2097152 /* TypeFlags.Intersection */) { + // Similarly to getTypeFromIntersectionTypeNode, we preserve the special string & {}, number & {}, + // and bigint & {} intersections that are used to prevent subtype reduction in union types. + var types = type.types; + if (types.length === 2 && !!(types[0].flags & (4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) && types[1] === emptyTypeLiteralType) { + return type; + } return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); } return type; @@ -345992,6 +346766,9 @@ var ts; else if (type.objectFlags & 32 /* ObjectFlags.Mapped */) { resolveMappedTypeMembers(type); } + else { + ts.Debug.fail("Unhandled object type " + ts.Debug.formatObjectFlags(type.objectFlags)); + } } else if (type.flags & 1048576 /* TypeFlags.Union */) { resolveUnionTypeMembers(type); @@ -345999,6 +346776,9 @@ var ts; else if (type.flags & 2097152 /* TypeFlags.Intersection */) { resolveIntersectionTypeMembers(type); } + else { + ts.Debug.fail("Unhandled type " + ts.Debug.formatTypeFlags(type.flags)); + } } return type; } @@ -346186,7 +346966,7 @@ var ts; } } } - else if (t.flags & 469892092 /* TypeFlags.DisjointDomains */) { + else if (t.flags & 469892092 /* TypeFlags.DisjointDomains */ || isEmptyAnonymousObjectType(t)) { hasDisjointDomainType = true; } } @@ -346198,12 +346978,13 @@ var ts; // intersection operation to reduce the union constraints. for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { var t = types_6[_a]; - if (t.flags & 469892092 /* TypeFlags.DisjointDomains */) { + if (t.flags & 469892092 /* TypeFlags.DisjointDomains */ || isEmptyAnonymousObjectType(t)) { constraints = ts.append(constraints, t); } } } - return getIntersectionType(constraints); + // The source types were normalized; ensure the result is normalized too. + return getNormalizedType(getIntersectionType(constraints), /*writing*/ false); } return undefined; } @@ -346314,7 +347095,7 @@ var ts; } if (t.flags & 268435456 /* TypeFlags.StringMapping */) { var constraint = getBaseConstraint(t.type); - return constraint ? getStringMappingType(t.symbol, constraint) : stringType; + return constraint && constraint !== t.type ? getStringMappingType(t.symbol, constraint) : stringType; } if (t.flags & 8388608 /* TypeFlags.IndexedAccess */) { if (isMappedTypeGenericIndexedAccess(t)) { @@ -346679,12 +347460,12 @@ var ts; * @param type a type to look up property from * @param name a name of property to look up in a given type */ - function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment) { + function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment, includeTypeOnlyMembers) { type = getReducedApparentType(type); if (type.flags & 524288 /* TypeFlags.Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { + if (symbol && symbolIsValue(symbol, includeTypeOnlyMembers)) { return symbol; } if (skipObjectFunctionPropertyAugment) @@ -346790,12 +347571,15 @@ var ts; // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual // type checking functions). function getTypeParametersFromDeclaration(declaration) { + var _a; var result; - for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { - var node = _a[_i]; + for (var _i = 0, _b = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _b.length; _i++) { + var node = _b[_i]; result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); } - return result; + return (result === null || result === void 0 ? void 0 : result.length) ? result + : ts.isFunctionDeclaration(declaration) ? (_a = getSignatureOfTypeTag(declaration)) === null || _a === void 0 ? void 0 : _a.typeParameters + : undefined; } function symbolsToArray(symbols) { var result = []; @@ -347346,8 +348130,7 @@ var ts; var _a; var inferences; if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { - for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { - var declaration = _b[_i]; + var _loop_15 = function (declaration) { if (declaration.parent.kind === 190 /* SyntaxKind.InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the @@ -347355,12 +348138,12 @@ var ts; // present, we form an intersection of the inferred constraint types. var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; if (grandParent.kind === 178 /* SyntaxKind.TypeReference */ && !omitTypeReferences) { - var typeReference = grandParent; - var typeParameters = getTypeParametersForTypeReference(typeReference); - if (typeParameters) { - var index = typeReference.typeArguments.indexOf(childTypeParameter); - if (index < typeParameters.length) { - var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + var typeReference_1 = grandParent; + var typeParameters_1 = getTypeParametersForTypeReference(typeReference_1); + if (typeParameters_1) { + var index = typeReference_1.typeArguments.indexOf(childTypeParameter); + if (index < typeParameters_1.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters_1[index]); if (declaredConstraint) { // Type parameter constraints can reference other type parameters so // constraints need to be instantiated. If instantiation produces the @@ -347368,7 +348151,9 @@ var ts; // type Foo = [T, U]; // type Bar = T extends Foo ? Foo : T; // the instantiated constraint for U is X, so we discard that inference. - var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var mapper = makeDeferredTypeMapper(typeParameters_1, typeParameters_1.map(function (_, index) { return function () { + return getEffectiveTypeArgumentAtIndex(typeReference_1, typeParameters_1, index); + }; })); var constraint = instantiateType(declaredConstraint, mapper); if (constraint !== typeParameter) { inferences = ts.append(inferences, constraint); @@ -347406,6 +348191,10 @@ var ts; inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); } } + }; + for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + _loop_15(declaration); } } return inferences && getIntersectionType(inferences); @@ -347468,13 +348257,13 @@ var ts; } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type - // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // of an object literal or a non-inferrable type. This is because there are operations in the type checker // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type = types_8[_i]; - if (!(type.flags & excludeKinds)) { + if (excludeKinds === undefined || !(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } } @@ -347486,7 +348275,7 @@ var ts; if (!type) { type = createObjectType(4 /* ObjectFlags.Reference */, target.symbol); target.instantiations.set(id, type); - type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0; type.target = target; type.resolvedTypeArguments = typeArguments; } @@ -348294,7 +349083,7 @@ var ts; var lastRequiredIndex = -1; var firstRestIndex = -1; var lastOptionalOrRestIndex = -1; - var _loop_15 = function (i) { + var _loop_16 = function (i) { var type = elementTypes[i]; var flags = target.elementFlags[i]; if (flags & 8 /* ElementFlags.Variadic */) { @@ -348324,7 +349113,7 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - var state_4 = _loop_15(i); + var state_4 = _loop_16(i); if (typeof state_4 === "object") return state_4.value; } @@ -348520,7 +349309,7 @@ var ts; var templates = ts.filter(types, isPatternLiteralType); if (templates.length) { var i = types.length; - var _loop_16 = function () { + var _loop_17 = function () { i--; var t = types[i]; if (t.flags & 128 /* TypeFlags.StringLiteral */ && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { @@ -348528,7 +349317,7 @@ var ts; } }; while (i > 0) { - _loop_16(); + _loop_17(); } } } @@ -348605,14 +349394,14 @@ var ts; var namedUnions = []; addNamedUnions(namedUnions, types); var reducedTypes = []; - var _loop_17 = function (t) { + var _loop_18 = function (t) { if (!ts.some(namedUnions, function (union) { return containsType(union.types, t); })) { reducedTypes.push(t); } }; for (var _i = 0, typeSet_1 = typeSet; _i < typeSet_1.length; _i++) { var t = typeSet_1[_i]; - _loop_17(t); + _loop_18(t); } if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) { return namedUnions[0]; @@ -348747,7 +349536,7 @@ var ts; } return includes; } - function removeRedundantPrimitiveTypes(types, includes) { + function removeRedundantSupertypes(types, includes) { var i = types.length; while (i > 0) { i--; @@ -348755,7 +349544,9 @@ var ts; var remove = t.flags & 4 /* TypeFlags.String */ && includes & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */ | 268435456 /* TypeFlags.StringMapping */) || t.flags & 8 /* TypeFlags.Number */ && includes & 256 /* TypeFlags.NumberLiteral */ || t.flags & 64 /* TypeFlags.BigInt */ && includes & 2048 /* TypeFlags.BigIntLiteral */ || - t.flags & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */; + t.flags & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */ || + t.flags & 16384 /* TypeFlags.Void */ && includes & 32768 /* TypeFlags.Undefined */ || + isEmptyAnonymousObjectType(t) && includes & 470302716 /* TypeFlags.DefinitelyNonNullable */; if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -348877,7 +349668,7 @@ var ts; // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + function getIntersectionType(types, aliasSymbol, aliasTypeArguments, noSupertypeReduction) { var typeMembershipMap = new ts.Map(); var includes = addTypesToIntersection(typeMembershipMap, 0, types); var typeSet = ts.arrayFrom(typeMembershipMap.values()); @@ -348909,16 +349700,16 @@ var ts; return includes & 8388608 /* TypeFlags.IncludesWildcard */ ? wildcardType : anyType; } if (!strictNullChecks && includes & 98304 /* TypeFlags.Nullable */) { - return includes & 32768 /* TypeFlags.Undefined */ ? undefinedType : nullType; + return includes & 16777216 /* TypeFlags.IncludesEmptyObject */ ? neverType : includes & 32768 /* TypeFlags.Undefined */ ? undefinedType : nullType; } if (includes & 4 /* TypeFlags.String */ && includes & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */ | 268435456 /* TypeFlags.StringMapping */) || includes & 8 /* TypeFlags.Number */ && includes & 256 /* TypeFlags.NumberLiteral */ || includes & 64 /* TypeFlags.BigInt */ && includes & 2048 /* TypeFlags.BigIntLiteral */ || - includes & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */) { - removeRedundantPrimitiveTypes(typeSet, includes); - } - if (includes & 16777216 /* TypeFlags.IncludesEmptyObject */ && includes & 524288 /* TypeFlags.Object */) { - ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); + includes & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */ || + includes & 16384 /* TypeFlags.Void */ && includes & 32768 /* TypeFlags.Undefined */ || + includes & 16777216 /* TypeFlags.IncludesEmptyObject */ && includes & 470302716 /* TypeFlags.DefinitelyNonNullable */) { + if (!noSupertypeReduction) + removeRedundantSupertypes(typeSet, includes); } if (includes & 262144 /* TypeFlags.IncludesMissingType */) { typeSet[typeSet.indexOf(undefinedType)] = missingType; @@ -348957,8 +349748,9 @@ var ts; } var constituents = getCrossProductIntersections(typeSet); // We attach a denormalized origin type when at least one constituent of the cross-product union is an - // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions). - var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* TypeFlags.Intersection */); }) ? createOriginUnionOrIntersectionType(2097152 /* TypeFlags.Intersection */, typeSet) : undefined; + // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions) and + // the denormalized origin has fewer constituents than the union itself. + var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* TypeFlags.Intersection */); }) && getConstituentCountOfTypes(constituents) > getConstituentCountOfTypes(typeSet) ? createOriginUnionOrIntersectionType(2097152 /* TypeFlags.Intersection */, typeSet) : undefined; result = getUnionType(constituents, 1 /* UnionReduction.Literal */, aliasSymbol, aliasTypeArguments, origin); } } @@ -349001,11 +349793,21 @@ var ts; } return intersections; } + function getConstituentCount(type) { + return !(type.flags & 3145728 /* TypeFlags.UnionOrIntersection */) || type.aliasSymbol ? 1 : + type.flags & 1048576 /* TypeFlags.Union */ && type.origin ? getConstituentCount(type.origin) : + getConstituentCountOfTypes(type.types); + } + function getConstituentCountOfTypes(types) { + return ts.reduceLeft(types, function (n, t) { return n + getConstituentCount(t); }, 0); + } function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var aliasSymbol = getAliasSymbolForTypeNode(node); - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + var types = ts.map(node.types, getTypeFromTypeNode); + var noSupertypeReduction = types.length === 2 && !!(types[0].flags & (4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) && types[1] === emptyTypeLiteralType; + links.resolvedType = getIntersectionType(types, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol), noSupertypeReduction); } return links.resolvedType; } @@ -349133,19 +349935,22 @@ var ts; * to reduce the resulting type if possible (since only intersections with conflicting literal-typed properties are reducible). */ function isPossiblyReducibleByInstantiation(type) { - return ts.some(type.types, function (t) { - var uniqueFilled = getUniqueLiteralFilledInstantiation(t); - return getReducedType(uniqueFilled) !== uniqueFilled; - }); + var uniqueFilled = getUniqueLiteralFilledInstantiation(type); + return getReducedType(uniqueFilled) !== uniqueFilled; + } + function shouldDeferIndexType(type) { + return !!(type.flags & 58982400 /* TypeFlags.InstantiableNonPrimitive */ || + isGenericTupleType(type) || + isGenericMappedType(type) && !hasDistributiveNameType(type) || + type.flags & 1048576 /* TypeFlags.Union */ && ts.some(type.types, isPossiblyReducibleByInstantiation) || + type.flags & 2097152 /* TypeFlags.Intersection */ && maybeTypeOfKind(type, 465829888 /* TypeFlags.Instantiable */) && ts.some(type.types, isEmptyAnonymousObjectType)); } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } type = getReducedType(type); - return type.flags & 1048576 /* TypeFlags.Union */ ? isPossiblyReducibleByInstantiation(type) - ? getIndexTypeForGenericType(type, stringsOnly) - : getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 2097152 /* TypeFlags.Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 58982400 /* TypeFlags.InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && !hasDistributiveNameType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + return shouldDeferIndexType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + type.flags & 1048576 /* TypeFlags.Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : + type.flags & 2097152 /* TypeFlags.Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */ ? getIndexTypeForMappedType(type, stringsOnly, noIndexSignatures) : type === wildcardType ? wildcardType : type.flags & 2 /* TypeFlags.Unknown */ ? neverType : @@ -349271,9 +350076,12 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 /* TypeFlags.Union */ | 131072 /* TypeFlags.Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type; + // Mapping> === Mapping + type.flags & 268435456 /* TypeFlags.StringMapping */ && symbol === type.symbol ? type : + isGenericIndexType(type) || isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, isPatternLiteralPlaceholderType(type) && !(type.flags & 268435456 /* TypeFlags.StringMapping */) ? getTemplateLiteralType(["", ""], [type]) : type) : + type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : + type.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : + type; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -349284,6 +350092,15 @@ var ts; } return str; } + function applyTemplateStringMapping(symbol, texts, types) { + switch (intrinsicTypeKinds.get(symbol.escapedName)) { + case 0 /* IntrinsicTypeKind.Uppercase */: return [texts.map(function (t) { return t.toUpperCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 1 /* IntrinsicTypeKind.Lowercase */: return [texts.map(function (t) { return t.toLowerCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 2 /* IntrinsicTypeKind.Capitalize */: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toUpperCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + case 3 /* IntrinsicTypeKind.Uncapitalize */: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toLowerCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + } + return [texts, types]; + } function getStringMappingTypeForGenericType(symbol, type) { var id = "".concat(getSymbolId(symbol), ",").concat(getTypeId(type)); var result = stringMappingTypes.get(id); @@ -349385,21 +350202,28 @@ var ts; getFlowTypeOfReference(accessExpression, propType) : propType; } - if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName) && +propName >= 0) { + if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName)) { + var index = +propName; if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 16 /* AccessFlags.NoTupleBoundsCheck */)) { var indexNode = getIndexNodeForAccessExpression(accessNode); if (isTupleType(objectType)) { + if (index < 0) { + error(indexNode, ts.Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value); + return undefinedType; + } error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName)); } else { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } } - errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); - return mapType(objectType, function (t) { - var restType = getRestTypeOfTupleType(t) || undefinedType; - return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([restType, undefinedType]) : restType; - }); + if (index >= 0) { + errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); + return mapType(objectType, function (t) { + var restType = getRestTypeOfTupleType(t) || undefinedType; + return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([restType, undefinedType]) : restType; + }); + } } } if (!(indexType.flags & 98304 /* TypeFlags.Nullable */) && isTypeAssignableToKind(indexType, 402653316 /* TypeFlags.StringLike */ | 296 /* TypeFlags.NumberLike */ | 12288 /* TypeFlags.ESSymbolLike */)) { @@ -349525,7 +350349,7 @@ var ts; accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)); + return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */ && isPatternLiteralPlaceholderType(type.type)); } function isPatternLiteralType(type) { return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); @@ -349566,7 +350390,7 @@ var ts; // (T | U)[K] -> T[K] | U[K] (reading) // (T | U)[K] -> T[K] & U[K] (writing) // (T & U)[K] -> T[K] & U[K] - if (objectType.flags & 3145728 /* TypeFlags.UnionOrIntersection */) { + if (objectType.flags & 1048576 /* TypeFlags.Union */ || objectType.flags & 2097152 /* TypeFlags.Intersection */ && !shouldDeferIndexType(objectType)) { var types = ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType), writing); }); return objectType.flags & 2097152 /* TypeFlags.Intersection */ || writing ? getIntersectionType(types) : getUnionType(types); } @@ -349663,7 +350487,7 @@ var ts; function substituteIndexedMappedType(objectType, index) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]); var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return instantiateType(getTemplateTypeFromMappedType(objectType.target || objectType), templateMapper); } function getIndexedAccessType(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) { if (accessFlags === void 0) { accessFlags = 0 /* AccessFlags.None */; } @@ -349811,7 +350635,7 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_18 = function () { + var _loop_19 = function () { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; @@ -349932,7 +350756,7 @@ var ts; // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive // cases we increment the tail recursion counter and stop after 1000 iterations. while (true) { - var state_5 = _loop_18(); + var state_5 = _loop_19(); if (typeof state_5 === "object") return state_5.value; if (state_5 === "break") @@ -350033,6 +350857,7 @@ var ts; } } function getTypeFromImportTypeNode(node) { + var _a; var links = getNodeLinks(node); if (!links.resolvedType) { if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments @@ -350052,6 +350877,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } + var isExportEquals = !!((_a = innerModuleSymbol.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* InternalSymbolName.ExportEquals */)); var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); if (!ts.nodeIsMissing(node.qualifier)) { var nameStack = getIdentifierChain(node.qualifier); @@ -350063,9 +350889,11 @@ var ts; // That, in turn, ultimately uses `getPropertyOfType` on the type of the symbol, which differs slightly from // the `exports` lookup process that only looks up namespace members which is used for most type references var mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace)); - var next = node.isTypeOf - ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText) - : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var symbolFromVariable = node.isTypeOf || ts.isInJSFile(node) && isExportEquals + ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ true) + : undefined; + var symbolFromModule = node.isTypeOf ? undefined : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var next = symbolFromModule !== null && symbolFromModule !== void 0 ? symbolFromModule : symbolFromVariable; if (!next) { error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); return links.resolvedType = errorType; @@ -350562,7 +351390,7 @@ var ts; switch (mapper.kind) { case 0 /* TypeMapKind.Simple */: return type === mapper.source ? mapper.target : type; - case 1 /* TypeMapKind.Array */: + case 1 /* TypeMapKind.Array */: { var sources = mapper.sources; var targets = mapper.targets; for (var i = 0; i < sources.length; i++) { @@ -350571,25 +351399,39 @@ var ts; } } return type; - case 2 /* TypeMapKind.Function */: + } + case 2 /* TypeMapKind.Deferred */: { + var sources = mapper.sources; + var targets = mapper.targets; + for (var i = 0; i < sources.length; i++) { + if (type === sources[i]) { + return targets[i](); + } + } + return type; + } + case 3 /* TypeMapKind.Function */: return mapper.func(type); - case 3 /* TypeMapKind.Composite */: - case 4 /* TypeMapKind.Merged */: + case 4 /* TypeMapKind.Composite */: + case 5 /* TypeMapKind.Merged */: var t1 = getMappedType(type, mapper.mapper1); - return t1 !== type && mapper.kind === 3 /* TypeMapKind.Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); + return t1 !== type && mapper.kind === 4 /* TypeMapKind.Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); } } function makeUnaryTypeMapper(source, target) { - return { kind: 0 /* TypeMapKind.Simple */, source: source, target: target }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 0 /* TypeMapKind.Simple */, source: source, target: target }); } function makeArrayTypeMapper(sources, targets) { - return { kind: 1 /* TypeMapKind.Array */, sources: sources, targets: targets }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 1 /* TypeMapKind.Array */, sources: sources, targets: targets }); } - function makeFunctionTypeMapper(func) { - return { kind: 2 /* TypeMapKind.Function */, func: func }; + function makeFunctionTypeMapper(func, debugInfo) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 3 /* TypeMapKind.Function */, func: func, debugInfo: ts.Debug.isDebugging ? debugInfo : undefined }); + } + function makeDeferredTypeMapper(sources, targets) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 2 /* TypeMapKind.Deferred */, sources: sources, targets: targets }); } function makeCompositeTypeMapper(kind, mapper1, mapper2) { - return { kind: kind, mapper1: mapper1, mapper2: mapper2 }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: kind, mapper1: mapper1, mapper2: mapper2 }); } function createTypeEraser(sources) { return createTypeMapper(sources, /*targets*/ undefined); @@ -350599,19 +351441,20 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(context, index) { - return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; }); + var forwardInferences = context.inferences.slice(index); + return createTypeMapper(ts.map(forwardInferences, function (i) { return i.typeParameter; }), ts.map(forwardInferences, function () { return unknownType; })); } function combineTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(3 /* TypeMapKind.Composite */, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(4 /* TypeMapKind.Composite */, mapper1, mapper2) : mapper2; } function mergeTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, mapper1, mapper2) : mapper2; } function prependTypeMapping(source, target, mapper) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, makeUnaryTypeMapper(source, target), mapper); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, makeUnaryTypeMapper(source, target), mapper); } function appendTypeMapping(mapper, source, target) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, mapper, makeUnaryTypeMapper(source, target)); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, mapper, makeUnaryTypeMapper(source, target)); } function getRestrictiveTypeParameter(tp) { return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol), @@ -350877,6 +351720,7 @@ var ts; result.mapper = mapper; result.aliasSymbol = aliasSymbol || type.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + result.objectFlags |= result.aliasTypeArguments ? getPropagatingFlagsOfTypes(result.aliasTypeArguments) : 0; return result; } function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { @@ -351525,7 +352369,7 @@ var ts; }); } function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068 /* TypeFlags.Primitive */) + if (target.flags & (131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) return false; if (isTupleLikeType(source)) { return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer); @@ -351592,7 +352436,7 @@ var ts; }); } function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068 /* TypeFlags.Primitive */) + if (target.flags & (131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) return false; return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer); } @@ -351679,7 +352523,7 @@ var ts; var sourceSig = checkMode & 3 /* SignatureCheckMode.Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = checkMode & 3 /* SignatureCheckMode.Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && - (getFalsyFlags(sourceType) & 98304 /* TypeFlags.Nullable */) === (getFalsyFlags(targetType) & 98304 /* TypeFlags.Nullable */); + (getTypeFacts(sourceType) & 50331648 /* TypeFacts.IsUndefinedOrNull */) === (getTypeFacts(targetType) & 50331648 /* TypeFacts.IsUndefinedOrNull */); var related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* SignatureCheckMode.StrictArity */) | (strictVariance ? 2 /* SignatureCheckMode.StrictCallback */ : 1 /* SignatureCheckMode.BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !(checkMode & 3 /* SignatureCheckMode.Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); @@ -351791,6 +352635,20 @@ var ts; return !!(ts.getObjectFlags(type) & 16 /* ObjectFlags.Anonymous */ && (type.members && isEmptyResolvedType(type) || type.symbol && type.symbol.flags & 2048 /* SymbolFlags.TypeLiteral */ && getMembersOfSymbol(type.symbol).size === 0)); } + function isUnknownLikeUnionType(type) { + if (strictNullChecks && type.flags & 1048576 /* TypeFlags.Union */) { + if (!(type.objectFlags & 33554432 /* ObjectFlags.IsUnknownLikeUnionComputed */)) { + var types = type.types; + type.objectFlags |= 33554432 /* ObjectFlags.IsUnknownLikeUnionComputed */ | (types.length >= 3 && types[0].flags & 32768 /* TypeFlags.Undefined */ && + types[1].flags & 65536 /* TypeFlags.Null */ && ts.some(types, isEmptyAnonymousObjectType) ? 67108864 /* ObjectFlags.IsUnknownLikeUnion */ : 0); + } + return !!(type.objectFlags & 67108864 /* ObjectFlags.IsUnknownLikeUnion */); + } + return false; + } + function containsUndefinedType(type) { + return !!((type.flags & 1048576 /* TypeFlags.Union */ ? type.types[0] : type).flags & 32768 /* TypeFlags.Undefined */); + } function isStringIndexSignatureOnlyType(type) { return type.flags & 524288 /* TypeFlags.Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, stringType) || type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) || @@ -351870,7 +352728,7 @@ var ts; return true; if (s & 65536 /* TypeFlags.Null */ && (!strictNullChecks && !(t & 3145728 /* TypeFlags.UnionOrIntersection */) || t & 65536 /* TypeFlags.Null */)) return true; - if (s & 524288 /* TypeFlags.Object */ && t & 67108864 /* TypeFlags.NonPrimitive */) + if (s & 524288 /* TypeFlags.Object */ && t & 67108864 /* TypeFlags.NonPrimitive */ && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(ts.getObjectFlags(source) & 8192 /* ObjectFlags.FreshLiteral */))) return true; if (relation === assignableRelation || relation === comparableRelation) { if (s & 1 /* TypeFlags.Any */) @@ -351880,6 +352738,9 @@ var ts; // bit-flag enum types sometimes look like literal enum types with numeric literal values. if (s & (8 /* TypeFlags.Number */ | 256 /* TypeFlags.NumberLiteral */) && !(s & 1024 /* TypeFlags.EnumLiteral */) && (t & 32 /* TypeFlags.Enum */ || relation === assignableRelation && t & 256 /* TypeFlags.NumberLiteral */ && t & 1024 /* TypeFlags.EnumLiteral */)) return true; + // Anything is assignable to a union containing undefined, null, and {} + if (isUnknownLikeUnionType(target)) + return true; } return false; } @@ -351922,16 +352783,27 @@ var ts; function getNormalizedType(type, writing) { while (true) { var t = isFreshLiteralType(type) ? type.regularType : - ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ ? getReducedType(type) : + ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */ ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : + type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & 33554432 /* TypeFlags.Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* TypeFlags.Simplifiable */ ? getSimplifiedType(type, writing) : type; - t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) - break; + return t; type = t; } + } + function getNormalizedUnionOrIntersectionType(type, writing) { + var reduced = getReducedType(type); + if (reduced !== type) { + return reduced; + } + if (type.flags & 2097152 /* TypeFlags.Intersection */ && ts.some(type.types, isEmptyAnonymousObjectType)) { + var normalizedTypes = ts.sameMap(type.types, function (t) { return getNormalizedType(t, writing); }); + if (normalizedTypes !== type.types) { + return getIntersectionType(normalizedTypes); + } + } return type; } /** @@ -352163,7 +353035,7 @@ var ts; ts.Debug.assert(!isTypeAssignableTo(generalizedSource, target), "generalized source shouldn't be assignable"); generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource); } - if (target.flags & 262144 /* TypeFlags.TypeParameter */ && target !== markerSuperType && target !== markerSubType) { + if (target.flags & 262144 /* TypeFlags.TypeParameter */ && target !== markerSuperTypeForCheck && target !== markerSubTypeForCheck) { var constraint = getBaseConstraintOfType(target); var needsOriginalSource = void 0; if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) { @@ -352378,6 +353250,7 @@ var ts; return 0 /* Ternary.False */; } function reportErrorResults(originalSource, originalTarget, source, target, headMessage) { + var _a, _b; var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; @@ -352418,6 +353291,14 @@ var ts; return; } reportRelationError(headMessage, source, target); + if (source.flags & 262144 /* TypeFlags.TypeParameter */ && ((_b = (_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) === null || _b === void 0 ? void 0 : _b[0]) && !getConstraintOfType(source)) { + var syntheticParam = cloneTypeParameter(source); + syntheticParam.constraint = instantiateType(target, makeUnaryTypeMapper(source, syntheticParam)); + if (hasNonCircularBaseConstraint(syntheticParam)) { + var targetConstraintString = typeToString(target, source.symbol.declarations[0]); + associateRelatedInfo(ts.createDiagnosticForNode(source.symbol.declarations[0], ts.Diagnostics.This_type_parameter_might_need_an_extends_0_constraint, targetConstraintString)); + } + } } function traceUnionsOrIntersectionsTooLarge(source, target) { if (!ts.tracing) { @@ -352470,7 +353351,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* TypeFlags.Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_19 = function (prop) { + var _loop_20 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -352533,7 +353414,7 @@ var ts; }; for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { var prop = _b[_i]; - var state_6 = _loop_19(prop); + var state_6 = _loop_20(prop); if (typeof state_6 === "object") return state_6.value; } @@ -352555,7 +353436,7 @@ var ts; return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* TypeFlags.Primitive */) && !(target.flags & 131068 /* TypeFlags.Primitive */)); } if (target.flags & 2097152 /* TypeFlags.Intersection */) { - return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* IntersectionState.Target */); + return typeRelatedToEachType(source, target, reportErrors, 2 /* IntersectionState.Target */); } // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the // constraints of all non-primitive types in the source into a new intersection. We do this because the @@ -352765,10 +353646,10 @@ var ts; // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component var saved = entry & 24 /* RelationComparisonResult.ReportsMask */; if (saved & 8 /* RelationComparisonResult.ReportsUnmeasurable */) { - instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers)); + instantiateType(source, reportUnmeasurableMapper); } if (saved & 16 /* RelationComparisonResult.ReportsUnreliable */) { - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } } return entry & 1 /* RelationComparisonResult.Succeeded */ ? -1 /* Ternary.True */ : 0 /* Ternary.False */; @@ -352868,13 +353749,40 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { + var saveErrorInfo = captureErrorCalculationState(); + var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo); + if (!result && (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */)) { + // The combined constraint of an intersection type is the intersection of the constraints of + // the constituents. When an intersection type contains instantiable types with union type + // constraints, there are situations where we need to examine the combined constraint. One is + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + // This also handles type parameters, as a type parameter with a union constraint compared against a union + // needs to have its constraint hoisted into an intersection with said type parameter, this way + // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) + // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` + var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); + if (constraint && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself + // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this + result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + } + } + if (result) { + resetErrorInfo(saveErrorInfo); + } + return result; + } + function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo) { if (intersectionState & 4 /* IntersectionState.PropertyCheck */) { return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* IntersectionState.None */); } var result; var originalErrorInfo; var varianceCheckFailed = false; - var saveErrorInfo = captureErrorCalculationState(); var sourceFlags = source.flags; var targetFlags = target.flags; if (relation === identityRelation) { @@ -352920,29 +353828,6 @@ var ts; if (result = unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState)) { return result; } - if (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */) { - // The combined constraint of an intersection type is the intersection of the constraints of - // the constituents. When an intersection type contains instantiable types with union type - // constraints, there are situations where we need to examine the combined constraint. One is - // when the target is a union type. Another is when the intersection contains types belonging - // to one of the disjoint domains. For example, given type variables T and U, each with the - // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and - // we need to check this constraint against a union on the target side. Also, given a type - // variable V constrained to 'string | number', 'V & number' has a combined constraint of - // 'string & number | number & number' which reduces to just 'number'. - // This also handles type parameters, as a type parameter with a union constraint compared against a union - // needs to have its constraint hoisted into an intersection with said type parameter, this way - // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) - // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` - var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); - if (constraint && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself - // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this - if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - } // The ordered decomposition above doesn't handle all cases. Specifically, we also need to handle: // Source is instantiable (e.g. source has union or intersection constraint). // Source is an object, target is a union (e.g. { a, b: boolean } <=> { a, b: true } | { a, b: false }). @@ -352986,6 +353871,20 @@ var ts; } } } + if (relation === comparableRelation && sourceFlags & 262144 /* TypeFlags.TypeParameter */) { + // This is a carve-out in comparability to essentially forbid comparing a type parameter + // with another type parameter unless one extends the other. (Remember: comparability is mostly bidirectional!) + var constraint = getConstraintOfTypeParameter(source); + if (constraint && hasNonCircularBaseConstraint(source)) { + while (constraint && constraint.flags & 262144 /* TypeFlags.TypeParameter */) { + if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false)) { + return result; + } + constraint = getConstraintOfTypeParameter(constraint); + } + } + return 0 /* Ternary.False */; + } } else if (targetFlags & 4194304 /* TypeFlags.Index */) { var targetType_1 = target.type; @@ -353049,7 +353948,6 @@ var ts; result &= isRelatedTo(source.indexType, target.indexType, 3 /* RecursionFlags.Both */, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } if (reportErrors) { @@ -353071,7 +353969,7 @@ var ts; // create a new chain for the constraint error resetErrorInfo(saveErrorInfo); } - if (result = isRelatedTo(source, constraint, 2 /* RecursionFlags.Target */, reportErrors)) { + if (result = isRelatedTo(source, constraint, 2 /* RecursionFlags.Target */, reportErrors, /* headMessage */ undefined, intersectionState)) { return result; } // prefer the shorter chain of the constraint comparison chain, and the direct comparison chain @@ -353152,7 +354050,6 @@ var ts; // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3 /* Ternary.Maybe */; } var c = target; @@ -353164,10 +354061,9 @@ var ts; var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); var skipFalse = !skipTrue && isTypeAssignableTo(getRestrictiveInstantiation(c.checkType), getRestrictiveInstantiation(c.extendsType)); // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) - if (result = skipTrue ? -1 /* Ternary.True */ : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false)) { - result &= skipFalse ? -1 /* Ternary.True */ : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false); + if (result = skipTrue ? -1 /* Ternary.True */ : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { + result &= skipFalse ? -1 /* Ternary.True */ : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -353180,31 +354076,29 @@ var ts; } // Report unreliable variance for type variables referenced in template literal type placeholders. // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } if (isTypeMatchedByTemplateLiteralType(source, target)) { return -1 /* Ternary.True */; } } + else if (target.flags & 268435456 /* TypeFlags.StringMapping */) { + if (!(source.flags & 268435456 /* TypeFlags.StringMapping */)) { + if (isMemberOfStringMapping(source, target)) { + return -1 /* Ternary.True */; + } + } + } if (sourceFlags & 8650752 /* TypeFlags.TypeVariable */) { // IndexedAccess comparisons are handled above in the `targetFlags & TypeFlage.IndexedAccess` branch if (!(sourceFlags & 8388608 /* TypeFlags.IndexedAccess */ && targetFlags & 8388608 /* TypeFlags.IndexedAccess */)) { - var constraint = getConstraintOfType(source); - if (!constraint || (sourceFlags & 262144 /* TypeFlags.TypeParameter */ && constraint.flags & 1 /* TypeFlags.Any */)) { - // A type variable with no constraint is not related to the non-primitive object type. - if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* TypeFlags.NonPrimitive */), 3 /* RecursionFlags.Both */)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } + var constraint = getConstraintOfType(source) || unknownType; // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed - else if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* RecursionFlags.Source */, reportErrors && !(targetFlags & sourceFlags & 262144 /* TypeFlags.TypeParameter */), /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* RecursionFlags.Source */, reportErrors && constraint !== unknownType && !(targetFlags & sourceFlags & 262144 /* TypeFlags.TypeParameter */), /*headMessage*/ undefined, intersectionState)) { return result; } if (isMappedTypeGenericIndexedAccess(source)) { @@ -353213,7 +354107,6 @@ var ts; var indexConstraint = getConstraintOfType(source.indexType); if (indexConstraint) { if (result = isRelatedTo(getIndexedAccessType(source.objectType, indexConstraint), target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -353222,7 +354115,6 @@ var ts; } else if (sourceFlags & 4194304 /* TypeFlags.Index */) { if (result = isRelatedTo(keyofConstraintType, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -353230,22 +354122,22 @@ var ts; if (!(targetFlags & 134217728 /* TypeFlags.TemplateLiteral */)) { var constraint = getBaseConstraintOfType(source); if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } } else if (sourceFlags & 268435456 /* TypeFlags.StringMapping */) { - if (targetFlags & 268435456 /* TypeFlags.StringMapping */ && source.symbol === target.symbol) { + if (targetFlags & 268435456 /* TypeFlags.StringMapping */) { + if (source.symbol !== target.symbol) { + return 0 /* Ternary.False */; + } if (result = isRelatedTo(source.type, target.type, 3 /* RecursionFlags.Both */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } else { var constraint = getBaseConstraintOfType(source); if (constraint && (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -353254,7 +354146,6 @@ var ts; // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3 /* Ternary.Maybe */; } if (targetFlags & 16777216 /* TypeFlags.Conditional */) { @@ -353277,7 +354168,6 @@ var ts; result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* RecursionFlags.Both */, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -353288,7 +354178,6 @@ var ts; var distributiveConstraint = hasNonCircularBaseConstraint(source) ? getConstraintOfDistributiveConditionalType(source) : undefined; if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -353298,7 +354187,6 @@ var ts; var defaultConstraint = getDefaultConstraintOfConditionalType(source); if (defaultConstraint) { if (result = isRelatedTo(defaultConstraint, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -353311,7 +354199,6 @@ var ts; if (isGenericMappedType(target)) { if (isGenericMappedType(source)) { if (result = mappedTypeRelatedTo(source, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -353449,18 +354336,6 @@ var ts; } } } - function reportUnmeasurableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false); - } - return p; - } - function reportUnreliableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true); - } - return p; - } // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice // that S and T are contra-variant whereas X and Y are co-variant. @@ -353470,7 +354345,7 @@ var ts; if (modifiersRelated) { var result_10; var targetConstraint = getConstraintTypeFromMappedType(target); - var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); + var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMapper : reportUnreliableMapper); if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* RecursionFlags.Both */, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { @@ -353524,11 +354399,11 @@ var ts; // constituents of 'target'. If any combination does not have a match then 'source' is not relatable. var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_20 = function (combination) { + var _loop_21 = function (combination) { var hasMatch = false; outer: for (var _c = 0, _d = target.types; _c < _d.length; _c++) { var type = _d[_c]; - var _loop_21 = function (i) { + var _loop_22 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -353544,7 +354419,7 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_8 = _loop_21(i); + var state_8 = _loop_22(i); switch (state_8) { case "continue-outer": continue outer; } @@ -353558,7 +354433,7 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_7 = _loop_20(combination); + var state_7 = _loop_21(combination); if (typeof state_7 === "object") return state_7.value; } @@ -354006,7 +354881,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* SignatureCheckMode.StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, makeFunctionTypeMapper(reportUnreliableMarkers)); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* SignatureCheckMode.StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, reportUnreliableMapper); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -354161,7 +355036,7 @@ var ts; return typeCouldHaveTopLevelSingletonTypes(constraint); } } - return isUnitType(type) || !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */); + return isUnitType(type) || !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */); } function getExactOptionalUnassignableProperties(source, target) { if (isTupleType(source) && isTupleType(target)) @@ -354265,7 +355140,7 @@ var ts; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* tracing.Phase.CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) }); links.variances = ts.emptyArray; var variances = []; - var _loop_22 = function (tp) { + var _loop_23 = function (tp) { var modifiers = getVarianceModifiers(tp); var variance = modifiers & 65536 /* ModifierFlags.Out */ ? modifiers & 32768 /* ModifierFlags.In */ ? 0 /* VarianceFlags.Invariant */ : 1 /* VarianceFlags.Covariant */ : @@ -354301,12 +355176,12 @@ var ts; } variances.push(variance); }; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var tp = typeParameters_1[_i]; - _loop_22(tp); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var tp = typeParameters_2[_i]; + _loop_23(tp); } links.variances = variances; - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop({ variances: variances.map(ts.Debug.formatVariance) }); } return links.variances; } @@ -354644,35 +355519,33 @@ var ts; var commonBaseType; for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { var t = types_13[_i]; - var baseType = getBaseTypeOfLiteralType(t); - if (!commonBaseType) { - commonBaseType = baseType; - } - if (baseType === t || baseType !== commonBaseType) { - return false; + if (!(t.flags & 131072 /* TypeFlags.Never */)) { + var baseType = getBaseTypeOfLiteralType(t); + commonBaseType !== null && commonBaseType !== void 0 ? commonBaseType : (commonBaseType = baseType); + if (baseType === t || baseType !== commonBaseType) { + return false; + } } } return true; } - // When the candidate types are all literal types with the same base type, return a union - // of those literal types. Otherwise, return the leftmost type for which no type to the - // right is a supertype. - function getSupertypeOrUnion(types) { - if (types.length === 1) { - return types[0]; - } - return literalTypesWithSameBaseType(types) ? - getUnionType(types) : - ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + function getCombinedTypeFlags(types) { + return ts.reduceLeft(types, function (flags, t) { return flags | (t.flags & 1048576 /* TypeFlags.Union */ ? getCombinedTypeFlags(t.types) : t.flags); }, 0); } function getCommonSupertype(types) { - if (!strictNullChecks) { - return getSupertypeOrUnion(types); + if (types.length === 1) { + return types[0]; } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* TypeFlags.Nullable */); }); - return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* TypeFlags.Nullable */) : - getUnionType(types, 2 /* UnionReduction.Subtype */); + // Remove nullable types from each of the candidates. + var primaryTypes = strictNullChecks ? ts.sameMap(types, function (t) { return filterType(t, function (u) { return !(u.flags & 98304 /* TypeFlags.Nullable */); }); }) : types; + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. + var superTypeOrUnion = literalTypesWithSameBaseType(primaryTypes) ? + getUnionType(primaryTypes) : + ts.reduceLeft(primaryTypes, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + // Add any nullable types that occurred in the candidates back to the result. + return primaryTypes === types ? superTypeOrUnion : getNullableType(superTypeOrUnion, getCombinedTypeFlags(types) & 98304 /* TypeFlags.Nullable */); } // Return the leftmost type for which no type to the right is a subtype. function getCommonSubtype(types) { @@ -354776,9 +355649,14 @@ var ts; type.flags & 256 /* TypeFlags.NumberLiteral */ ? numberType : type.flags & 2048 /* TypeFlags.BigIntLiteral */ ? bigintType : type.flags & 512 /* TypeFlags.BooleanLiteral */ ? booleanType : - type.flags & 1048576 /* TypeFlags.Union */ ? mapType(type, getBaseTypeOfLiteralType) : + type.flags & 1048576 /* TypeFlags.Union */ ? getBaseTypeOfLiteralTypeUnion(type) : type; } + function getBaseTypeOfLiteralTypeUnion(type) { + var _a; + var key = "B".concat(getTypeId(type)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, mapType(type, getBaseTypeOfLiteralType)); + } function getWidenedLiteralType(type) { return type.flags & 1024 /* TypeFlags.EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : type.flags & 128 /* TypeFlags.StringLiteral */ && isFreshLiteralType(type) ? stringType : @@ -354859,29 +355737,8 @@ var ts; var value = _a.value; return value.base10Value === "0"; } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; - result |= getFalsyFlags(t); - } - return result; - } - // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null - // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns - // no flags for all other types (including non-falsy literal types). - function getFalsyFlags(type) { - return type.flags & 1048576 /* TypeFlags.Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? type.value === "" ? 128 /* TypeFlags.StringLiteral */ : 0 : - type.flags & 256 /* TypeFlags.NumberLiteral */ ? type.value === 0 ? 256 /* TypeFlags.NumberLiteral */ : 0 : - type.flags & 2048 /* TypeFlags.BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* TypeFlags.BigIntLiteral */ : 0 : - type.flags & 512 /* TypeFlags.BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* TypeFlags.BooleanLiteral */ : 0 : - type.flags & 117724 /* TypeFlags.PossiblyFalsy */; - } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 117632 /* TypeFlags.DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* TypeFlags.DefinitelyFalsy */); }) : - type; + return filterType(type, function (t) { return !!(getTypeFacts(t) & 4194304 /* TypeFacts.Truthy */); }); } function extractDefinitelyFalsyTypes(type) { return mapType(type, getDefinitelyFalsyPartOfType); @@ -354916,20 +355773,15 @@ var ts; return type.flags & 32768 /* TypeFlags.Undefined */ ? type : getUnionType([type, isProperty ? missingType : undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { - // First reduce away any constituents that are assignable to 'undefined' or 'null'. This not only eliminates - // 'undefined' and 'null', but also higher-order types such as a type parameter 'U extends undefined | null' - // that isn't eliminated by a NonNullable instantiation. - var reducedType = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* SymbolFlags.TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; } - // If the NonNullable type is available, return an instantiation. Otherwise just return the reduced type. return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? - getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : - reducedType; + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]) : + getIntersectionType([type, emptyObjectType]); } function getNonNullableType(type) { - return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; + return strictNullChecks ? getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; } function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; @@ -354983,12 +355835,13 @@ var ts; * with no call or construct signatures. */ function isObjectTypeWithInferableIndex(type) { + var objectFlags = ts.getObjectFlags(type); return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* SymbolFlags.ObjectLiteral */ | 2048 /* SymbolFlags.TypeLiteral */ | 384 /* SymbolFlags.Enum */ | 512 /* SymbolFlags.ValueModule */)) !== 0 && !(type.symbol.flags & 32 /* SymbolFlags.Class */) - && !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ObjectFlags.ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + && !typeHasCallOrConstructSignatures(type)) || !!(objectFlags & 4194304 /* ObjectFlags.ObjectRestType */) || !!(objectFlags & 1024 /* ObjectFlags.ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* CheckFlags.Readonly */); @@ -355321,27 +356174,29 @@ var ts; signature: signature, flags: flags, compareTypes: compareTypes, - mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }), - nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }), + mapper: reportUnmeasurableMapper, + nonFixingMapper: reportUnmeasurableMapper, }; + context.mapper = makeFixingMapperForContext(context); + context.nonFixingMapper = makeNonFixingMapperForContext(context); return context; } - function mapToInferredType(context, t, fix) { - var inferences = context.inferences; - for (var i = 0; i < inferences.length; i++) { - var inference = inferences[i]; - if (t === inference.typeParameter) { - if (fix && !inference.isFixed) { - // Before we commit to a particular inference (and thus lock out any further inferences), - // we infer from any intra-expression inference sites we have collected. - inferFromIntraExpressionSites(context); - clearCachedInferences(inferences); - inference.isFixed = true; - } - return getInferredType(context, i); + function makeFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (inference, i) { return function () { + if (!inference.isFixed) { + // Before we commit to a particular inference (and thus lock out any further inferences), + // we infer from any intra-expression inference sites we have collected. + inferFromIntraExpressionSites(context); + clearCachedInferences(context.inferences); + inference.isFixed = true; } - } - return t; + return getInferredType(context, i); + }; })); + } + function makeNonFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (_, i) { return function () { + return getInferredType(context, i); + }; })); } function clearCachedInferences(inferences) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { @@ -355610,13 +356465,40 @@ var ts; return sourceStart.slice(0, startLen) !== targetStart.slice(0, startLen) || sourceEnd.slice(sourceEnd.length - endLen) !== targetEnd.slice(targetEnd.length - endLen); } - function isValidBigIntString(s) { + /** + * Tests whether the provided string can be parsed as a number. + * @param s The string to test. + * @param roundTripOnly Indicates the resulting number matches the input when converted back to a string. + */ + function isValidNumberString(s, roundTripOnly) { + if (s === "") + return false; + var n = +s; + return isFinite(n) && (!roundTripOnly || "" + n === s); + } + /** + * @param text a valid bigint string excluding a trailing `n`, but including a possible prefix `-`. Use `isValidBigIntString(text, roundTripOnly)` before calling this function. + */ + function parseBigIntLiteralType(text) { + var negative = text.startsWith("-"); + var base10Value = ts.parsePseudoBigInt("".concat(negative ? text.slice(1) : text, "n")); + return getBigIntLiteralType({ negative: negative, base10Value: base10Value }); + } + /** + * Tests whether the provided string can be parsed as a bigint. + * @param s The string to test. + * @param roundTripOnly Indicates the resulting bigint matches the input when converted back to a string. + */ + function isValidBigIntString(s, roundTripOnly) { + if (s === "") + return false; var scanner = ts.createScanner(99 /* ScriptTarget.ESNext */, /*skipTrivia*/ false); var success = true; scanner.setOnError(function () { return success = false; }); scanner.setText(s + "n"); var result = scanner.scan(); - if (result === 40 /* SyntaxKind.MinusToken */) { + var negative = result === 40 /* SyntaxKind.MinusToken */; + if (negative) { result = scanner.scan(); } var flags = scanner.getTokenFlags(); @@ -355625,7 +356507,33 @@ var ts; // * a bigint can be scanned, and that when it is scanned, it is // * the full length of the input string (so the scanner is one character beyond the augmented input length) // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input) - return success && result === 9 /* SyntaxKind.BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* TokenFlags.ContainsSeparator */); + return success && result === 9 /* SyntaxKind.BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* TokenFlags.ContainsSeparator */) + && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); + } + function isMemberOfStringMapping(source, target) { + if (target.flags & (4 /* TypeFlags.String */ | 3 /* TypeFlags.AnyOrUnknown */)) { + return true; + } + if (target.flags & 134217728 /* TypeFlags.TemplateLiteral */) { + return isTypeAssignableTo(source, target); + } + if (target.flags & 268435456 /* TypeFlags.StringMapping */) { + // We need to see whether applying the same mappings of the target + // onto the source would produce an identical type *and* that + // it's compatible with the inner-most non-string-mapped type. + // + // The intuition here is that if same mappings don't affect the source at all, + // and the source is compatible with the unmapped target, then they must + // still reside in the same domain. + var mappingStack = []; + while (target.flags & 268435456 /* TypeFlags.StringMapping */) { + mappingStack.unshift(target.symbol); + target = target.type; + } + var mappedSource = ts.reduceLeft(mappingStack, function (memo, value) { return getStringMappingType(value, memo); }, source); + return mappedSource === source && isMemberOfStringMapping(source, target); + } + return false; } function isValidTypeForTemplateLiteralPlaceholder(source, target) { if (source === target || target.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */)) { @@ -355633,9 +356541,10 @@ var ts; } if (source.flags & 128 /* TypeFlags.StringLiteral */) { var value = source.value; - return !!(target.flags & 8 /* TypeFlags.Number */ && value !== "" && isFinite(+value) || - target.flags & 64 /* TypeFlags.BigInt */ && value !== "" && isValidBigIntString(value) || - target.flags & (512 /* TypeFlags.BooleanLiteral */ | 98304 /* TypeFlags.Nullable */) && value === target.intrinsicName); + return !!(target.flags & 8 /* TypeFlags.Number */ && isValidNumberString(value, /*roundTripOnly*/ false) || + target.flags & 64 /* TypeFlags.BigInt */ && isValidBigIntString(value, /*roundTripOnly*/ false) || + target.flags & (512 /* TypeFlags.BooleanLiteral */ | 98304 /* TypeFlags.Nullable */) && value === target.intrinsicName || + target.flags & 268435456 /* TypeFlags.StringMapping */ && isMemberOfStringMapping(getStringLiteralType(value), target)); } if (source.flags & 134217728 /* TypeFlags.TemplateLiteral */) { var texts = source.texts; @@ -355758,10 +356667,13 @@ var ts; propagationType = savePropagationType; return; } - if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { - // Source and target are types originating in the same generic type alias declaration. - // Simply infer from source type arguments to target type arguments. - inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + if (source.aliasSymbol && source.aliasSymbol === target.aliasSymbol) { + if (source.aliasTypeArguments) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + } + // And if there weren't any type arguments, there's no reason to run inference as the types must be the same. return; } if (source === target && source.flags & 3145728 /* TypeFlags.UnionOrIntersection */) { @@ -355817,19 +356729,30 @@ var ts; target = getActualTypeVariable(target); } if (target.flags & 8650752 /* TypeFlags.TypeVariable */) { - // If target is a type parameter, make an inference, unless the source type contains - // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). - // Because the anyFunctionType is internal, it should not be exposed to the user by adding - // it as an inference candidate. Hopefully, a better candidate will come along that does - // not contain anyFunctionType when we come back to this argument for its second round - // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard - // when constructing types from type parameters that had no inference candidates). - if (source === nonInferrableAnyType || source === silentNeverType || (priority & 128 /* InferencePriority.ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + // Skip inference if the source is "blocked", which is used by the language service to + // prevent inference on nodes currently being edited. + if (isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); if (inference) { - if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */) { + // If target is a type parameter, make an inference, unless the source type contains + // a "non-inferrable" type. Types with this flag set are markers used to prevent inference. + // + // For example: + // - anyFunctionType is a wildcard type that's used to avoid contextually typing functions; + // it's internal, so should not be exposed to the user by adding it as a candidate. + // - autoType (and autoArrayType) is a special "any" used in control flow; like anyFunctionType, + // it's internal and should not be observable. + // - silentNeverType is returned by getInferredType when instantiating a generic function for + // inference (and a type variable has no mapping). + // + // This flag is infectious; if we produce Box (where never is silentNeverType), Box is + // also non-inferrable. + // + // As a special case, also ignore nonInferrableAnyType, which is a special form of the any type + // used as a stand-in for binding elements when they are being inferred. + if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */ || source === nonInferrableAnyType) { return; } if (!inference.isFixed) { @@ -355885,15 +356808,11 @@ var ts; inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target)); } else if (source.flags & 4194304 /* TypeFlags.Index */ && target.flags & 4194304 /* TypeFlags.Index */) { - contravariant = !contravariant; - inferFromTypes(source.type, target.type); - contravariant = !contravariant; + inferFromContravariantTypes(source.type, target.type); } else if ((isLiteralType(source) || source.flags & 4 /* TypeFlags.String */) && target.flags & 4194304 /* TypeFlags.Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); - contravariant = !contravariant; - inferWithPriority(empty, target.type, 256 /* InferencePriority.LiteralKeyof */); - contravariant = !contravariant; + inferFromContravariantTypesWithPriority(empty, target.type, 256 /* InferencePriority.LiteralKeyof */); } else if (source.flags & 8388608 /* TypeFlags.IndexedAccess */ && target.flags & 8388608 /* TypeFlags.IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); @@ -355906,10 +356825,7 @@ var ts; } else if (source.flags & 33554432 /* TypeFlags.Substitution */) { inferFromTypes(source.baseType, target); - var oldPriority = priority; - priority |= 4 /* InferencePriority.SubstituteSource */; - inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority - priority = oldPriority; + inferWithPriority(source.substitute, target, 4 /* InferencePriority.SubstituteSource */); // Make substitute inference at a lower priority } else if (target.flags & 16777216 /* TypeFlags.Conditional */) { invokeOnce(source, target, inferToConditionalType); @@ -355959,6 +356875,18 @@ var ts; inferFromTypes(source, target); priority = savePriority; } + function inferFromContravariantTypesWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromContravariantTypes(source, target); + priority = savePriority; + } + function inferToMultipleTypesWithPriority(source, targets, targetFlags, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferToMultipleTypes(source, targets, targetFlags); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -356023,10 +356951,13 @@ var ts; } } function inferFromContravariantTypes(source, target) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + function inferFromContravariantTypesIfStrictFunctionTypes(source, target) { if (strictFunctionTypes || priority & 1024 /* InferencePriority.AlwaysStrict */) { - contravariant = !contravariant; - inferFromTypes(source, target); - contravariant = !contravariant; + inferFromContravariantTypes(source, target); } else { inferFromTypes(source, target); @@ -356045,8 +356976,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var type = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 /* TypeFlags.Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -356190,11 +357121,8 @@ var ts; inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } else { - var savePriority = priority; - priority |= contravariant ? 64 /* InferencePriority.ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; - inferToMultipleTypes(source, targetTypes, target.flags); - priority = savePriority; + inferToMultipleTypesWithPriority(source, targetTypes, target.flags, contravariant ? 64 /* InferencePriority.ContravariantConditional */ : 0); } } function inferToTemplateLiteralType(source, target) { @@ -356207,8 +357135,57 @@ var ts; // upon instantiation, would collapse all the placeholders to just 'string', and an assignment check might // succeed. That would be a pointless and confusing outcome. if (matches || ts.every(target.texts, function (s) { return s.length === 0; })) { + var _loop_24 = function (i) { + var source_1 = matches ? matches[i] : neverType; + var target_3 = types[i]; + // If we are inferring from a string literal type to a type variable whose constraint includes one of the + // allowed template literal placeholder types, infer from a literal type corresponding to the constraint. + if (source_1.flags & 128 /* TypeFlags.StringLiteral */ && target_3.flags & 8650752 /* TypeFlags.TypeVariable */) { + var inferenceContext = getInferenceInfoForType(target_3); + var constraint = inferenceContext ? getBaseConstraintOfType(inferenceContext.typeParameter) : undefined; + if (constraint && !isTypeAny(constraint)) { + var constraintTypes = constraint.flags & 1048576 /* TypeFlags.Union */ ? constraint.types : [constraint]; + var allTypeFlags_1 = ts.reduceLeft(constraintTypes, function (flags, t) { return flags | t.flags; }, 0); + // If the constraint contains `string`, we don't need to look for a more preferred type + if (!(allTypeFlags_1 & 4 /* TypeFlags.String */)) { + var str_1 = source_1.value; + // If the type contains `number` or a number literal and the string isn't a valid number, exclude numbers + if (allTypeFlags_1 & 296 /* TypeFlags.NumberLike */ && !isValidNumberString(str_1, /*roundTripOnly*/ true)) { + allTypeFlags_1 &= ~296 /* TypeFlags.NumberLike */; + } + // If the type contains `bigint` or a bigint literal and the string isn't a valid bigint, exclude bigints + if (allTypeFlags_1 & 2112 /* TypeFlags.BigIntLike */ && !isValidBigIntString(str_1, /*roundTripOnly*/ true)) { + allTypeFlags_1 &= ~2112 /* TypeFlags.BigIntLike */; + } + // for each type in the constraint, find the highest priority matching type + var matchingType = ts.reduceLeft(constraintTypes, function (left, right) { + return !(right.flags & allTypeFlags_1) ? left : + left.flags & 4 /* TypeFlags.String */ ? left : right.flags & 4 /* TypeFlags.String */ ? source_1 : + left.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? left : right.flags & 134217728 /* TypeFlags.TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source_1, right) ? source_1 : + left.flags & 268435456 /* TypeFlags.StringMapping */ ? left : right.flags & 268435456 /* TypeFlags.StringMapping */ && str_1 === applyStringMapping(right.symbol, str_1) ? source_1 : + left.flags & 128 /* TypeFlags.StringLiteral */ ? left : right.flags & 128 /* TypeFlags.StringLiteral */ && right.value === str_1 ? right : + left.flags & 8 /* TypeFlags.Number */ ? left : right.flags & 8 /* TypeFlags.Number */ ? getNumberLiteralType(+str_1) : + left.flags & 32 /* TypeFlags.Enum */ ? left : right.flags & 32 /* TypeFlags.Enum */ ? getNumberLiteralType(+str_1) : + left.flags & 256 /* TypeFlags.NumberLiteral */ ? left : right.flags & 256 /* TypeFlags.NumberLiteral */ && right.value === +str_1 ? right : + left.flags & 64 /* TypeFlags.BigInt */ ? left : right.flags & 64 /* TypeFlags.BigInt */ ? parseBigIntLiteralType(str_1) : + left.flags & 2048 /* TypeFlags.BigIntLiteral */ ? left : right.flags & 2048 /* TypeFlags.BigIntLiteral */ && ts.pseudoBigIntToString(right.value) === str_1 ? right : + left.flags & 16 /* TypeFlags.Boolean */ ? left : right.flags & 16 /* TypeFlags.Boolean */ ? str_1 === "true" ? trueType : str_1 === "false" ? falseType : booleanType : + left.flags & 512 /* TypeFlags.BooleanLiteral */ ? left : right.flags & 512 /* TypeFlags.BooleanLiteral */ && right.intrinsicName === str_1 ? right : + left.flags & 32768 /* TypeFlags.Undefined */ ? left : right.flags & 32768 /* TypeFlags.Undefined */ && right.intrinsicName === str_1 ? right : + left.flags & 65536 /* TypeFlags.Null */ ? left : right.flags & 65536 /* TypeFlags.Null */ && right.intrinsicName === str_1 ? right : + left; + }, neverType); + if (!(matchingType.flags & 131072 /* TypeFlags.Never */)) { + inferFromTypes(matchingType, target_3); + return "continue"; + } + } + } + } + inferFromTypes(source_1, target_3); + }; for (var i = 0; i < types.length; i++) { - inferFromTypes(matches ? matches[i] : neverType, types[i]); + _loop_24(i); } } } @@ -356322,20 +357299,17 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } } - function inferFromSignature(source, target, skipParameters) { - if (!skipParameters) { - var saveBivariant = bivariant; - var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; - // Once we descend into a bivariant signature we remain bivariant for all nested inferences - bivariant = bivariant || kind === 169 /* SyntaxKind.MethodDeclaration */ || kind === 168 /* SyntaxKind.MethodSignature */ || kind === 171 /* SyntaxKind.Constructor */; - applyToParameterTypes(source, target, inferFromContravariantTypes); - bivariant = saveBivariant; - } + function inferFromSignature(source, target) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 169 /* SyntaxKind.MethodDeclaration */ || kind === 168 /* SyntaxKind.MethodSignature */ || kind === 171 /* SyntaxKind.Constructor */; + applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes); + bivariant = saveBivariant; applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { @@ -356582,6 +357556,15 @@ var ts; var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); return key && key + "." + propName; } + break; + case 201 /* SyntaxKind.ObjectBindingPattern */: + case 202 /* SyntaxKind.ArrayBindingPattern */: + case 256 /* SyntaxKind.FunctionDeclaration */: + case 213 /* SyntaxKind.FunctionExpression */: + case 214 /* SyntaxKind.ArrowFunction */: + case 169 /* SyntaxKind.MethodDeclaration */: + // Handle pseudo-references originating in getNarrowedTypeOfSymbol. + return "".concat(getNodeId(node), "#").concat(getTypeId(declaredType)); } return undefined; } @@ -356726,7 +357709,7 @@ var ts; function mapTypesByKeyProperty(types, name) { var map = new ts.Map(); var count = 0; - var _loop_23 = function (type) { + var _loop_25 = function (type) { if (type.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */ | 58982400 /* TypeFlags.InstantiableNonPrimitive */)) { var discriminant = getTypeOfPropertyOfType(type, name); if (discriminant) { @@ -356750,9 +357733,9 @@ var ts; } } }; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - var state_9 = _loop_23(type); + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var type = types_15[_i]; + var state_9 = _loop_25(type); if (typeof state_9 === "object") return state_9.value; } @@ -356841,23 +357824,25 @@ var ts; // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - if (assignedType.flags & 131072 /* TypeFlags.Never */) { - return assignedType; - } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (assignedType.flags & 512 /* TypeFlags.BooleanLiteral */ && isFreshLiteralType(assignedType)) { - reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types - } - // Our crude heuristic produces an invalid result in some cases: see GH#26130. - // For now, when that happens, we give up and don't narrow at all. (This also - // means we'll never narrow for erroneous assignments where the assigned type - // is not assignable to the declared type.) - if (isTypeAssignableTo(assignedType, reducedType)) { - return reducedType; - } + var _a; + if (declaredType === assignedType) { + return declaredType; } - return declaredType; + if (assignedType.flags & 131072 /* TypeFlags.Never */) { + return assignedType; + } + var key = "A".concat(getTypeId(declaredType), ",").concat(getTypeId(assignedType)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType)); + } + function getAssignmentReducedTypeWorker(declaredType, assignedType) { + var filteredType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + // Ensure that we narrow to fresh types if the assignment is a fresh boolean literal type. + var reducedType = assignedType.flags & 512 /* TypeFlags.BooleanLiteral */ && isFreshLiteralType(assignedType) ? mapType(filteredType, getFreshTypeOfLiteralType) : filteredType; + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + return isTypeAssignableTo(assignedType, reducedType) ? reducedType : declaredType; } function isFunctionObjectType(type) { // We do a quick check for a "bind" property before performing the more expensive subtype @@ -356866,14 +357851,16 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type, ignoreObjects) { - if (ignoreObjects === void 0) { ignoreObjects = false; } + function getTypeFacts(type) { + if (type.flags & (2097152 /* TypeFlags.Intersection */ | 465829888 /* TypeFlags.Instantiable */)) { + type = getBaseConstraintOfType(type) || unknownType; + } var flags = type.flags; - if (flags & 4 /* TypeFlags.String */) { + if (flags & (4 /* TypeFlags.String */ | 268435456 /* TypeFlags.StringMapping */)) { return strictNullChecks ? 16317953 /* TypeFacts.StringStrictFacts */ : 16776705 /* TypeFacts.StringFacts */; } - if (flags & 128 /* TypeFlags.StringLiteral */) { - var isEmpty = type.value === ""; + if (flags & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */)) { + var isEmpty = flags & 128 /* TypeFlags.StringLiteral */ && type.value === ""; return strictNullChecks ? isEmpty ? 12123649 /* TypeFacts.EmptyStringStrictFacts */ : 7929345 /* TypeFacts.NonEmptyStringStrictFacts */ : isEmpty ? 12582401 /* TypeFacts.EmptyStringFacts */ : 16776705 /* TypeFacts.NonEmptyStringFacts */; @@ -356905,20 +357892,20 @@ var ts; (type === falseType || type === regularFalseType) ? 12580616 /* TypeFacts.FalseFacts */ : 16774920 /* TypeFacts.TrueFacts */; } if (flags & 524288 /* TypeFlags.Object */) { - if (ignoreObjects) { - return 16768959 /* TypeFacts.AndFactsMask */; // This is the identity element for computing type facts of intersection. - } return ts.getObjectFlags(type) & 16 /* ObjectFlags.Anonymous */ && isEmptyObjectType(type) ? - strictNullChecks ? 16318463 /* TypeFacts.EmptyObjectStrictFacts */ : 16777215 /* TypeFacts.EmptyObjectFacts */ : + strictNullChecks ? 83427327 /* TypeFacts.EmptyObjectStrictFacts */ : 83886079 /* TypeFacts.EmptyObjectFacts */ : isFunctionObjectType(type) ? strictNullChecks ? 7880640 /* TypeFacts.FunctionStrictFacts */ : 16728000 /* TypeFacts.FunctionFacts */ : strictNullChecks ? 7888800 /* TypeFacts.ObjectStrictFacts */ : 16736160 /* TypeFacts.ObjectFacts */; } - if (flags & (16384 /* TypeFlags.Void */ | 32768 /* TypeFlags.Undefined */)) { - return 9830144 /* TypeFacts.UndefinedFacts */; + if (flags & 16384 /* TypeFlags.Void */) { + return 9830144 /* TypeFacts.VoidFacts */; + } + if (flags & 32768 /* TypeFlags.Undefined */) { + return 26607360 /* TypeFacts.UndefinedFacts */; } if (flags & 65536 /* TypeFlags.Null */) { - return 9363232 /* TypeFacts.NullFacts */; + return 42917664 /* TypeFacts.NullFacts */; } if (flags & 12288 /* TypeFlags.ESSymbolLike */) { return strictNullChecks ? 7925520 /* TypeFacts.SymbolStrictFacts */ : 16772880 /* TypeFacts.SymbolFacts */; @@ -356929,37 +357916,56 @@ var ts; if (flags & 131072 /* TypeFlags.Never */) { return 0 /* TypeFacts.None */; } - if (flags & 465829888 /* TypeFlags.Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : - strictNullChecks ? 7929345 /* TypeFacts.NonEmptyStringStrictFacts */ : 16776705 /* TypeFacts.NonEmptyStringFacts */; - } if (flags & 1048576 /* TypeFlags.Union */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* TypeFacts.None */); + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t); }, 0 /* TypeFacts.None */); } if (flags & 2097152 /* TypeFlags.Intersection */) { - // When an intersection contains a primitive type we ignore object type constituents as they are - // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. - ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* TypeFlags.Primitive */)); - return getIntersectionTypeFacts(type, ignoreObjects); + return getIntersectionTypeFacts(type); } - return 16777215 /* TypeFacts.All */; + return 83886079 /* TypeFacts.UnknownFacts */; } - function getIntersectionTypeFacts(type, ignoreObjects) { + function getIntersectionTypeFacts(type) { + // When an intersection contains a primitive type we ignore object type constituents as they are + // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. + var ignoreObjects = maybeTypeOfKind(type, 131068 /* TypeFlags.Primitive */); // When computing the type facts of an intersection type, certain type facts are computed as `and` // and others are computed as `or`. var oredFacts = 0 /* TypeFacts.None */; - var andedFacts = 16777215 /* TypeFacts.All */; + var andedFacts = 134217727 /* TypeFacts.All */; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - var f = getTypeFacts(t, ignoreObjects); - oredFacts |= f; - andedFacts &= f; + if (!(ignoreObjects && t.flags & 524288 /* TypeFlags.Object */)) { + var f = getTypeFacts(t); + oredFacts |= f; + andedFacts &= f; + } } - return oredFacts & 8256 /* TypeFacts.OrFactsMask */ | andedFacts & 16768959 /* TypeFacts.AndFactsMask */; + return oredFacts & 8256 /* TypeFacts.OrFactsMask */ | andedFacts & 134209471 /* TypeFacts.AndFactsMask */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } + // This function is similar to getTypeWithFacts, except that in strictNullChecks mode it replaces type + // unknown with the union {} | null | undefined (and reduces that accordingly), and it intersects remaining + // instantiable types with {}, {} | null, or {} | undefined in order to remove null and/or undefined. + function getAdjustedTypeWithFacts(type, facts) { + var reduced = recombineUnknownType(getTypeWithFacts(strictNullChecks && type.flags & 2 /* TypeFlags.Unknown */ ? unknownUnionType : type, facts)); + if (strictNullChecks) { + switch (facts) { + case 524288 /* TypeFacts.NEUndefined */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 65536 /* TypeFacts.EQUndefined */ ? getIntersectionType([t, getTypeFacts(t) & 131072 /* TypeFacts.EQNull */ && !maybeTypeOfKind(reduced, 65536 /* TypeFlags.Null */) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]) : t; }); + case 1048576 /* TypeFacts.NENull */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 131072 /* TypeFacts.EQNull */ ? getIntersectionType([t, getTypeFacts(t) & 65536 /* TypeFacts.EQUndefined */ && !maybeTypeOfKind(reduced, 32768 /* TypeFlags.Undefined */) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]) : t; }); + case 2097152 /* TypeFacts.NEUndefinedOrNull */: + case 4194304 /* TypeFacts.Truthy */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 262144 /* TypeFacts.EQUndefinedOrNull */ ? getGlobalNonNullableTypeInstantiation(t) : t; }); + } + } + return reduced; + } + function recombineUnknownType(type) { + return type === unknownUnionType ? unknownType : type; + } function getTypeWithDefault(type, defaultExpression) { return defaultExpression ? getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : @@ -357114,19 +358120,17 @@ var ts; } return links.switchTypes; } - function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) { + // Get the type names from all cases in a switch on `typeof`. The default clause and/or duplicate type names are + // represented as undefined. Return undefined if one or more case clause expressions are not string literals. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + if (ts.some(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 289 /* SyntaxKind.CaseClause */ && !ts.isStringLiteralLike(clause.expression); })) { + return undefined; + } var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - if (clause.kind === 289 /* SyntaxKind.CaseClause */) { - if (ts.isStringLiteralLike(clause.expression)) { - witnesses.push(clause.expression.text); - continue; - } - return ts.emptyArray; - } - if (retainDefault) - witnesses.push(/*explicitDefaultStatement*/ undefined); + var text = clause.kind === 289 /* SyntaxKind.CaseClause */ ? clause.expression.text : undefined; + witnesses.push(text && !ts.contains(witnesses, text) ? text : undefined); } return witnesses; } @@ -357208,8 +358212,8 @@ var ts; var types = origin && origin.flags & 1048576 /* TypeFlags.Union */ ? origin.types : type.types; var mappedTypes; var changed = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; var mapped = t.flags & 1048576 /* TypeFlags.Union */ ? mapType(t, mapper, noReductions) : mapper(t); changed || (changed = t !== mapped); if (mapped) { @@ -357295,8 +358299,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (!(t.flags & 131072 /* TypeFlags.Never */)) { if (!(ts.getObjectFlags(t) & 256 /* ObjectFlags.EvolvingArray */)) { return false; @@ -357757,7 +358761,7 @@ var ts; } // for (const _ in ref) acts as a nonnull on ref if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 243 /* SyntaxKind.ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { - return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + return getNonNullableTypeIfNeeded(finalizeEvolvingArrayType(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)))); } // Assignment doesn't affect reference return undefined; @@ -358017,7 +359021,7 @@ var ts; if (isEvolvingArrayTypeList(types)) { return getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))); } - var result = getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + var result = recombineUnknownType(getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction)); if (result !== declaredType && result.flags & declaredType.flags & 1048576 /* TypeFlags.Union */ && ts.arraysEqual(result.types, declaredType.types)) { return declaredType; } @@ -358090,7 +359094,7 @@ var ts; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); - return !(narrowedPropType.flags & 131072 /* TypeFlags.Never */) && isTypeComparableTo(narrowedPropType, discriminantType); + return !(narrowedPropType.flags & 131072 /* TypeFlags.Never */) && areTypesComparable(narrowedPropType, discriminantType); }); } function narrowTypeByDiscriminantProperty(type, access, operator, value, assumeTrue) { @@ -358119,11 +359123,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return type.flags & 2 /* TypeFlags.Unknown */ && assumeTrue ? nonNullUnknownType : - getTypeWithFacts(type, assumeTrue ? 4194304 /* TypeFacts.Truthy */ : 8388608 /* TypeFacts.Falsy */); + return getAdjustedTypeWithFacts(type, assumeTrue ? 4194304 /* TypeFacts.Truthy */ : 8388608 /* TypeFacts.Falsy */); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { - type = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + type = getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -358140,7 +359143,7 @@ var ts; } function narrowByInKeyword(type, name, assumeTrue) { if (type.flags & 1048576 /* TypeFlags.Union */ - || type.flags & 524288 /* TypeFlags.Object */ && declaredType !== type + || type.flags & 524288 /* TypeFlags.Object */ && declaredType !== type && !(declaredType === unknownType && isEmptyAnonymousObjectType(type)) || ts.isThisTypeParameter(type) || type.flags & 2097152 /* TypeFlags.Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) { return filterType(type, function (t) { return isTypePresencePossible(t, name, assumeTrue); }); @@ -358245,7 +359248,7 @@ var ts; var targetType = ts.hasStaticModifier(ts.Debug.checkDefined(symbol.valueDeclaration, "should always have a declaration")) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ true); } function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows: @@ -358263,7 +359266,7 @@ var ts; // Note that we include any and unknown in the exclusion test because their domain includes null and undefined. var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) || equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* TypeFlags.AnyOrUnknown */ | nullableFlags)); }); - return removeNullable ? getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; + return removeNullable ? getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* TypeFlags.Any */) { @@ -358273,17 +359276,18 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (assumeTrue && (type.flags & 2 /* TypeFlags.Unknown */) && (operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 35 /* SyntaxKind.ExclamationEqualsToken */) && (valueType.flags & 65536 /* TypeFlags.Null */)) { - return getUnionType([nullType, undefinedType]); - } - if ((type.flags & 2 /* TypeFlags.Unknown */) && assumeTrue && (operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */ || operator === 37 /* SyntaxKind.ExclamationEqualsEqualsToken */)) { + if (((type.flags & 2 /* TypeFlags.Unknown */) || isEmptyAnonymousObjectType(type) && !(valueType.flags & 98304 /* TypeFlags.Nullable */)) && + assumeTrue && + (operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */ || operator === 37 /* SyntaxKind.ExclamationEqualsEqualsToken */)) { if (valueType.flags & (131068 /* TypeFlags.Primitive */ | 67108864 /* TypeFlags.NonPrimitive */)) { return valueType; } if (valueType.flags & 524288 /* TypeFlags.Object */) { return nonPrimitiveType; } - return type; + if (type.flags & 2 /* TypeFlags.Unknown */) { + return type; + } } if (valueType.flags & 98304 /* TypeFlags.Nullable */) { if (!strictNullChecks) { @@ -358295,7 +359299,7 @@ var ts; valueType.flags & 65536 /* TypeFlags.Null */ ? assumeTrue ? 131072 /* TypeFacts.EQNull */ : 1048576 /* TypeFacts.NENull */ : assumeTrue ? 65536 /* TypeFacts.EQUndefined */ : 524288 /* TypeFacts.NEUndefined */; - return type.flags & 2 /* TypeFlags.Unknown */ && facts & (1048576 /* TypeFacts.NENull */ | 2097152 /* TypeFacts.NEUndefinedOrNull */) ? nonNullUnknownType : getTypeWithFacts(type, facts); + return getAdjustedTypeWithFacts(type, facts); } if (assumeTrue) { var filterFn = operator === 34 /* SyntaxKind.EqualsEqualsToken */ ? @@ -358316,24 +359320,13 @@ var ts; var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { - return getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } return type; } - if (type.flags & 1 /* TypeFlags.Any */ && literal.text === "function") { - return type; - } - if (assumeTrue && type.flags & 2 /* TypeFlags.Unknown */ && literal.text === "object") { - // The non-null unknown type is used to track whether a previous narrowing operation has removed the null type - // from the unknown type. For example, the expression `x && typeof x === 'object'` first narrows x to the non-null - // unknown type, and then narrows that to the non-primitive type. - return type === nonNullUnknownType ? nonPrimitiveType : getUnionType([nonPrimitiveType, nullType]); - } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 128 /* TypeFacts.TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 32768 /* TypeFacts.TypeofNEHostObject */; - var impliedType = getImpliedTypeFromTypeofGuard(type, literal.text); - return getTypeWithFacts(assumeTrue && impliedType ? mapType(type, narrowUnionMemberByTypeof(impliedType)) : type, facts); + return assumeTrue ? + narrowTypeByTypeName(type, literal.text) : + getTypeWithFacts(type, typeofNEFacts.get(literal.text) || 32768 /* TypeFacts.TypeofNEHostObject */); } function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); @@ -358380,97 +359373,52 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); }); return caseType.flags & 131072 /* TypeFlags.Never */ ? defaultType : getUnionType([caseType, defaultType]); } - function getImpliedTypeFromTypeofGuard(type, text) { - switch (text) { - case "function": - return type.flags & 1 /* TypeFlags.Any */ ? type : globalFunctionType; - case "object": - return type.flags & 2 /* TypeFlags.Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; - default: - return typeofTypesByName.get(text); - } - } - // When narrowing a union type by a `typeof` guard using type-facts alone, constituent types that are - // super-types of the implied guard will be retained in the final type: this is because type-facts only - // filter. Instead, we would like to replace those union constituents with the more precise type implied by - // the guard. For example: narrowing `{} | undefined` by `"boolean"` should produce the type `boolean`, not - // the filtered type `{}`. For this reason we narrow constituents of the union individually, in addition to - // filtering by type-facts. - function narrowUnionMemberByTypeof(candidate) { - return function (type) { - if (isTypeSubtypeOf(type, candidate)) { - return type; - } - if (isTypeSubtypeOf(candidate, type)) { - return candidate; - } - if (type.flags & 465829888 /* TypeFlags.Instantiable */) { - var constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(candidate, constraint)) { - return getIntersectionType([type, candidate]); - } - } - return type; - }; + function narrowTypeByTypeName(type, typeName) { + switch (typeName) { + case "string": return narrowTypeByTypeFacts(type, stringType, 1 /* TypeFacts.TypeofEQString */); + case "number": return narrowTypeByTypeFacts(type, numberType, 2 /* TypeFacts.TypeofEQNumber */); + case "bigint": return narrowTypeByTypeFacts(type, bigintType, 4 /* TypeFacts.TypeofEQBigInt */); + case "boolean": return narrowTypeByTypeFacts(type, booleanType, 8 /* TypeFacts.TypeofEQBoolean */); + case "symbol": return narrowTypeByTypeFacts(type, esSymbolType, 16 /* TypeFacts.TypeofEQSymbol */); + case "object": return type.flags & 1 /* TypeFlags.Any */ ? type : getUnionType([narrowTypeByTypeFacts(type, nonPrimitiveType, 32 /* TypeFacts.TypeofEQObject */), narrowTypeByTypeFacts(type, nullType, 131072 /* TypeFacts.EQNull */)]); + case "function": return type.flags & 1 /* TypeFlags.Any */ ? type : narrowTypeByTypeFacts(type, globalFunctionType, 64 /* TypeFacts.TypeofEQFunction */); + case "undefined": return narrowTypeByTypeFacts(type, undefinedType, 65536 /* TypeFacts.EQUndefined */); + } + return narrowTypeByTypeFacts(type, nonPrimitiveType, 128 /* TypeFacts.TypeofEQHostObject */); + } + function narrowTypeByTypeFacts(type, impliedType, facts) { + return mapType(type, function (t) { + // We first check if a constituent is a subtype of the implied type. If so, we either keep or eliminate + // 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`. + return isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? getTypeFacts(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; + }); } function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { - var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true); - if (!switchWitnesses.length) { + var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!witnesses) { return type; } - // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause - var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); - var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); - var clauseWitnesses; - var switchFacts; - if (defaultCaseLocation > -1) { - // We no longer need the undefined denoting an explicit default case. Remove the undefined and - // fix-up clauseStart and clauseEnd. This means that we don't have to worry about undefined in the - // witness array. - var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); - // The adjusted clause start and end after removing the `default` statement. - var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; - var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; - clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); - switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); - } - else { - clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); - switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); - } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause. + var defaultIndex = ts.findIndex(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 290 /* SyntaxKind.DefaultClause */; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultIndex >= clauseStart && defaultIndex < clauseEnd); if (hasDefaultClause) { - return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + // In the default clause we filter constituents down to those that are not-equal to all handled cases. + var notEqualFacts_1 = getNotEqualFactsFromTypeofSwitch(clauseStart, clauseEnd, witnesses); + return filterType(type, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }); } - /* - The implied type is the raw type suggested by a - value being caught in this clause. - - When the clause contains a default case we ignore - the implied type and try to narrow using any facts - we can learn: see `switchFacts`. - - Example: - switch (typeof x) { - case 'number': - case 'string': break; - default: break; - case 'number': - case 'boolean': break - } - - In the first clause (case `number` and `string`) the - implied type is number | string. - - In the default clause we de not compute an implied type. - - In the third clause (case `number` and `boolean`) - the naive implied type is number | boolean, however - we use the type facts to narrow the implied type to - boolean. We know that number cannot be selected - because it is caught in the first clause. - */ - var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofGuard(type, text) || type; })), switchFacts); - return getTypeWithFacts(mapType(type, narrowUnionMemberByTypeof(impliedType)), switchFacts); + // In the non-default cause we create a union of the type narrowed by each of the listed cases. + var clauseWitnesses = witnesses.slice(clauseStart, clauseEnd); + return getUnionType(ts.map(clauseWitnesses, function (text) { return text ? narrowTypeByTypeName(type, text) : neverType; })); } function isMatchingConstructorReference(expr) { return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || @@ -358521,7 +359469,7 @@ var ts; var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { - return getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } return type; } @@ -358555,29 +359503,48 @@ var ts; if (!nonConstructorTypeInUnion) return type; } - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ true); } - function getNarrowedType(type, candidate, assumeTrue, isRelated) { + function getNarrowedType(type, candidate, assumeTrue, checkDerived) { + var _a; + var key = type.flags & 1048576 /* TypeFlags.Union */ ? "N".concat(getTypeId(type), ",").concat(getTypeId(candidate), ",").concat((assumeTrue ? 1 : 0) | (checkDerived ? 2 : 0)) : undefined; + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived)); + } + function getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived) { + var isRelated = checkDerived ? isTypeDerivedFrom : isTypeSubtypeOf; if (!assumeTrue) { return filterType(type, function (t) { return !isRelated(t, candidate); }); } - // If the current type is a union type, remove all constituents that couldn't be instances of - // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 1048576 /* TypeFlags.Union */) { - var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 131072 /* TypeFlags.Never */)) { - return assignableType; - } + if (type.flags & 3 /* TypeFlags.AnyOrUnknown */) { + return candidate; } - // If the candidate type is a subtype of the target type, narrow to the candidate type. - // Otherwise, if the target type is assignable to the candidate type, keep the target type. - // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate - // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the - // two types. - return isTypeSubtypeOf(candidate, type) ? candidate : - isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); + // We first attempt to filter the current type, narrowing constituents as appropriate and removing + // constituents that are unrelated to the candidate. + var keyPropertyName = type.flags & 1048576 /* TypeFlags.Union */ ? getKeyPropertyName(type) : undefined; + var narrowedType = mapType(candidate, function (c) { + // If a discriminant property is available, use that to reduce the type. + var discriminant = keyPropertyName && getTypeOfPropertyOfType(c, keyPropertyName); + var matching = discriminant && getConstituentTypeForKeyType(type, discriminant); + // For each constituent t in the current type, if t and and c are directly related, pick the most + // specific of the two. When t and c are related in both directions, we prefer c for type predicates + // because that is the asserted type, but t for `instanceof` because generics aren't reflected in + // prototype object types. + var directlyRelated = mapType(matching || type, checkDerived ? + function (t) { return isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType; } : + function (t) { return isTypeSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : neverType; }); + // If no constituents are directly related, create intersections for any generic constituents that + // are related by constraint. + return directlyRelated.flags & 131072 /* TypeFlags.Never */ ? + mapType(type, function (t) { return maybeTypeOfKind(t, 465829888 /* TypeFlags.Instantiable */) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType; }) : + directlyRelated; + }); + // If filtering produced a non-empty type, return that. Otherwise, pick the most specific of the two + // based on assignability, or as a last resort produce an intersection. + return !(narrowedType.flags & 131072 /* TypeFlags.Never */) ? narrowedType : + isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -358605,15 +359572,15 @@ var ts; var predicateArgument = getTypePredicateArgument(predicate, callExpression); if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + return getNarrowedType(type, predicate.type, assumeTrue, /*checkDerived*/ false); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && !(getTypeFacts(predicate.type) & 65536 /* TypeFacts.EQUndefined */)) { - type = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + type = getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(predicateArgument, type); if (access) { - return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); + return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, /*checkDerived*/ false); }); } } } @@ -358666,7 +359633,7 @@ var ts; } function narrowTypeByOptionality(type, expr, assumePresent) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumePresent ? 2097152 /* TypeFacts.NEUndefinedOrNull */ : 262144 /* TypeFacts.EQUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, assumePresent ? 2097152 /* TypeFacts.NEUndefinedOrNull */ : 262144 /* TypeFacts.EQUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -358752,8 +359719,8 @@ var ts; var annotationIncludesUndefined = strictNullChecks && declaration.kind === 164 /* SyntaxKind.Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 32768 /* TypeFlags.Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* TypeFlags.Undefined */); + getTypeFacts(declaredType) & 16777216 /* TypeFacts.IsUndefined */ && + !(getTypeFacts(checkExpression(declaration.initializer)) & 16777216 /* TypeFacts.IsUndefined */); popTypeResolution(); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* TypeFacts.NEUndefined */) : declaredType; } @@ -358774,10 +359741,14 @@ var ts; !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { - return !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* TypeFlags.Nullable */ | 1048576 /* TypeFlags.Union */)); + return type.flags & 2097152 /* TypeFlags.Intersection */ ? + ts.some(type.types, isGenericTypeWithUnionConstraint) : + !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* TypeFlags.Nullable */ | 1048576 /* TypeFlags.Union */)); } function isGenericTypeWithoutNullableConstraint(type) { - return !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* TypeFlags.Nullable */)); + return type.flags & 2097152 /* TypeFlags.Intersection */ ? + ts.some(type.types, isGenericTypeWithoutNullableConstraint) : + !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* TypeFlags.Nullable */)); } function hasContextualTypeWithNoGenericTypes(node, checkMode) { // Computing the contextual type for a child of a JSX element involves resolving the type of the @@ -358788,7 +359759,7 @@ var ts; !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 64 /* CheckMode.RestBindingElement */ ? getContextualType(node, 8 /* ContextFlags.SkipBindingPatterns */) - : getContextualType(node)); + : getContextualType(node, /*contextFlags*/ undefined)); return contextualType && !isGenericType(contextualType); } function getNarrowableTypeForReference(type, reference, checkMode) { @@ -358802,7 +359773,7 @@ var ts; var substituteConstraints = !(checkMode && checkMode & 2 /* CheckMode.Inferential */) && someType(type, isGenericTypeWithUnionConstraint) && (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode)); - return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* TypeFlags.Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; + return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type; } function isExportOrExportExpression(location) { return !!ts.findAncestor(location, function (n) { @@ -358950,9 +359921,7 @@ var ts; getNodeLinks(container).flags |= 8192 /* NodeCheckFlags.CaptureArguments */; return getTypeOfSymbol(symbol); } - // We should only mark aliases as referenced if there isn't a local value declaration - // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that - if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + if (shouldMarkIdentifierAliasReferenced(node)) { markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); @@ -359079,13 +360048,32 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */) && getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */) { + else if (!assumeInitialized && !containsUndefinedType(type) && containsUndefinedType(flowType)) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function shouldMarkIdentifierAliasReferenced(node) { + var _a; + var parent = node.parent; + if (parent) { + // A property access expression LHS? checkPropertyAccessExpression will handle that. + if (ts.isPropertyAccessExpression(parent) && parent.expression === node) { + return false; + } + // Next two check for an identifier inside a type only export. + if (ts.isExportSpecifier(parent) && parent.isTypeOnly) { + return false; + } + var greatGrandparent = (_a = parent.parent) === null || _a === void 0 ? void 0 : _a.parent; + if (greatGrandparent && ts.isExportDeclaration(greatGrandparent) && greatGrandparent.isTypeOnly) { + return false; + } + } + return true; + } function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); }); } @@ -359213,7 +360201,7 @@ var ts; } function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression, container) { if (ts.isPropertyDeclaration(container) && ts.hasStaticModifier(container) && - container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.length(container.parent.decorators)) { + container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.hasDecorators(container.parent)) { error(thisExpression, ts.Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); } } @@ -359635,7 +360623,7 @@ var ts; // We have an object literal method. Check if the containing object literal has a contextual type // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in // any directly enclosing object literals. - var contextualType = getApparentTypeOfContextualType(containingLiteral); + var contextualType = getApparentTypeOfContextualType(containingLiteral, /*contextFlags*/ undefined); var literal = containingLiteral; var type = contextualType; while (type) { @@ -359647,7 +360635,7 @@ var ts; break; } literal = literal.parent.parent; - type = getApparentTypeOfContextualType(literal); + type = getApparentTypeOfContextualType(literal, /*contextFlags*/ undefined); } // There was no contextual ThisType for the containing object literal, so the contextual type // for 'this' is the non-null form of the contextual type for the containing object literal or @@ -359704,7 +360692,7 @@ var ts; tryGetTypeAtPosition(contextualSignature, index); } } - function getContextualTypeForVariableLikeDeclaration(declaration) { + function getContextualTypeForVariableLikeDeclaration(declaration, contextFlags) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); @@ -359713,18 +360701,18 @@ var ts; case 164 /* SyntaxKind.Parameter */: return getContextuallyTypedParameterType(declaration); case 203 /* SyntaxKind.BindingElement */: - return getContextualTypeForBindingElement(declaration); + return getContextualTypeForBindingElement(declaration, contextFlags); case 167 /* SyntaxKind.PropertyDeclaration */: if (ts.isStatic(declaration)) { - return getContextualTypeForStaticPropertyDeclaration(declaration); + return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags); } // By default, do nothing and return undefined - only the above cases have context implied by a parent } } - function getContextualTypeForBindingElement(declaration) { + function getContextualTypeForBindingElement(declaration, contextFlags) { var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - var parentType = getContextualTypeForVariableLikeDeclaration(parent) || + var parentType = getContextualTypeForVariableLikeDeclaration(parent, contextFlags) || parent.kind !== 203 /* SyntaxKind.BindingElement */ && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 64 /* CheckMode.RestBindingElement */ : 0 /* CheckMode.Normal */); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; @@ -359740,8 +360728,8 @@ var ts; return getTypeOfPropertyOfType(parentType, text); } } - function getContextualTypeForStaticPropertyDeclaration(declaration) { - var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent); + function getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags) { + var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent, contextFlags); if (!parentType) return undefined; return getTypeOfPropertyOfContextualType(parentType, getSymbolOfNode(declaration).escapedName); @@ -359757,29 +360745,32 @@ var ts; function getContextualTypeForInitializerExpression(node, contextFlags) { var declaration = node.parent; if (ts.hasInitializer(declaration) && node === declaration.initializer) { - var result = getContextualTypeForVariableLikeDeclaration(declaration); + var result = getContextualTypeForVariableLikeDeclaration(declaration, contextFlags); if (result) { return result; } - if (!(contextFlags & 8 /* ContextFlags.SkipBindingPatterns */) && ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable + if (!(contextFlags & 8 /* ContextFlags.SkipBindingPatterns */) && ts.isBindingPattern(declaration.name) && declaration.name.elements.length > 0) { return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } } return undefined; } - function getContextualTypeForReturnExpression(node) { + function getContextualTypeForReturnExpression(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { var functionFlags = ts.getFunctionFlags(func); if (functionFlags & 1 /* FunctionFlags.Generator */) { // Generator or AsyncGenerator function - var use = functionFlags & 2 /* FunctionFlags.Async */ ? 2 /* IterationUse.AsyncGeneratorReturnType */ : 1 /* IterationUse.GeneratorReturnType */; - var iterationTypes = getIterationTypesOfIterable(contextualReturnType, use, /*errorNode*/ undefined); - if (!iterationTypes) { + var isAsyncGenerator_1 = (functionFlags & 2 /* FunctionFlags.Async */) !== 0; + if (contextualReturnType.flags & 1048576 /* TypeFlags.Union */) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, type, isAsyncGenerator_1); }); + } + var iterationReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, contextualReturnType, (functionFlags & 2 /* FunctionFlags.Async */) !== 0); + if (!iterationReturnType) { return undefined; } - contextualReturnType = iterationTypes.returnType; + contextualReturnType = iterationReturnType; // falls through to unwrap Promise for AsyncGenerators } if (functionFlags & 2 /* FunctionFlags.Async */) { // Async function or AsyncGenerator function @@ -359800,15 +360791,19 @@ var ts; } return undefined; } - function getContextualTypeForYieldOperand(node) { + function getContextualTypeForYieldOperand(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { var functionFlags = ts.getFunctionFlags(func); - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { + var isAsyncGenerator_2 = (functionFlags & 2 /* FunctionFlags.Async */) !== 0; + if (!node.asteriskToken && contextualReturnType.flags & 1048576 /* TypeFlags.Union */) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, type, isAsyncGenerator_2); }); + } return node.asteriskToken ? contextualReturnType - : getIterationTypeOfGeneratorFunctionReturnType(0 /* IterationTypeKind.Yield */, contextualReturnType, (functionFlags & 2 /* FunctionFlags.Async */) !== 0); + : getIterationTypeOfGeneratorFunctionReturnType(0 /* IterationTypeKind.Yield */, contextualReturnType, isAsyncGenerator_2); } } return undefined; @@ -359828,14 +360823,14 @@ var ts; } function getContextualIterationType(kind, functionDecl) { var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* FunctionFlags.Async */); - var contextualReturnType = getContextualReturnType(functionDecl); + var contextualReturnType = getContextualReturnType(functionDecl, /*contextFlags*/ undefined); if (contextualReturnType) { return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync) || undefined; } return undefined; } - function getContextualReturnType(functionDecl) { + function getContextualReturnType(functionDecl, contextFlags) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed var returnType = getReturnTypeFromAnnotation(functionDecl); @@ -359850,7 +360845,7 @@ var ts; } var iife = ts.getImmediatelyInvokedFunctionExpression(functionDecl); if (iife) { - return getContextualType(iife); + return getContextualType(iife, contextFlags); } return undefined; } @@ -359924,6 +360919,14 @@ var ts; var lhsType = getTypeOfExpression(e.expression); return ts.isPrivateIdentifier(e.name) ? tryGetPrivateIdentifierPropertyOfType(lhsType, e.name) : getPropertyOfType(lhsType, e.name.escapedText); } + if (ts.isElementAccessExpression(e)) { + var propType = checkExpressionCached(e.argumentExpression); + if (!isTypeUsableAsPropertyName(propType)) { + return undefined; + } + var lhsType = getTypeOfExpression(e.expression); + return getPropertyOfType(lhsType, getPropertyNameFromType(propType)); + } return undefined; function tryGetPrivateIdentifierPropertyOfType(type, id) { var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(id.escapedText, id); @@ -359945,7 +360948,7 @@ var ts; if (decl && (ts.isPropertyDeclaration(decl) || ts.isPropertySignature(decl))) { var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); return (overallAnnotation && instantiateType(getTypeFromTypeNode(overallAnnotation), getSymbolLinks(lhsSymbol).mapper)) || - (decl.initializer && getTypeOfExpression(binaryExpression.left)); + (ts.isPropertyDeclaration(decl) ? decl.initializer && getTypeOfExpression(binaryExpression.left) : undefined); } if (kind === 0 /* AssignmentDeclarationKind.None */) { return getTypeOfExpression(binaryExpression.left); @@ -360078,7 +361081,7 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; - var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element, contextFlags); if (propertyAssignmentType) { return propertyAssignmentType; } @@ -360113,8 +361116,8 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined; } - function getContextualTypeForChildJsxExpression(node, child) { - var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + function getContextualTypeForChildJsxExpression(node, child, contextFlags) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName, contextFlags); // JSX expression is in children of JSX Element, we will look for an "children" attribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { @@ -360132,27 +361135,27 @@ var ts; } }, /*noReductions*/ true)); } - function getContextualTypeForJsxExpression(node) { + function getContextualTypeForJsxExpression(node, contextFlags) { var exprParent = node.parent; return ts.isJsxAttributeLike(exprParent) - ? getContextualType(node) + ? getContextualType(node, contextFlags) : ts.isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent, node) + ? getContextualTypeForChildJsxExpression(exprParent, node, contextFlags) : undefined; } - function getContextualTypeForJsxAttribute(attribute) { + function getContextualTypeForJsxAttribute(attribute, contextFlags) { // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type // which is a type of the parameter of the signature we are trying out. // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName if (ts.isJsxAttribute(attribute)) { - var attributesType = getApparentTypeOfContextualType(attribute.parent); + var attributesType = getApparentTypeOfContextualType(attribute.parent, contextFlags); if (!attributesType || isTypeAny(attributesType)) { return undefined; } return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { - return getContextualType(attribute.parent); + return getContextualType(attribute.parent, contextFlags); } } // Return true if the given expression is possibly a discriminant value. We limit the kinds of @@ -360205,22 +361208,20 @@ var ts; var inferenceContext = getInferenceContext(node); // If no inferences have been made, nothing is gained from instantiating as type parameters // would just be replaced with their defaults similar to the apparent type. - if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { // For contextual signatures we incorporate all inferences made so far, e.g. from return // types as well as arguments to the left in a function call. - if (contextFlags && contextFlags & 1 /* ContextFlags.Signature */) { - return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); - } + return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); + } + if (inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.returnMapper) { // For other purposes (e.g. determining whether to produce literal types) we only // incorporate inferences made from the return type in a function call. We remove // the 'boolean' type from the contextual type such that contextually typed boolean // literals actually end up widening to 'boolean' (see #48363). - if (inferenceContext.returnMapper) { - var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); - return type.flags & 1048576 /* TypeFlags.Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? - filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : - type; - } + var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); + return type.flags & 1048576 /* TypeFlags.Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? + filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : + type; } } return contextualType; @@ -360275,9 +361276,9 @@ var ts; return getContextualTypeForInitializerExpression(node, contextFlags); case 214 /* SyntaxKind.ArrowFunction */: case 247 /* SyntaxKind.ReturnStatement */: - return getContextualTypeForReturnExpression(node); + return getContextualTypeForReturnExpression(node, contextFlags); case 224 /* SyntaxKind.YieldExpression */: - return getContextualTypeForYieldOperand(parent); + return getContextualTypeForYieldOperand(parent, contextFlags); case 218 /* SyntaxKind.AwaitExpression */: return getContextualTypeForAwaitOperand(parent, contextFlags); case 208 /* SyntaxKind.CallExpression */: @@ -360315,17 +361316,17 @@ var ts; case 271 /* SyntaxKind.ExportAssignment */: return tryGetTypeFromEffectiveTypeNode(parent); case 288 /* SyntaxKind.JsxExpression */: - return getContextualTypeForJsxExpression(parent); + return getContextualTypeForJsxExpression(parent, contextFlags); case 285 /* SyntaxKind.JsxAttribute */: case 287 /* SyntaxKind.JsxSpreadAttribute */: - return getContextualTypeForJsxAttribute(parent); + return getContextualTypeForJsxAttribute(parent, contextFlags); case 280 /* SyntaxKind.JsxOpeningElement */: case 279 /* SyntaxKind.JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; function tryFindWhenConstTypeReference(node) { - return getContextualType(node); + return getContextualType(node, contextFlags); } } function getInferenceContext(node) { @@ -360585,8 +361586,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var current = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var current = types_18[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -360627,7 +361628,7 @@ var ts; var elementCount = elements.length; var elementTypes = []; var elementFlags = []; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ undefined); var inDestructuringPattern = ts.isAssignmentTarget(node); var inConstContext = isConstContext(node); var hasOmittedExpression = false; @@ -360798,7 +361799,7 @@ var ts; var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; var spread = emptyObjectType; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ undefined); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 201 /* SyntaxKind.ObjectBindingPattern */ || contextualType.pattern.kind === 205 /* SyntaxKind.ObjectLiteralExpression */); var inConstContext = isConstContext(node); @@ -361137,7 +362138,7 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes, /*contextFlags*/ undefined); var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* SymbolFlags.Property */, jsxChildrenPropertyName); @@ -361748,19 +362749,19 @@ var ts; return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { - return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* TypeFlags.Nullable */); + return !!(getTypeFacts(type) & 50331648 /* TypeFacts.IsUndefinedOrNull */); } function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function reportObjectPossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 /* TypeFlags.Undefined */ ? flags & 65536 /* TypeFlags.Null */ ? + function reportObjectPossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); } - function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 /* TypeFlags.Undefined */ ? flags & 65536 /* TypeFlags.Null */ ? + function reportCannotInvokePossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); @@ -361770,9 +362771,9 @@ var ts; error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* TypeFlags.Nullable */; - if (kind) { - reportError(node, kind); + var facts = getTypeFacts(type); + if (facts & 50331648 /* TypeFacts.IsUndefinedOrNull */) { + reportError(node, facts); var t = getNonNullableType(type); return t.flags & (98304 /* TypeFlags.Nullable */ | 131072 /* TypeFlags.Never */) ? errorType : t; } @@ -361941,9 +362942,8 @@ var ts; markAliasReferenced(parentSymbol, node); } return isErrorType(apparentType) ? errorType : apparentType; - ; } - prop = getPropertyOfType(apparentType, right.escapedText); + prop = getPropertyOfType(apparentType, right.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ node.kind === 161 /* SyntaxKind.QualifiedName */); } // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. // `Foo` is also not referenced in `enum FooCopy { Bar = Foo.Bar }`, because the enum member value gets inlined @@ -362068,7 +363068,7 @@ var ts; assumeUninitialized = true; } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* TypeFlags.Undefined */) && getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */) { + if (assumeUninitialized && !containsUndefinedType(propType) && containsUndefinedType(flowType)) { error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; @@ -362251,9 +363251,9 @@ var ts; function getSuggestedSymbolForNonexistentProperty(name, containingType) { var props = getPropertiesOfType(containingType); if (typeof name !== "string") { - var parent_2 = name.parent; - if (ts.isPropertyAccessExpression(parent_2)) { - props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); }); + var parent_3 = name.parent; + if (ts.isPropertyAccessExpression(parent_3)) { + props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_3, containingType, prop); }); } name = ts.idText(name); } @@ -362755,29 +363755,43 @@ var ts; // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. if (node.kind !== 165 /* SyntaxKind.Decorator */) { - var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* ContextFlags.SkipBindingPatterns */ : 0 /* ContextFlags.None */); + var skipBindingPatterns = ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }); + var contextualType = getContextualType(node, skipBindingPatterns ? 8 /* ContextFlags.SkipBindingPatterns */ : 0 /* ContextFlags.None */); if (contextualType) { var inferenceTargetType = getReturnTypeOfSignature(signature); if (couldContainTypeVariables(inferenceTargetType)) { - // We clone the inference context to avoid disturbing a resolution in progress for an - // outer call expression. Effectively we just want a snapshot of whatever has been - // inferred for any outer call expression so far. var outerContext = getInferenceContext(node); - var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* InferenceFlags.NoDefault */)); - var instantiatedType = instantiateType(contextualType, outerMapper); - // If the contextual type is a generic function type with a single call signature, we - // instantiate the type with its own type parameters and type arguments. This ensures that - // the type parameters are not erased to type any during type inference such that they can - // be inferred as actual types from the contextual type. For example: - // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; - // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); - // Above, the type of the 'value' parameter is inferred to be 'A'. - var contextualSignature = getSingleCallSignature(instantiatedType); - var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : - instantiatedType; - // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* InferencePriority.ReturnType */); + var isFromBindingPattern = !skipBindingPatterns && getContextualType(node, 8 /* ContextFlags.SkipBindingPatterns */) !== contextualType; + // A return type inference from a binding pattern can be used in instantiating the contextual + // type of an argument later in inference, but cannot stand on its own as the final return type. + // It is incorporated into `context.returnMapper` which is used in `instantiateContextualType`, + // but doesn't need to go into `context.inferences`. This allows a an array binding pattern to + // produce a tuple for `T` in + // declare function f(cb: () => T): T; + // const [e1, e2, e3] = f(() => [1, "hi", true]); + // but does not produce any inference for `T` in + // declare function f(): T; + // const [e1, e2, e3] = f(); + if (!isFromBindingPattern) { + // We clone the inference context to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. + var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* InferenceFlags.NoDefault */)); + var instantiatedType = instantiateType(contextualType, outerMapper); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* InferencePriority.ReturnType */); + } // Create a type mapper for instantiating generic contextual types using the inferences made // from the return type. We need a separate inference pass here because (a) instantiation of // the source type uses the outer context's return mapper (which excludes inferences made from @@ -363104,7 +364118,7 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_24 = function (i) { + var _loop_26 = function (i) { var arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. var spreadType = arg.kind === 225 /* SyntaxKind.SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); @@ -363121,7 +364135,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_24(i); + _loop_26(i); } return effectiveArgs_1; } @@ -363328,7 +364342,7 @@ var ts; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray; var typeArguments; - if (!isDecorator) { + if (!isDecorator && !ts.isSuperCall(node)) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 106 /* SyntaxKind.SuperKeyword */) { @@ -363407,6 +364421,15 @@ var ts; if (result) { return result; } + result = getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + // Preemptively cache the result; getResolvedSignature will do this after we return, but + // we need to ensure that the result is present for the error checks below so that if + // this signature is encountered again, we handle the circularity (rather than producing a + // different result which may produce no errors and assert). Callers of getResolvedSignature + // don't hit this issue because they only observe this result after it's had a chance to + // be cached, but the error reporting code below executes before getResolvedSignature sets + // resolvedSignature. + getNodeLinks(node).resolvedSignature = result; // No signatures were applicable. Now report errors based on the last applicable signature with // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, @@ -363441,7 +364464,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_25 = function (c) { + var _loop_27 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* CheckMode.Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -363459,7 +364482,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_25(c); + _loop_27(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); @@ -363498,7 +364521,7 @@ var ts; } } } - return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + return result; function addImplementationSuccessElaboration(failed, diagnostic) { var _a, _b; var oldCandidatesForArgumentError = candidatesForArgumentError; @@ -363578,7 +364601,7 @@ var ts; argCheckMode = checkMode & 32 /* CheckMode.IsForStringLiteralArgumentCompletions */; if (inferenceContext) { var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext); - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext.inferredTypeParameters); // If the original signature has a generic rest type, instantiation may produce a // signature with different arity and we need to perform another arity check. if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { @@ -363617,7 +364640,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_26 = function (i) { + var _loop_28 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -363625,7 +364648,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_26(i); + _loop_28(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* SignatureFlags.None */; @@ -363793,7 +364816,7 @@ var ts; // returns a function type, we choose to defer processing. This narrowly permits function composition // operators to flow inferences through return types, but otherwise processes calls right away. We // use the resolvingSignature singleton to indicate that we deferred processing. This result will be - // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and + // propagated out and eventually turned into silentNeverType (a type that is assignable to anything and // from which we never make inferences). if (checkMode & 8 /* CheckMode.SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) { skippedGenericFunction(node, checkMode); @@ -363970,8 +364993,8 @@ var ts; if (apparentType.flags & 1048576 /* TypeFlags.Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var constituent = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var constituent = types_19[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -364137,7 +365160,7 @@ var ts; // file would probably be preferable. var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* SymbolFlags.Type */); var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* SymbolFlags.Type */, node); - var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); + var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); var parameterSymbol = createSymbol(1 /* SymbolFlags.FunctionScopedVariable */, "props"); parameterSymbol.type = result; return createSignature(declaration, @@ -364346,8 +365369,8 @@ var ts; var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode); if (signature === resolvingSignature) { // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that - // returns a function type. We defer checking and return nonInferrableType. - return nonInferrableType; + // returns a function type. We defer checking and return silentNeverType. + return silentNeverType; } checkDeprecatedSignature(signature, node); if (node.expression.kind === 106 /* SyntaxKind.SuperKeyword */) { @@ -364955,17 +365978,6 @@ var ts; } } } - var restType = getEffectiveRestType(context); - if (restType && restType.flags & 262144 /* TypeFlags.TypeParameter */) { - // The contextual signature has a generic rest parameter. We first instantiate the contextual - // signature (without fixing type parameters) and assign types to contextually typed parameters. - var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper); - assignContextualParameterTypes(signature, instantiatedContext); - // We then infer from a tuple type representing the parameters that correspond to the contextual - // rest parameter. - var restPos = getParameterCount(context) - 1; - inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType); - } } function assignContextualParameterTypes(signature, context) { if (context.typeParameters) { @@ -365158,7 +366170,7 @@ var ts; var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : - instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); + instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func, /*contextFlags*/ undefined); if (isGenerator) { yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* IterationTypeKind.Yield */, isAsync); returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* IterationTypeKind.Return */, isAsync); @@ -365229,7 +366241,7 @@ var ts; nextType = iterationTypes && iterationTypes.nextType; } else { - nextType = getContextualType(yieldExpression); + nextType = getContextualType(yieldExpression, /*contextFlags*/ undefined); } if (nextType) ts.pushIfUnique(nextTypes, nextType); @@ -365244,45 +366256,12 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - /** - * Collect the TypeFacts learned from a typeof switch with - * total clauses `witnesses`, and the active clause ranging - * from `start` to `end`. Parameter `hasDefault` denotes - * whether the active clause contains a default clause. - */ - function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + // Return the combined not-equal type facts for all cases except those between the start and end indices. + function getNotEqualFactsFromTypeofSwitch(start, end, witnesses) { var facts = 0 /* TypeFacts.None */; - // When in the default we only collect inequality facts - // because default is 'in theory' a set of infinite - // equalities. - if (hasDefault) { - // Value is not equal to any types after the active clause. - for (var i = end; i < witnesses.length; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeFacts.TypeofNEHostObject */; - } - // Remove inequalities for types that appear in the - // active clause because they appear before other - // types collected so far. - for (var i = start; i < end; i++) { - facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); - } - // Add inequalities for types before the active clause unconditionally. - for (var i = 0; i < start; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeFacts.TypeofNEHostObject */; - } - } - // When in an active clause without default the set of - // equalities is finite. - else { - // Add equalities for all types in the active clause. - for (var i = start; i < end; i++) { - facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeFacts.TypeofEQHostObject */; - } - // Remove equalities for types that appear before the - // active clause. - for (var i = 0; i < start; i++) { - facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); - } + for (var i = 0; i < witnesses.length; i++) { + var witness = i < start || i >= end ? witnesses[i] : undefined; + facts |= witness !== undefined ? typeofNEFacts.get(witness) || 32768 /* TypeFacts.TypeofNEHostObject */ : 0; } return facts; } @@ -365292,16 +366271,19 @@ var ts; } function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 216 /* SyntaxKind.TypeOfExpression */) { - var operandType = getTypeOfExpression(node.expression.expression); - var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); - // notEqualFacts states that the type of the switched value is not equal to every type in the switch. - var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_6 = getBaseConstraintOfType(operandType) || operandType; - // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types. - if (type_6.flags & 3 /* TypeFlags.AnyOrUnknown */) { - return (556800 /* TypeFacts.AllTypeofNE */ & notEqualFacts_1) === 556800 /* TypeFacts.AllTypeofNE */; + var witnesses = getSwitchClauseTypeOfWitnesses(node); + if (!witnesses) { + return false; + } + var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(node.expression.expression)); + // Get the not-equal flags for all handled cases. + var notEqualFacts_2 = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses); + if (operandConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */) { + // We special case the top types to be exhaustive when all cases are handled. + return (556800 /* TypeFacts.AllTypeofNE */ & notEqualFacts_2) === 556800 /* TypeFacts.AllTypeofNE */; } - return !!(filterType(type_6, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* TypeFlags.Never */); + // A missing not-equal flag indicates that the type wasn't handled by some case. + return !someType(operandConstraint, function (t) { return (getTypeFacts(t) & notEqualFacts_2) === notEqualFacts_2; }); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -365468,11 +366450,16 @@ var ts; if (isContextSensitive(node)) { if (contextualSignature) { var inferenceContext = getInferenceContext(node); + var instantiatedContextualSignature = void 0; if (checkMode && checkMode & 2 /* CheckMode.Inferential */) { inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext); + var restType = getEffectiveRestType(contextualSignature); + if (restType && restType.flags & 262144 /* TypeFlags.TypeParameter */) { + instantiatedContextualSignature = instantiateSignature(contextualSignature, inferenceContext.nonFixingMapper); + } } - var instantiatedContextualSignature = inferenceContext ? - instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature; + instantiatedContextualSignature || (instantiatedContextualSignature = inferenceContext ? + instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature); assignContextualParameterTypes(signature, instantiatedContextualSignature); } else { @@ -365662,7 +366649,7 @@ var ts; var type = getTypeOfSymbol(symbol); if (strictNullChecks && !(type.flags & (3 /* TypeFlags.AnyOrUnknown */ | 131072 /* TypeFlags.Never */)) && - !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* SymbolFlags.Optional */ : getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */)) { + !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* SymbolFlags.Optional */ : getTypeFacts(type) & 16777216 /* TypeFacts.IsUndefined */)) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional); } } @@ -365771,7 +366758,7 @@ var ts; error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } if (node.operator === 39 /* SyntaxKind.PlusToken */) { - if (maybeTypeOfKind(operandType, 2112 /* TypeFlags.BigIntLike */)) { + if (maybeTypeOfKindConsideringBaseConstraint(operandType, 2112 /* TypeFlags.BigIntLike */)) { error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType))); } return numberType; @@ -365830,8 +366817,8 @@ var ts; } if (type.flags & 3145728 /* TypeFlags.UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { - var t = types_21[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var t = types_20[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -366058,7 +367045,7 @@ var ts; // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* TypeFlags.Undefined */)) { + !(getTypeFacts(checkExpression(prop.objectAssignmentInitializer)) & 16777216 /* TypeFacts.IsUndefined */)) { sourceType = getTypeWithFacts(sourceType, 524288 /* TypeFacts.NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -366071,6 +367058,10 @@ var ts; if (target.kind === 221 /* SyntaxKind.BinaryExpression */ && target.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; + // A default value is specified, so remove undefined from the final type. + if (strictNullChecks) { + sourceType = getTypeWithFacts(sourceType, 524288 /* TypeFacts.NEUndefined */); + } } if (target.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); @@ -366211,7 +367202,11 @@ var ts; var operator = operatorToken.kind; if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */ || operator === 56 /* SyntaxKind.BarBarToken */ || operator === 60 /* SyntaxKind.QuestionQuestionToken */) { if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */) { - var parent = ts.walkUpParenthesizedExpressions(node.parent); + var parent = node.parent; + while (parent.kind === 212 /* SyntaxKind.ParenthesizedExpression */ + || ts.isBinaryExpression(parent) && (parent.operatorToken.kind === 55 /* SyntaxKind.AmpersandAmpersandToken */ || parent.operatorToken.kind === 56 /* SyntaxKind.BarBarToken */)) { + parent = parent.parent; + } checkTestingKnownTruthyCallableOrAwaitableType(node.left, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } checkTruthinessOfType(leftType, node.left); @@ -366435,6 +367430,10 @@ var ts; case 35 /* SyntaxKind.ExclamationEqualsToken */: case 36 /* SyntaxKind.EqualsEqualsEqualsToken */: case 37 /* SyntaxKind.ExclamationEqualsEqualsToken */: + if (ts.isLiteralExpressionOfObject(left) || ts.isLiteralExpressionOfObject(right)) { + var eqType = operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */; + error(errorNode, ts.Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true"); + } reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); }); return booleanType; case 102 /* SyntaxKind.InstanceOfKeyword */: @@ -366454,7 +367453,7 @@ var ts; case 56 /* SyntaxKind.BarBarToken */: case 75 /* SyntaxKind.BarBarEqualsToken */: { var resultType_3 = getTypeFacts(leftType) & 8388608 /* TypeFacts.Falsy */ ? - getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* UnionReduction.Subtype */) : + getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2 /* UnionReduction.Subtype */) : leftType; if (operator === 75 /* SyntaxKind.BarBarEqualsToken */) { checkAssignmentOperator(rightType); @@ -366706,7 +367705,7 @@ var ts; type = anyType; addLazyDiagnostic(function () { if (noImplicitAny && !ts.expressionResultIsUnused(node)) { - var contextualType = getContextualType(node); + var contextualType = getContextualType(node, /*contextFlags*/ undefined); if (!contextualType || isTypeAny(contextualType)) { error(node, ts.Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation); } @@ -366747,7 +367746,7 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node, /*contextFlags*/ undefined) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; } function isTemplateLiteralContextualType(type) { return !!(type.flags & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */) || @@ -366775,7 +367774,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 2944 /* TypeFlags.Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* TypeFlags.Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node, /*contextFlags*/ undefined)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -366890,7 +367889,7 @@ var ts; var type = checkExpression(node, checkMode, forceTuple); return isConstContext(node) || ts.isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : - getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node)); + getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node, /*contextFlags*/ undefined) : contextualType, node, /*contextFlags*/ undefined)); } function checkPropertyAssignment(node, checkMode) { // Do not use hasDynamicName here, because that returns false for well known symbols. @@ -367000,8 +367999,8 @@ var ts; var result = []; var oldTypeParameters; var newTypeParameters; - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var tp = typeParameters_2[_i]; + for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { + var tp = typeParameters_3[_i]; var name = tp.symbol.escapedName; if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) { var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name); @@ -367323,12 +368322,14 @@ var ts; error(node, ts.Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types); } else if (modifiers === 32768 /* ModifierFlags.In */ || modifiers === 65536 /* ModifierFlags.Out */) { - var source = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSubType : markerSuperType); - var target = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSuperType : markerSubType); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* tracing.Phase.CheckTypes */, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) }); + var source = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSubTypeForCheck : markerSuperTypeForCheck); + var target = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSuperTypeForCheck : markerSubTypeForCheck); var saveVarianceTypeParameter = typeParameter; varianceTypeParameter = typeParameter; checkTypeAssignableTo(source, target, node, ts.Diagnostics.Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation); varianceTypeParameter = saveVarianceTypeParameter; + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } } } @@ -367349,7 +368350,7 @@ var ts; error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } - if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + if ((node.questionToken || isJSDocOptionalParameter(node)) && ts.isBindingPattern(node.name) && func.body) { error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { @@ -367678,7 +368679,7 @@ var ts; var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { var indexSignatureMap_1 = new ts.Map(); - var _loop_27 = function (declaration) { + var _loop_29 = function (declaration) { if (declaration.parameters.length === 1 && declaration.parameters[0].type) { forEachType(getTypeFromTypeNode(declaration.parameters[0].type), function (type) { var entry = indexSignatureMap_1.get(getTypeId(type)); @@ -367693,7 +368694,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_27(declaration); + _loop_29(declaration); } indexSignatureMap_1.forEach(function (entry) { if (entry.declarations.length > 1) { @@ -367726,6 +368727,9 @@ var ts; // Grammar checking if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); + if (ts.isMethodDeclaration(node) && node.asteriskToken && ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_a_generator); + } // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // method signatures already report "implementation not allowed in ambient context" elsewhere @@ -367853,6 +368857,9 @@ var ts; return !!ts.forEachChild(node, nodeImmediatelyReferencesSuperOrThis); } function checkAccessorDeclaration(node) { + if (ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_an_accessor); + } addLazyDiagnostic(checkAccessorDeclarationDiagnostics); checkSourceElement(node.body); setNodeLinksForPrivateIdentifierScope(node); @@ -367910,6 +368917,12 @@ var ts; function checkMissingDeclaration(node) { checkDecorators(node); } + function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) { + if (node.typeArguments && index < node.typeArguments.length) { + return getTypeFromTypeNode(node.typeArguments[index]); + } + return getEffectiveTypeArguments(node, typeParameters)[index]; + } function getEffectiveTypeArguments(node, typeParameters) { return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } @@ -368540,7 +369553,7 @@ var ts; * @param type The type of the promise. * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. */ - function getPromisedTypeOfPromise(type, errorNode) { + function getPromisedTypeOfPromise(type, errorNode, thisTypeForErrorOut) { // // { // type // then( // thenFunction @@ -368575,7 +369588,29 @@ var ts; } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* TypeFacts.NEUndefinedOrNull */); + var thisTypeForError; + var candidates; + for (var _i = 0, thenSignatures_1 = thenSignatures; _i < thenSignatures_1.length; _i++) { + var thenSignature = thenSignatures_1[_i]; + var thisType = getThisTypeOfSignature(thenSignature); + if (thisType && thisType !== voidType && !isTypeRelatedTo(type, thisType, subtypeRelation)) { + thisTypeForError = thisType; + } + else { + candidates = ts.append(candidates, thenSignature); + } + } + if (!candidates) { + ts.Debug.assertIsDefined(thisTypeForError); + if (thisTypeForErrorOut) { + thisTypeForErrorOut.value = thisTypeForError; + } + if (errorNode) { + error(errorNode, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForError)); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(candidates, getTypeOfFirstParameterOfSignature)), 2097152 /* TypeFacts.NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -368629,6 +369664,34 @@ var ts; isAwaitedTypeInstantiation(type) ? type.aliasTypeArguments[0] : type; } + function isAwaitedTypeNeeded(type) { + // If this is already an `Awaited`, we shouldn't wrap it. This helps to avoid `Awaited>` in higher-order. + if (isTypeAny(type) || isAwaitedTypeInstantiation(type)) { + return false; + } + // We only need `Awaited` if `T` contains possibly non-primitive types. + if (isGenericObjectType(type)) { + var baseConstraint = getBaseConstraintOfType(type); + // We only need `Awaited` if `T` is a type variable that has no base constraint, or the base constraint of `T` is `any`, `unknown`, `{}`, `object`, + // or is promise-like. + if (baseConstraint ? + baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || isThenableType(baseConstraint) : + maybeTypeOfKind(type, 8650752 /* TypeFlags.TypeVariable */)) { + return true; + } + } + return false; + } + function tryCreateAwaitedType(type) { + // Nothing to do if `Awaited` doesn't exist + var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ true); + if (awaitedSymbol) { + // Unwrap unions that may contain `Awaited`, otherwise its possible to manufacture an `Awaited | U>` where + // an `Awaited` would suffice. + return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); + } + return undefined; + } function createAwaitedTypeIfNeeded(type) { // We wrap type `T` in `Awaited` based on the following conditions: // - `T` is not already an `Awaited`, and @@ -368637,26 +369700,10 @@ var ts; // - `T` has no base constraint, or // - The base constraint of `T` is `any`, `unknown`, `object`, or `{}`, or // - The base constraint of `T` is an object type with a callable `then` method. - if (isTypeAny(type)) { - return type; - } - // If this is already an `Awaited`, just return it. This helps to avoid `Awaited>` in higher-order. - if (isAwaitedTypeInstantiation(type)) { - return type; - } - // Only instantiate `Awaited` if `T` contains possibly non-primitive types. - if (isGenericObjectType(type)) { - var baseConstraint = getBaseConstraintOfType(type); - // Only instantiate `Awaited` if `T` has no base constraint, or the base constraint of `T` is `any`, `unknown`, `{}`, `object`, - // or is promise-like. - if (!baseConstraint || (baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */) || isEmptyObjectType(baseConstraint) || isThenableType(baseConstraint)) { - // Nothing to do if `Awaited` doesn't exist - var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ true); - if (awaitedSymbol) { - // Unwrap unions that may contain `Awaited`, otherwise its possible to manufacture an `Awaited | U>` where - // an `Awaited` would suffice. - return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); - } + if (isAwaitedTypeNeeded(type)) { + var awaitedType = tryCreateAwaitedType(type); + if (awaitedType) { + return awaitedType; } } ts.Debug.assert(getPromisedTypeOfPromise(type) === undefined, "type provided should not be a non-generic 'promise'-like."); @@ -368696,10 +369743,24 @@ var ts; } // For a union, get a union of the awaited types of each constituent. if (type.flags & 1048576 /* TypeFlags.Union */) { + if (awaitedTypeStack.lastIndexOf(type.id) >= 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } var mapper = errorNode ? function (constituentType) { return getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeNoAlias; - return typeAsAwaitable.awaitedTypeOfType = mapType(type, mapper); + awaitedTypeStack.push(type.id); + var mapped = mapType(type, mapper); + awaitedTypeStack.pop(); + return typeAsAwaitable.awaitedTypeOfType = mapped; } - var promisedType = getPromisedTypeOfPromise(type); + // If `type` is generic and should be wrapped in `Awaited`, return it. + if (isAwaitedTypeNeeded(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + var thisTypeForErrorOut = { value: undefined }; + var promisedType = getPromisedTypeOfPromise(type, /*errorNode*/ undefined, thisTypeForErrorOut); if (promisedType) { if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose @@ -368768,7 +369829,12 @@ var ts; if (isThenableType(type)) { if (errorNode) { ts.Debug.assertIsDefined(diagnosticMessage); - error(errorNode, diagnosticMessage, arg0); + var chain = void 0; + if (thisTypeForErrorOut.value) { + chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForErrorOut.value)); + } + chain = ts.chainDiagnosticMessages(chain, diagnosticMessage, arg0); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, chain)); } return undefined; } @@ -368964,8 +370030,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { - var typeNode = types_22[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 191 /* SyntaxKind.ParenthesizedType */ || typeNode.kind === 197 /* SyntaxKind.NamedTupleMember */) { typeNode = typeNode.type; // Skip parens if need be } @@ -369005,18 +370071,18 @@ var ts; } /** Check the decorators of a node */ function checkDecorators(node) { - if (!node.decorators) { - return; - } // skip this check for nodes that cannot have decorators. These should have already had an error reported by // checkGrammarDecorators. - if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node) || !node.modifiers || !ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { return; } if (!compilerOptions.experimentalDecorators) { error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning); } - var firstDecorator = node.decorators[0]; + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (!firstDecorator) { + return; + } checkExternalEmitHelpers(firstDecorator, 8 /* ExternalEmitHelpers.Decorate */); if (node.kind === 164 /* SyntaxKind.Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* ExternalEmitHelpers.Param */); @@ -369060,7 +370126,12 @@ var ts; break; } } - ts.forEach(node.decorators, checkDecorator); + for (var _f = 0, _g = node.modifiers; _f < _g.length; _f++) { + var modifier = _g[_f]; + if (ts.isDecorator(modifier)) { + checkDecorator(modifier); + } + } } function checkFunctionDeclaration(node) { addLazyDiagnostic(checkFunctionDeclarationDiagnostics); @@ -369091,6 +370162,11 @@ var ts; function checkJSDocTypeTag(node) { checkSourceElement(node.typeExpression); } + function checkJSDocLinkLikeTag(node) { + if (node.name) { + resolveJSDocMemberName(node.name, /*ignoreErrors*/ true); + } + } function checkJSDocParameterTag(node) { checkSourceElement(node.typeExpression); } @@ -369330,8 +370406,8 @@ var ts; return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.Set(); - for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { - var typeParameter = typeParameters_3[_i]; + for (var _i = 0, typeParameters_4 = typeParameters; _i < typeParameters_4.length; _i++) { + var typeParameter = typeParameters_4[_i]; if (!isTypeParameterUnused(typeParameter)) continue; var name = ts.idText(typeParameter.name); @@ -369491,6 +370567,22 @@ var ts; } }); } + function checkPotentialUncheckedRenamedBindingElementsInTypes() { + var _a; + for (var _i = 0, potentialUnusedRenamedBindingElementsInTypes_1 = potentialUnusedRenamedBindingElementsInTypes; _i < potentialUnusedRenamedBindingElementsInTypes_1.length; _i++) { + var node = potentialUnusedRenamedBindingElementsInTypes_1[_i]; + if (!((_a = getSymbolOfNode(node)) === null || _a === void 0 ? void 0 : _a.isReferenced)) { + var wrappingDeclaration = ts.walkUpBindingElementsAndPatterns(node); + ts.Debug.assert(ts.isParameterDeclaration(wrappingDeclaration), "Only parameter declaration should be checked here"); + var diagnostic = ts.createDiagnosticForNode(node.name, ts.Diagnostics._0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation, ts.declarationNameToString(node.name), ts.declarationNameToString(node.propertyName)); + if (!wrappingDeclaration.type) { + // entire parameter does not have type annotation, suggest adding an annotation + ts.addRelatedInfo(diagnostic, ts.createFileDiagnostic(ts.getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 1, ts.Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, ts.declarationNameToString(node.propertyName))); + } + diagnostics.add(diagnostic); + } + } + } function bindingNameText(name) { switch (name.kind) { case 79 /* SyntaxKind.Identifier */: @@ -369787,11 +370879,22 @@ var ts; // well known symbols. if (node.name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { checkComputedPropertyName(node.name); - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkExpressionCached(node.initializer); } } if (ts.isBindingElement(node)) { + if (node.propertyName && + ts.isIdentifier(node.name) && + ts.isParameterDeclaration(node) && + ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + // type F = ({a: string}) => void; + // ^^^^^^ + // variable renaming in function type notation is confusing, + // so we forbid it even if noUnusedLocals is not enabled + potentialUnusedRenamedBindingElementsInTypes.push(node); + return; + } if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ScriptTarget.ES2018 */) { checkExternalEmitHelpers(node, 4 /* ExternalEmitHelpers.Rest */); } @@ -369824,14 +370927,14 @@ var ts; ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.isParameterDeclaration(node) && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (ts.isParameter(node) && node.initializer && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = node.initializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */; - var needCheckWidenedType = node.name.elements.length === 0; + var needCheckInitializer = ts.hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */; + var needCheckWidenedType = !ts.some(node.name.elements, ts.not(ts.isOmittedExpression)); if (needCheckInitializer || needCheckWidenedType) { // Don't validate for-in initializer as it is already an error var widenedType = getWidenedTypeForVariableLikeDeclaration(node); @@ -369866,7 +370969,7 @@ var ts; if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error - var initializer = ts.getEffectiveInitializer(node); + var initializer = ts.hasOnlyExpressionInitializer(node) && ts.getEffectiveInitializer(node); if (initializer) { var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && @@ -369891,7 +370994,7 @@ var ts; !(symbol.flags & 67108864 /* SymbolFlags.Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType); } - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { @@ -369984,7 +371087,7 @@ var ts; return; var type = checkTruthinessExpression(location); var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) && isTypeAssertion(location.expression); - if (getFalsyFlags(type) || isPropertyExpressionCast) + if (!(getTypeFacts(type) & 4194304 /* TypeFacts.Truthy */) || isPropertyExpressionCast) return; // While it technically should be invalid for any known-truthy value // to be tested, we de-scope to functions and Promises unreferenced in @@ -370450,17 +371553,28 @@ var ts; * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. */ function getIterationTypesOfIterable(type, use, errorNode) { + var _a, _b; if (isTypeAny(type)) { return anyIterationTypes; } if (!(type.flags & 1048576 /* TypeFlags.Union */)) { - var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode); + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer); if (iterationTypes_1 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } return undefined; } + else if ((_a = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _a === void 0 ? void 0 : _a.length) { + for (var _i = 0, _c = errorOutputContainer.errors; _i < _c.length; _i++) { + var diag = _c[_i]; + diagnostics.add(diag); + } + } return iterationTypes_1; } var cacheKey = use & 2 /* IterationUse.AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable"; @@ -370468,19 +371582,27 @@ var ts; if (cachedTypes) return cachedTypes === noIterationTypes ? undefined : cachedTypes; var allIterationTypes; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var constituent = _a[_i]; - var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode); + for (var _d = 0, _e = type.types; _d < _e.length; _d++) { + var constituent = _e[_d]; + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode, errorOutputContainer); if (iterationTypes_2 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } setCachedIterationTypes(type, cacheKey, noIterationTypes); return undefined; } - else { - allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); + else if ((_b = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _b === void 0 ? void 0 : _b.length) { + for (var _f = 0, _g = errorOutputContainer.errors; _f < _g.length; _f++) { + var diag = _g[_f]; + diagnostics.add(diag); + } } + allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); } var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes; setCachedIterationTypes(type, cacheKey, iterationTypes); @@ -370508,47 +371630,62 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableWorker(type, use, errorNode) { + function getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer) { if (isTypeAny(type)) { return anyIterationTypes; } + // If we are reporting errors and encounter a cached `noIterationTypes`, we should ignore the cached value and continue as if nothing was cached. + // In addition, we should not cache any new results for this call. + var noCache = false; if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) || getIterationTypesOfIterableFast(type, asyncIterationTypesResolver); if (iterationTypes) { - return use & 8 /* IterationUse.ForOfFlag */ ? - getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : - iterationTypes; + if (iterationTypes === noIterationTypes && errorNode) { + // ignore the cached value + noCache = true; + } + else { + return use & 8 /* IterationUse.ForOfFlag */ ? + getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : + iterationTypes; + } } } if (use & 1 /* IterationUse.AllowsSyncIterablesFlag */) { var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) || getIterationTypesOfIterableFast(type, syncIterationTypesResolver); if (iterationTypes) { - if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - // for a sync iterable in an async context, only use the cached types if they are valid. - if (iterationTypes !== noIterationTypes) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode)); - } + if (iterationTypes === noIterationTypes && errorNode) { + // ignore the cached value + noCache = true; } else { - return iterationTypes; + if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { + // for a sync iterable in an async context, only use the cached types if they are valid. + if (iterationTypes !== noIterationTypes) { + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); + } + } + else { + return iterationTypes; + } } } } if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { return iterationTypes; } } if (use & 1 /* IterationUse.AllowsSyncIterablesFlag */) { - var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes - ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode) - : noIterationTypes); + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); } else { return iterationTypes; @@ -370569,7 +371706,7 @@ var ts; } function getIterationTypesOfGlobalIterableType(globalType, resolver) { var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) || - getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined); + getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; } /** @@ -370623,26 +371760,26 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableSlow(type, resolver, errorNode) { + function getIterationTypesOfIterableSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var _a; var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); var methodType = method && !(method.flags & 16777216 /* SymbolFlags.Optional */) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); + return noCache ? anyIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); } var signatures = methodType ? getSignaturesOfType(methodType, 0 /* SignatureKind.Call */) : undefined; if (!ts.some(signatures)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); + return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); } var iteratorType = getIntersectionType(ts.map(signatures, getReturnTypeOfSignature)); - var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes; - return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); + var iterationTypes = (_a = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache)) !== null && _a !== void 0 ? _a : noIterationTypes; + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { var message = allowAsyncIterables ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator; - errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); } /** * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. @@ -370650,13 +371787,29 @@ var ts; * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, `undefined` is returned. */ - function getIterationTypesOfIterator(type, resolver, errorNode) { + function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) { + return getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, /*noCache*/ false); + } + /** + * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. + * + * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` + * record is returned. Otherwise, `undefined` is returned. + * + * NOTE: You probably don't want to call this directly and should be calling + * `getIterationTypesOfIterator` instead. + */ + function getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, noCache) { if (isTypeAny(type)) { return anyIterationTypes; } var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) || - getIterationTypesOfIteratorFast(type, resolver) || - getIterationTypesOfIteratorSlow(type, resolver, errorNode); + getIterationTypesOfIteratorFast(type, resolver); + if (iterationTypes === noIterationTypes && errorNode) { + iterationTypes = undefined; + noCache = true; + } + iterationTypes !== null && iterationTypes !== void 0 ? iterationTypes : (iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache)); return iterationTypes === noIterationTypes ? undefined : iterationTypes; } /** @@ -370694,7 +371847,7 @@ var ts; // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any` // and `undefined` in our libs by default, a custom lib *could* use different definitions. var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) || - getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined); + getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType; return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); } @@ -370764,8 +371917,8 @@ var ts; * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, we return `undefined`. */ - function getIterationTypesOfMethod(type, resolver, methodName, errorNode) { - var _a, _b, _c, _d; + function getIterationTypesOfMethod(type, resolver, methodName, errorNode, errorOutputContainer) { + var _a, _b, _c, _d, _e, _f; var method = getPropertyOfType(type, methodName); // Ignore 'return' or 'throw' if they are missing. if (!method && methodName !== "next") { @@ -370785,9 +371938,15 @@ var ts; var diagnostic = methodName === "next" ? resolver.mustHaveANextMethodDiagnostic : resolver.mustBeAMethodDiagnostic; - error(errorNode, diagnostic, methodName); + if (errorOutputContainer) { + (_a = errorOutputContainer.errors) !== null && _a !== void 0 ? _a : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, diagnostic, methodName)); + } + else { + error(errorNode, diagnostic, methodName); + } } - return methodName === "next" ? anyIterationTypes : undefined; + return methodName === "next" ? noIterationTypes : undefined; } // If the method signature comes exclusively from the global iterator or generator type, // create iteration types from its type arguments like `getIterationTypesOfIteratorFast` @@ -370799,8 +371958,8 @@ var ts; if ((methodType === null || methodType === void 0 ? void 0 : methodType.symbol) && methodSignatures.length === 1) { var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false); var globalIteratorType = resolver.getGlobalIteratorType(/*reportErrors*/ false); - var isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) === null || _a === void 0 ? void 0 : _a.members) === null || _b === void 0 ? void 0 : _b.get(methodName)) === methodType.symbol; - var isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) === null || _c === void 0 ? void 0 : _c.members) === null || _d === void 0 ? void 0 : _d.get(methodName)) === methodType.symbol; + var isGeneratorMethod = ((_c = (_b = globalGeneratorType.symbol) === null || _b === void 0 ? void 0 : _b.members) === null || _c === void 0 ? void 0 : _c.get(methodName)) === methodType.symbol; + var isIteratorMethod = !isGeneratorMethod && ((_e = (_d = globalIteratorType.symbol) === null || _d === void 0 ? void 0 : _d.members) === null || _e === void 0 ? void 0 : _e.get(methodName)) === methodType.symbol; if (isGeneratorMethod || isIteratorMethod) { var globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType; var mapper = methodType.mapper; @@ -370840,7 +371999,13 @@ var ts; var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType); if (iterationTypes === noIterationTypes) { if (errorNode) { - error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + if (errorOutputContainer) { + (_f = errorOutputContainer.errors) !== null && _f !== void 0 ? _f : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, resolver.mustHaveAValueDiagnostic, methodName)); + } + else { + error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + } } yieldType = anyType; returnTypes = ts.append(returnTypes, anyType); @@ -370861,13 +372026,13 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterator` instead. */ - function getIterationTypesOfIteratorSlow(type, resolver, errorNode) { + function getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var iterationTypes = combineIterationTypes([ - getIterationTypesOfMethod(type, resolver, "next", errorNode), - getIterationTypesOfMethod(type, resolver, "return", errorNode), - getIterationTypesOfMethod(type, resolver, "throw", errorNode), + getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "throw", errorNode, errorOutputContainer), ]); - return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); } /** * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like, @@ -370888,7 +372053,7 @@ var ts; var use = isAsyncGenerator ? 2 /* IterationUse.AsyncGeneratorReturnType */ : 1 /* IterationUse.GeneratorReturnType */; var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver; return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) || - getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined); + getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined); } function checkBreakOrContinueStatement(node) { // Grammar checking @@ -370899,9 +372064,14 @@ var ts; function unwrapReturnType(returnType, functionFlags) { var isGenerator = !!(functionFlags & 1 /* FunctionFlags.Generator */); var isAsync = !!(functionFlags & 2 /* FunctionFlags.Async */); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, returnType, isAsync) || errorType : - isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : - returnType; + if (isGenerator) { + var returnIterationType = getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, returnType, isAsync); + if (!returnIterationType) { + return errorType; + } + return isAsync ? getAwaitedTypeNoAlias(unwrapAwaitedType(returnIterationType)) : returnIterationType; + } + return isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func)); @@ -371121,9 +372291,10 @@ var ts; } var indexInfos = getApplicableIndexInfos(type, propNameType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; - var localPropDeclaration = declaration && declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || - name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ || getParentOfSymbol(prop) === type.symbol ? declaration : undefined; - var _loop_28 = function (info) { + var propDeclaration = declaration && declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || + name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ ? declaration : undefined; + var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; + var _loop_30 = function (info) { var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; // We check only when (a) the property is declared in the containing type, or (b) the applicable index signature is declared // in the containing type, or (c) the containing type is an interface and no base interface contains both the property and @@ -371131,12 +372302,16 @@ var ts; var errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !ts.some(getBaseTypes(type), function (base) { return !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType); }) ? interfaceDeclaration : undefined); if (errorNode && !isTypeAssignableTo(propType, info.type)) { - error(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + var diagnostic = createError(errorNode, ts.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) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(propDeclaration, ts.Diagnostics._0_is_declared_here, symbolToString(prop))); + } + diagnostics.add(diagnostic); } }; for (var _i = 0, indexInfos_9 = indexInfos; _i < indexInfos_9.length; _i++) { var info = indexInfos_9[_i]; - _loop_28(info); + _loop_30(info); } } function checkIndexConstraintForIndexSignature(type, checkInfo) { @@ -371144,7 +372319,7 @@ var ts; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; - var _loop_29 = function (info) { + var _loop_31 = function (info) { if (info === checkInfo) return "continue"; var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; @@ -371159,7 +372334,7 @@ var ts; }; for (var _i = 0, indexInfos_10 = indexInfos; _i < indexInfos_10.length; _i++) { var info = indexInfos_10[_i]; - _loop_29(info); + _loop_31(info); } } function checkTypeNameIsReserved(name, message) { @@ -371348,8 +372523,9 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { - grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (firstDecorator && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { + grammarErrorOnNode(firstDecorator, ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); } if (!node.name && !ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -371478,7 +372654,7 @@ var ts; var baseTypes = baseTypeNode && getBaseTypes(type); var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; var baseStaticType = getBaseConstructorTypeOfClass(type); - var _loop_30 = function (member) { + var _loop_32 = function (member) { if (ts.hasAmbientModifier(member)) { return "continue"; } @@ -371495,7 +372671,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_30(member); + _loop_32(member); } } /** @@ -371583,7 +372759,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_31 = function (member) { + var _loop_33 = function (member) { if (ts.isStatic(member)) { return "continue"; } @@ -371602,7 +372778,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_31(member); + _loop_33(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -371670,18 +372846,17 @@ var ts; // but not by other kinds of members. // Base class instance member variables and accessors can be overridden by // derived class instance member variables and accessors, but not by other kinds of members. - var _a, _b; + var _a, _b, _c, _d; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); - basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { - var baseProperty = baseProperties_1[_i]; + var _loop_34 = function (baseProperty) { var base = getTargetSymbol(baseProperty); if (base.flags & 4194304 /* SymbolFlags.Prototype */) { - continue; + return "continue"; } var baseSymbol = getPropertyOfObjectType(type, base.escapedName); if (!baseSymbol) { - continue; + return "continue"; } var derived = getTargetSymbol(baseSymbol); var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); @@ -371699,14 +372874,14 @@ var ts; // Searches other base types for a declaration that would satisfy the inherited abstract member. // (The class may have more than one base type via declaration merging with an interface with the // same name.) - for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) { - var otherBaseType = _d[_c]; + for (var _e = 0, _f = getBaseTypes(type); _e < _f.length; _e++) { + var otherBaseType = _f[_e]; if (otherBaseType === baseType) continue; var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName); var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1); if (derivedElsewhere && derivedElsewhere !== base) { - continue basePropertyCheck; + return "continue-basePropertyCheck"; } } if (derivedClassDecl.kind === 226 /* SyntaxKind.ClassExpression */) { @@ -371721,20 +372896,19 @@ var ts; // derived overrides base. var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 /* ModifierFlags.Private */ || derivedDeclarationFlags & 8 /* ModifierFlags.Private */) { - // either base or derived property is private - not override, skip it - continue; + return "continue"; } var errorMessage = void 0; var basePropertyFlags = base.flags & 98308 /* SymbolFlags.PropertyOrAccessor */; var derivedPropertyFlags = derived.flags & 98308 /* SymbolFlags.PropertyOrAccessor */; if (basePropertyFlags && derivedPropertyFlags) { // property/accessor is overridden with property/accessor - if (baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer) - || base.valueDeclaration && base.valueDeclaration.parent.kind === 258 /* SyntaxKind.InterfaceDeclaration */ + if ((ts.getCheckFlags(base) & 6 /* CheckFlags.Synthetic */ + ? (_a = base.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); }) + : (_b = base.declarations) === null || _b === void 0 ? void 0 : _b.every(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); })) + || ts.getCheckFlags(base) & 262144 /* CheckFlags.Mapped */ || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { - // when the base property is abstract or from an interface, base/derived flags don't need to match - // same when the derived property is from an assignment - continue; + return "continue"; } var overriddenInstanceProperty = basePropertyFlags !== 4 /* SymbolFlags.Property */ && derivedPropertyFlags === 4 /* SymbolFlags.Property */; var overriddenInstanceAccessor = basePropertyFlags === 4 /* SymbolFlags.Property */ && derivedPropertyFlags !== 4 /* SymbolFlags.Property */; @@ -371745,12 +372919,12 @@ var ts; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } else if (useDefineForClassFields) { - var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); + var uninitialized = (_c = derived.declarations) === null || _c === void 0 ? void 0 : _c.find(function (d) { return d.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* SymbolFlags.Transient */) && !(baseDeclarationFlags & 128 /* ModifierFlags.Abstract */) && !(derivedDeclarationFlags & 128 /* ModifierFlags.Abstract */) - && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 16777216 /* NodeFlags.Ambient */); }))) { + && !((_d = derived.declarations) === null || _d === void 0 ? void 0 : _d.some(function (d) { return !!(d.flags & 16777216 /* NodeFlags.Ambient */); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; if (uninitialized.exclamationToken @@ -371763,13 +372937,11 @@ var ts; } } } - // correct case - continue; + return "continue"; } else if (isPrototypeProperty(base)) { if (isPrototypeProperty(derived) || derived.flags & 4 /* SymbolFlags.Property */) { - // method is overridden with method or property -- correct case - continue; + return "continue"; } else { ts.Debug.assert(!!(derived.flags & 98304 /* SymbolFlags.Accessor */)); @@ -371784,9 +372956,20 @@ var ts; } error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } + }; + basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var state_10 = _loop_34(baseProperty); + switch (state_10) { + case "continue-basePropertyCheck": continue basePropertyCheck; + } } } - function getNonInterhitedProperties(type, baseTypes, properties) { + function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) { + return baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && (!ts.isPropertyDeclaration(declaration) || !declaration.initializer) + || ts.isInterfaceDeclaration(declaration.parent); + } + function getNonInheritedProperties(type, baseTypes, properties) { if (!ts.length(baseTypes)) { return properties; } @@ -371855,7 +373038,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName) || ts.isComputedPropertyName(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 3 /* TypeFlags.AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */)) { + if (!(type.flags & 3 /* TypeFlags.AnyOrUnknown */ || containsUndefinedType(type))) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -371880,7 +373063,7 @@ var ts; ts.setParent(reference, staticBlock); reference.flowNode = staticBlock.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - if (!(getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */)) { + if (!containsUndefinedType(flowType)) { return true; } } @@ -371895,7 +373078,7 @@ var ts; ts.setParent(reference, constructor); reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */); + return !containsUndefinedType(flowType); } function checkInterfaceDeclaration(node) { // Grammar checking @@ -372411,6 +373594,7 @@ var ts; return true; } function checkAliasSymbol(node) { + var _a, _b, _c, _d, _e; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -372421,6 +373605,31 @@ var ts; // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). symbol = getMergedSymbol(symbol.exportSymbol || symbol); + // A type-only import/export will already have a grammar error in a JS file, so no need to issue more errors within + if (ts.isInJSFile(node) && !(target.flags & 111551 /* SymbolFlags.Value */) && !ts.isTypeOnlyImportOrExportDeclaration(node)) { + var errorNode = ts.isImportOrExportSpecifier(node) ? node.propertyName || node.name : + ts.isNamedDeclaration(node) ? node.name : + node; + ts.Debug.assert(node.kind !== 274 /* SyntaxKind.NamespaceExport */); + if (node.kind === 275 /* SyntaxKind.ExportSpecifier */) { + var diag = error(errorNode, ts.Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files); + var alreadyExportedSymbol = (_b = (_a = ts.getSourceFileOfNode(node).symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.get((node.propertyName || node.name).escapedText); + if (alreadyExportedSymbol === target) { + var exportingDeclaration = (_c = alreadyExportedSymbol.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isJSDocNode); + if (exportingDeclaration) { + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(exportingDeclaration, ts.Diagnostics._0_is_automatically_exported_here, ts.unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName))); + } + } + } + else { + ts.Debug.assert(node.kind !== 254 /* SyntaxKind.VariableDeclaration */); + var importDeclaration = ts.findAncestor(node, ts.or(ts.isImportDeclaration, ts.isImportEqualsDeclaration)); + var moduleSpecifier = (_e = (importDeclaration && ((_d = ts.tryGetModuleSpecifierFromDeclaration(importDeclaration)) === null || _d === void 0 ? void 0 : _d.text))) !== null && _e !== void 0 ? _e : "..."; + var importedIdentifier = ts.unescapeLeadingUnderscores(ts.isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName); + error(errorNode, ts.Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation, importedIdentifier, "import(\"".concat(moduleSpecifier, "\").").concat(importedIdentifier)); + } + return; + } var excludedMeanings = (symbol.flags & (111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */) ? 111551 /* SymbolFlags.Value */ : 0) | (symbol.flags & 788968 /* SymbolFlags.Type */ ? 788968 /* SymbolFlags.Type */ : 0) | (symbol.flags & 1920 /* SymbolFlags.Namespace */ ? 1920 /* SymbolFlags.Namespace */ : 0); @@ -372736,7 +373945,9 @@ var ts; error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { - markExportAsReferenced(node); + if (!node.isTypeOnly && !node.parent.parent.isTypeOnly) { + markExportAsReferenced(node); + } var target = symbol && (symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol); if (!target || target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { checkExpressionCached(node.propertyName || node.name); @@ -372878,12 +374089,16 @@ var ts; } } function checkSourceElementWorker(node) { - if (ts.isInJSFile(node)) { - ts.forEach(node.jsDoc, function (_a) { - var tags = _a.tags; - return ts.forEach(tags, checkSourceElement); + ts.forEach(node.jsDoc, function (_a) { + var comment = _a.comment, tags = _a.tags; + checkJSDocCommentWorker(comment); + ts.forEach(tags, function (tag) { + checkJSDocCommentWorker(tag.comment); + if (ts.isInJSFile(node)) { + checkSourceElement(tag); + } }); - } + }); var kind = node.kind; if (cancellationToken) { // Only bother checking on a few construct kinds. We don't want to be excessively @@ -372969,6 +374184,10 @@ var ts; return checkJSDocTemplateTag(node); case 343 /* SyntaxKind.JSDocTypeTag */: return checkJSDocTypeTag(node); + case 324 /* SyntaxKind.JSDocLink */: + case 325 /* SyntaxKind.JSDocLinkCode */: + case 326 /* SyntaxKind.JSDocLinkPlain */: + return checkJSDocLinkLikeTag(node); case 340 /* SyntaxKind.JSDocParameterTag */: return checkJSDocParameterTag(node); case 347 /* SyntaxKind.JSDocPropertyTag */: @@ -373063,6 +374282,15 @@ var ts; return checkMissingDeclaration(node); } } + function checkJSDocCommentWorker(node) { + if (ts.isArray(node)) { + ts.forEach(node, function (tag) { + if (ts.isJSDocLinkLike(tag)) { + checkSourceElement(tag); + } + }); + } + } function checkJSDocTypeIsInJsFile(node) { if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); @@ -373230,6 +374458,7 @@ var ts; ts.clear(potentialNewTargetCollisions); ts.clear(potentialWeakMapSetCollisions); ts.clear(potentialReflectCollisions); + ts.clear(potentialUnusedRenamedBindingElementsInTypes); ts.forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -373245,6 +374474,9 @@ var ts; } }); } + if (!node.isDeclarationFile) { + checkPotentialUncheckedRenamedBindingElementsInTypes(); + } }); if (compilerOptions.importsNotUsedAsValues === 2 /* ImportsNotUsedAsValues.Error */ && !node.isDeclarationFile && @@ -373618,7 +374850,7 @@ var ts; if (!result && isJSDoc_1) { var container = ts.findAncestor(name, ts.or(ts.isClassLike, ts.isInterfaceDeclaration)); if (container) { - return resolveJSDocMemberName(name, getSymbolOfNode(container)); + return resolveJSDocMemberName(name, /*ignoreErrors*/ false, getSymbolOfNode(container)); } } return result; @@ -373664,11 +374896,11 @@ var ts; * * For unqualified names, a container K may be provided as a second argument. */ - function resolveJSDocMemberName(name, container) { + function resolveJSDocMemberName(name, ignoreErrors, container) { if (ts.isEntityName(name)) { // resolve static values first var meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */ | 111551 /* SymbolFlags.Value */; - var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); + var symbol = resolveEntityName(name, meaning, ignoreErrors, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); if (!symbol && ts.isIdentifier(name) && container) { symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(container), name.escapedText, meaning)); } @@ -373676,7 +374908,7 @@ var ts; return symbol; } } - var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left); + var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left, ignoreErrors, container); var right = ts.isIdentifier(name) ? name.escapedText : name.right.escapedText; if (left) { var proto = left.flags & 111551 /* SymbolFlags.Value */ && getPropertyOfType(getTypeOfSymbol(left), "prototype"); @@ -374667,13 +375899,20 @@ var ts; if (!fileToDirective) { return undefined; } + // computed property name should use node as value // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */; - if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { + var meaning; + if (node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) { meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; } + else { + meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */; + if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; + } + } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -374957,7 +376196,10 @@ var ts; return checkGrammarDecorators(node) || checkGrammarModifiers(node); } function checkGrammarDecorators(node) { - if (!node.decorators) { + if (ts.canHaveIllegalDecorators(node) && ts.some(node.illegalDecorators)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node)) { return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { @@ -374970,7 +376212,7 @@ var ts; } else if (node.kind === 172 /* SyntaxKind.GetAccessor */ || node.kind === 173 /* SyntaxKind.SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + if (ts.hasDecorators(accessors.firstAccessor) && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); } } @@ -374985,6 +376227,8 @@ var ts; var flags = 0 /* ModifierFlags.None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; if (modifier.kind !== 145 /* SyntaxKind.ReadonlyKeyword */) { if (node.kind === 166 /* SyntaxKind.PropertySignature */ || node.kind === 168 /* SyntaxKind.MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); @@ -375270,6 +376514,13 @@ var ts; case 164 /* SyntaxKind.Parameter */: case 163 /* SyntaxKind.TypeParameter */: return false; + case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 296 /* SyntaxKind.PropertyAssignment */: + case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 264 /* SyntaxKind.NamespaceExportDeclaration */: + case 179 /* SyntaxKind.FunctionType */: + case 276 /* SyntaxKind.MissingDeclaration */: + return true; default: if (node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 305 /* SyntaxKind.SourceFile */) { return false; @@ -375280,20 +376531,26 @@ var ts; case 257 /* SyntaxKind.ClassDeclaration */: case 180 /* SyntaxKind.ConstructorType */: return nodeHasAnyModifiersExcept(node, 126 /* SyntaxKind.AbstractKeyword */); + case 226 /* SyntaxKind.ClassExpression */: case 258 /* SyntaxKind.InterfaceDeclaration */: case 237 /* SyntaxKind.VariableStatement */: case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: return true; case 260 /* SyntaxKind.EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 85 /* SyntaxKind.ConstKeyword */); default: - ts.Debug.fail(); + ts.Debug.assertNever(node); } } } function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; + return modifier.kind !== allowedModifier; + } + return false; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { @@ -375585,14 +376842,20 @@ var ts; grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration - if (prop.modifiers) { + if (ts.canHaveModifiers(prop) && prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 131 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 169 /* SyntaxKind.MethodDeclaration */) { + if (ts.isModifier(mod) && (mod.kind !== 131 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 169 /* SyntaxKind.MethodDeclaration */)) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } + else if (ts.canHaveIllegalModifiers(prop) && prop.modifiers) { + for (var _d = 0, _e = prop.modifiers; _d < _e.length; _d++) { + var mod = _e[_d]; + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and @@ -375604,10 +376867,9 @@ var ts; var currentKind = void 0; switch (prop.kind) { case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); - // falls through case 296 /* SyntaxKind.PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* SyntaxKind.NumericLiteral */) { checkGrammarNumericLiteral(name); @@ -376046,9 +377308,6 @@ var ts; else { return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } - if (!isConstOrReadonly || isInvalidInitializer) { - return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } } } function checkGrammarVariableDeclaration(node) { @@ -376215,7 +377474,7 @@ var ts; } } function checkGrammarConstructorTypeAnnotation(node) { - var type = ts.getEffectiveReturnTypeNode(node); + var type = node.type || ts.getEffectiveReturnTypeNode(node); if (type) { return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); } @@ -376239,6 +377498,8 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + // Interfaces cannot contain property declarations + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } @@ -376247,6 +377508,8 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + // Type literals cannot contain property declarations + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } @@ -376434,7 +377697,7 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments); } var nodeArguments = node.arguments; - if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext) { + if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext && moduleKind !== ts.ModuleKind.Node16) { // We are allowed trailing comma after proposal-import-assertions. checkGrammarForDisallowedTrailingComma(nodeArguments); if (nodeArguments.length > 1) { @@ -376621,7 +377884,6 @@ var ts; if (nodes === undefined || visitor === undefined) { return nodes; } - var updated; // Ensure start and count have valid values var length = nodes.length; if (start === undefined || start < 0) { @@ -376634,12 +377896,49 @@ var ts; var pos = -1; var end = -1; if (start > 0 || count < length) { - // If we are not visiting all of the original nodes, we must always create a new array. // Since this is a fragment of a node array, we do not copy over the previous location // and will only copy over `hasTrailingComma` if we are including the last element. - updated = []; hasTrailingComma = nodes.hasTrailingComma && start + count === length; } + else { + pos = nodes.pos; + end = nodes.end; + hasTrailingComma = nodes.hasTrailingComma; + } + var updated = visitArrayWorker(nodes, visitor, test, start, count); + if (updated !== nodes) { + // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory. + var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); + ts.setTextRangePosEnd(updatedArray, pos, end); + return updatedArray; + } + return nodes; + } + ts.visitNodes = visitNodes; + /* @internal */ + function visitArray(nodes, visitor, test, start, count) { + if (nodes === undefined) { + return nodes; + } + // Ensure start and count have valid values + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + return visitArrayWorker(nodes, visitor, test, start, count); + } + ts.visitArray = visitArray; + /* @internal */ + function visitArrayWorker(nodes, visitor, test, start, count) { + var updated; + var length = nodes.length; + if (start > 0 || count < length) { + // If we are not visiting all of the original nodes, we must always create a new array. + updated = []; + } // Visit each original node. for (var i = 0; i < count; i++) { var node = nodes[i + start]; @@ -376648,9 +377947,6 @@ var ts; if (updated === undefined) { // Ensure we have a copy of `nodes`, up to the current index. updated = nodes.slice(0, i); - hasTrailingComma = nodes.hasTrailingComma; - pos = nodes.pos; - end = nodes.end; } if (visited) { if (ts.isArray(visited)) { @@ -376667,15 +377963,8 @@ var ts; } } } - if (updated) { - // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory. - var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); - ts.setTextRangePosEnd(updatedArray, pos, end); - return updatedArray; - } - return nodes; + return updated !== null && updated !== void 0 ? updated : nodes; } - ts.visitNodes = visitNodes; /** * Starts a new lexical environment and visits a statement list, ending the lexical environment * and merging hoisted declarations upon completion. @@ -376747,7 +378036,7 @@ var ts; /*colonToken*/ undefined, factory.getGeneratedNameForNode(parameter)) : factory.getGeneratedNameForNode(parameter)), ]))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, /*initializer*/ undefined); } function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { @@ -376755,7 +378044,7 @@ var ts; context.addInitializationStatement(factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([ factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(ts.setEmitFlags(factory.cloneNode(name), 48 /* EmitFlags.NoSourceMap */), ts.setEmitFlags(initializer, 48 /* EmitFlags.NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* EmitFlags.NoComments */)), parameter), 1536 /* EmitFlags.NoComments */)) ]), parameter), 1 /* EmitFlags.SingleLine */ | 32 /* EmitFlags.NoTrailingSourceMap */ | 384 /* EmitFlags.NoTokenSourceMaps */ | 1536 /* EmitFlags.NoComments */))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, /*initializer*/ undefined); } function visitFunctionBody(node, visitor, context, nodeVisitor) { @@ -376821,7 +378110,7 @@ var ts; return factory.updateTypeParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); case 164 /* SyntaxKind.Parameter */: ts.Debug.type(node); - return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + return factory.updateParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 165 /* SyntaxKind.Decorator */: ts.Debug.type(node); return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -376831,7 +378120,7 @@ var ts; return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 167 /* SyntaxKind.PropertyDeclaration */: ts.Debug.type(node); - return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), + return factory.updatePropertyDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 168 /* SyntaxKind.MethodSignature */: @@ -376839,21 +378128,21 @@ var ts; return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 169 /* SyntaxKind.MethodDeclaration */: ts.Debug.type(node); - return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateMethodDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 171 /* SyntaxKind.Constructor */: ts.Debug.type(node); - return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateConstructorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 172 /* SyntaxKind.GetAccessor */: ts.Debug.type(node); - return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 173 /* SyntaxKind.SetAccessor */: ts.Debug.type(node); - return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: ts.Debug.type(node); context.startLexicalEnvironment(); context.suspendLexicalEnvironment(); - return factory.updateClassStaticBlockDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateClassStaticBlockDeclaration(node, visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 174 /* SyntaxKind.CallSignature */: ts.Debug.type(node); return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -376862,7 +378151,7 @@ var ts; return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 176 /* SyntaxKind.IndexSignature */: ts.Debug.type(node); - return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateIndexSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); // Types case 177 /* SyntaxKind.TypePredicate */: ts.Debug.type(node); @@ -376908,13 +378197,13 @@ var ts; return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); case 200 /* SyntaxKind.ImportType */: ts.Debug.type(node); - return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); case 295 /* SyntaxKind.ImportTypeAssertionContainer */: ts.Debug.type(node); return factory.updateImportTypeAssertionContainer(node, nodeVisitor(node.assertClause, visitor, ts.isNode), node.multiLine); case 197 /* SyntaxKind.NamedTupleMember */: ts.Debug.type(node); - return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode)); + return factory.updateNamedTupleMember(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 191 /* SyntaxKind.ParenthesizedType */: ts.Debug.type(node); return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -376979,7 +378268,7 @@ var ts; return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 210 /* SyntaxKind.TaggedTemplateExpression */: ts.Debug.type(node); - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); case 211 /* SyntaxKind.TypeAssertionExpression */: ts.Debug.type(node); return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -377027,7 +378316,7 @@ var ts; return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 226 /* SyntaxKind.ClassExpression */: ts.Debug.type(node); - return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 228 /* SyntaxKind.ExpressionWithTypeArguments */: ts.Debug.type(node); return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); @@ -377108,22 +378397,22 @@ var ts; return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 256 /* SyntaxKind.FunctionDeclaration */: ts.Debug.type(node); - return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateFunctionDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 257 /* SyntaxKind.ClassDeclaration */: ts.Debug.type(node); - return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 258 /* SyntaxKind.InterfaceDeclaration */: ts.Debug.type(node); - return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + return factory.updateInterfaceDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 259 /* SyntaxKind.TypeAliasDeclaration */: ts.Debug.type(node); - return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 260 /* SyntaxKind.EnumDeclaration */: ts.Debug.type(node); - return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + return factory.updateEnumDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 261 /* SyntaxKind.ModuleDeclaration */: ts.Debug.type(node); - return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); + return factory.updateModuleDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); case 262 /* SyntaxKind.ModuleBlock */: ts.Debug.type(node); return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); @@ -377135,10 +378424,10 @@ var ts; return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); case 265 /* SyntaxKind.ImportEqualsDeclaration */: ts.Debug.type(node); - return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); + return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); case 266 /* SyntaxKind.ImportDeclaration */: ts.Debug.type(node); - return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateImportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 293 /* SyntaxKind.AssertClause */: ts.Debug.type(node); return factory.updateAssertClause(node, nodesVisitor(node.elements, visitor, ts.isAssertEntry), node.multiLine); @@ -377162,10 +378451,10 @@ var ts; return factory.updateImportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); case 271 /* SyntaxKind.ExportAssignment */: ts.Debug.type(node); - return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); + return factory.updateExportAssignment(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); case 272 /* SyntaxKind.ExportDeclaration */: ts.Debug.type(node); - return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateExportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 273 /* SyntaxKind.NamedExports */: ts.Debug.type(node); return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); @@ -378258,6 +379547,126 @@ var ts; return !ts.isStatic(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); } ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; + if (decorators || ts.hasDecorators(parameter)) { + if (!decorators) { + decorators = new Array(numParameters); + } + decorators[i] = ts.getDecorators(parameter); + } + } + } + return decorators; + } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ + function getAllDecoratorsOfClass(node) { + var decorators = ts.getDecorators(node); + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + ts.getAllDecoratorsOfClass = getAllDecoratorsOfClass; + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param parent The class node that contains the member. + * @param member The class member. + */ + function getAllDecoratorsOfClassElement(member, parent) { + switch (member.kind) { + case 172 /* SyntaxKind.GetAccessor */: + case 173 /* SyntaxKind.SetAccessor */: + return getAllDecoratorsOfAccessors(member, parent); + case 169 /* SyntaxKind.MethodDeclaration */: + return getAllDecoratorsOfMethod(member); + case 167 /* SyntaxKind.PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + ts.getAllDecoratorsOfClassElement = getAllDecoratorsOfClassElement; + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param parent The class node that contains the accessor. + * @param accessor The class accessor member. + */ + function getAllDecoratorsOfAccessors(accessor, parent) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(parent.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var firstAccessorWithDecorators = ts.hasDecorators(firstAccessor) ? firstAccessor : + secondAccessor && ts.hasDecorators(secondAccessor) ? secondAccessor : + undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return undefined; + } + var decorators = ts.getDecorators(firstAccessorWithDecorators); + var parameters = getDecoratorsOfParameters(setAccessor); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters, + getDecorators: getAccessor && ts.getDecorators(getAccessor), + setDecorators: setAccessor && ts.getDecorators(setAccessor) + }; + } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = ts.getDecorators(method); + var parameters = getDecoratorsOfParameters(method); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ + function getAllDecoratorsOfProperty(property) { + var decorators = ts.getDecorators(property); + if (!ts.some(decorators)) { + return undefined; + } + return { decorators: decorators }; + } })(ts || (ts = {})); /*@internal*/ var ts; @@ -378531,8 +379940,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* FlattenLevel.ObjectRest */ - && !(element.transformFlags & (16384 /* TransformFlags.ContainsRestOrSpread */ | 32768 /* TransformFlags.ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 /* TransformFlags.ContainsRestOrSpread */ | 32768 /* TransformFlags.ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (32768 /* TransformFlags.ContainsRestOrSpread */ | 65536 /* TransformFlags.ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (32768 /* TransformFlags.ContainsRestOrSpread */ | 65536 /* TransformFlags.ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor)); } @@ -378598,7 +380007,7 @@ var ts; if (flattenContext.level >= 1 /* FlattenLevel.ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if (element.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { @@ -378820,8 +380229,6 @@ var ts; var USE_NEW_TYPE_METADATA_FORMAT = false; var TypeScriptSubstitutionFlags; (function (TypeScriptSubstitutionFlags) { - /** Enables substitutions for decorated classes. */ - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; /** Enables substitutions for namespace exports. */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; /* Enables substitutions for unqualified enum members */ @@ -378847,9 +380254,9 @@ var ts; var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); - var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var typeSerializer = compilerOptions.emitDecoratorMetadata ? ts.createRuntimeTypeSerializer(context) : undefined; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -378864,7 +380271,6 @@ var ts; var currentNamespace; var currentNamespaceContainerName; var currentLexicalScope; - var currentNameScope; var currentScopeFirstDeclarationsOfName; var currentClassHasParameterProperties; /** @@ -378872,11 +380278,6 @@ var ts; * They are persisted between each SourceFile transformation and should not be reset. */ var enabledSubstitutions; - /** - * A map that keeps track of aliases created for classes with decorators to avoid issues - * with the double-binding behavior of classes. - */ - var classAliases; /** * Keeps track of whether we are within any containing namespaces when performing * just-in-time substitution while printing an expression identifier. @@ -378920,7 +380321,6 @@ var ts; function saveStateAndInvoke(node, f) { // Save state var savedCurrentScope = currentLexicalScope; - var savedCurrentNameScope = currentNameScope; var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties; // Handle state changes before visiting a node. @@ -378931,7 +380331,6 @@ var ts; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; } currentLexicalScope = savedCurrentScope; - currentNameScope = savedCurrentNameScope; currentClassHasParameterProperties = savedCurrentClassHasParameterProperties; return visited; } @@ -378947,7 +380346,6 @@ var ts; case 262 /* SyntaxKind.ModuleBlock */: case 235 /* SyntaxKind.Block */: currentLexicalScope = node; - currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; case 257 /* SyntaxKind.ClassDeclaration */: @@ -378965,10 +380363,6 @@ var ts; // programs may also have an undefined name. ts.Debug.assert(node.kind === 257 /* SyntaxKind.ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)); } - if (ts.isClassDeclaration(node)) { - // XXX: should probably also cover interfaces and type aliases that can have type variables? - currentNameScope = node; - } break; } } @@ -379070,40 +380464,73 @@ var ts; return node; } /** - * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * Gets a specialized visitor that visits the immediate children of a class with TypeScript syntax. * - * @param node The node to visit. + * @param parent The class containing the elements to visit. */ - function classElementVisitor(node) { - return saveStateAndInvoke(node, classElementVisitorWorker); + function getClassElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return classElementVisitorWorker(n, parent); }); }; } /** * Specialized visitor that visits the immediate children of a class with TypeScript syntax. * * @param node The node to visit. */ - function classElementVisitorWorker(node) { + function classElementVisitorWorker(node, parent) { switch (node.kind) { case 171 /* SyntaxKind.Constructor */: return visitConstructor(node); case 167 /* SyntaxKind.PropertyDeclaration */: // Property declarations are not TypeScript syntax, but they must be visited // for the decorator transformation. - return visitPropertyDeclaration(node); - case 176 /* SyntaxKind.IndexSignature */: + return visitPropertyDeclaration(node, parent); case 172 /* SyntaxKind.GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node, parent); case 173 /* SyntaxKind.SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node, parent); case 169 /* SyntaxKind.MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node, parent); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - // Fallback to the default visit behavior. - return visitorWorker(node); + return ts.visitEachChild(node, visitor, context); case 234 /* SyntaxKind.SemicolonClassElement */: return node; + case 176 /* SyntaxKind.IndexSignature */: + // Index signatures are elided + return; + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function getObjectLiteralElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return objectLiteralElementVisitorWorker(n, parent); }); }; + } + function objectLiteralElementVisitorWorker(node, parent) { + switch (node.kind) { + case 296 /* SyntaxKind.PropertyAssignment */: + case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 298 /* SyntaxKind.SpreadAssignment */: + return visitor(node); + case 172 /* SyntaxKind.GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node, parent); + case 173 /* SyntaxKind.SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node, parent); + case 169 /* SyntaxKind.MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node, parent); default: return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { + if (ts.isDecorator(node)) + return undefined; if (ts.modifierToFlag(node.kind) & 116958 /* ModifierFlags.TypeScriptModifier */) { return undefined; } @@ -379171,22 +380598,14 @@ var ts; // TypeScript type nodes are elided. // falls through case 176 /* SyntaxKind.IndexSignature */: - // TypeScript index signatures are elided. - // falls through - case 165 /* SyntaxKind.Decorator */: - // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + // TypeScript index signatures are elided. return undefined; case 259 /* SyntaxKind.TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return factory.createNotEmittedStatement(node); - case 167 /* SyntaxKind.PropertyDeclaration */: - // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects - return visitPropertyDeclaration(node); case 264 /* SyntaxKind.NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 171 /* SyntaxKind.Constructor */: - return visitConstructor(node); case 258 /* SyntaxKind.InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. @@ -379220,16 +380639,15 @@ var ts; case 228 /* SyntaxKind.ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); + case 205 /* SyntaxKind.ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 171 /* SyntaxKind.Constructor */: + case 167 /* SyntaxKind.PropertyDeclaration */: case 169 /* SyntaxKind.MethodDeclaration */: - // TypeScript method declarations may have decorators, modifiers - // or type annotations. - return visitMethodDeclaration(node); case 172 /* SyntaxKind.GetAccessor */: - // Get Accessors can have TypeScript modifiers, decorators, and type annotations. - return visitGetAccessor(node); case 173 /* SyntaxKind.SetAccessor */: - // Set Accessors can have TypeScript modifiers and type annotations. - return visitSetAccessor(node); + case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + return ts.Debug.fail("Class and object literal elements must be visited with their respective visitors"); case 256 /* SyntaxKind.FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); @@ -379295,6 +380713,9 @@ var ts; !ts.isJsonSourceFile(node); return factory.updateSourceFile(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } + function visitObjectLiteralExpression(node) { + return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, getObjectLiteralElementVisitor(node), ts.isObjectLiteralElement)); + } function getClassFacts(node, staticProperties) { var facts = 0 /* ClassFacts.None */; if (ts.some(staticProperties)) @@ -379317,17 +380738,18 @@ var ts; return facts; } function hasTypeScriptClassSyntax(node) { - return !!(node.transformFlags & 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */); + return !!(node.transformFlags & 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */); } function isClassLikeDeclarationWithTypeScriptSyntax(node) { - return ts.some(node.decorators) + return ts.hasDecorators(node) || ts.some(node.typeParameters) || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) || ts.some(node.members, hasTypeScriptClassSyntax); } function visitClassDeclaration(node) { if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */))) { - return ts.visitEachChild(node, visitor, context); + return factory.updateClassDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); var facts = getClassFacts(node, staticProperties); @@ -379335,14 +380757,25 @@ var ts; context.startLexicalEnvironment(); } var name = node.name || (facts & 5 /* ClassFacts.NeedsName */ ? factory.getGeneratedNameForNode(node) : undefined); - var classStatement = facts & 2 /* ClassFacts.HasConstructorDecorators */ - ? createClassDeclarationHeadWithDecorators(node, name) - : createClassDeclarationHeadWithoutDecorators(node, name, facts); + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : ts.elideNodes(factory, node.modifiers); // preserve positions, if available + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var classStatement = factory.updateClassDeclaration(node, ts.concatenate(decorators, modifiers), name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + var emitFlags = ts.getEmitFlags(node); + if (facts & 1 /* ClassFacts.HasStaticInitializedProperties */) { + emitFlags |= 32 /* EmitFlags.NoTrailingSourceMap */; + } + ts.setEmitFlags(classStatement, emitFlags); var statements = [classStatement]; - // Write any decorators of the node. - addClassElementDecorationStatements(statements, node, /*isStatic*/ false); - addClassElementDecorationStatements(statements, node, /*isStatic*/ true); - addConstructorDecorationStatement(statements, node); if (facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) { // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the // 'es2015' transformer can properly nest static initializers and decorators. The result @@ -379402,164 +380835,13 @@ var ts; } return ts.singleOrMany(statements); } - /** - * Transforms a non-decorated class declaration and appends the resulting statements. - * - * @param node A ClassDeclaration node. - * @param name The name of the class. - * @param facts Precomputed facts about the class. - */ - function createClassDeclarationHeadWithoutDecorators(node, name, facts) { - // ${modifiers} class ${name} ${heritageClauses} { - // ${members} - // } - // we do not emit modifiers on the declaration if we are emitting an IIFE - var modifiers = !(facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) - ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) - : undefined; - var classDeclaration = factory.createClassDeclaration( - /*decorators*/ undefined, modifiers, name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - // To better align with the old emitter, we should not emit a trailing source map - // entry if the class has static properties. - var emitFlags = ts.getEmitFlags(node); - if (facts & 1 /* ClassFacts.HasStaticInitializedProperties */) { - emitFlags |= 32 /* EmitFlags.NoTrailingSourceMap */; - } - ts.setTextRange(classDeclaration, node); - ts.setOriginalNode(classDeclaration, node); - ts.setEmitFlags(classDeclaration, emitFlags); - return classDeclaration; - } - /** - * Transforms a decorated class declaration and appends the resulting statements. If - * the class requires an alias to avoid issues with double-binding, the alias is returned. - */ - function createClassDeclarationHeadWithDecorators(node, name) { - // When we emit an ES6 class that has a class decorator, we must tailor the - // emit to certain specific cases. - // - // In the simplest case, we emit the class declaration as a let declaration, and - // evaluate decorators after the close of the class body: - // - // [Example 1] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = class C { - // class C { | } - // } | C = __decorate([dec], C); - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export class C { | } - // } | C = __decorate([dec], C); - // | export { C }; - // --------------------------------------------------------------------- - // - // If a class declaration contains a reference to itself *inside* of the class body, - // this introduces two bindings to the class: One outside of the class body, and one - // inside of the class body. If we apply decorators as in [Example 1] above, there - // is the possibility that the decorator `dec` will return a new value for the - // constructor, which would result in the binding inside of the class no longer - // pointing to the same reference as the binding outside of the class. - // - // As a result, we must instead rewrite all references to the class *inside* of the - // class body to instead point to a local temporary alias for the class: - // - // [Example 2] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = C_1 = class C { - // class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | var C_1; - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | export { C }; - // | var C_1; - // --------------------------------------------------------------------- - // - // If a class declaration is the default export of a module, we instead emit - // the export after the decorated declaration: - // - // [Example 3] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let default_1 = class { - // export default class { | } - // } | default_1 = __decorate([dec], default_1); - // | export default default_1; - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export default class C { | } - // } | C = __decorate([dec], C); - // | export default C; - // --------------------------------------------------------------------- - // - // If the class declaration is the default export and a reference to itself - // inside of the class body, we must emit both an alias for the class *and* - // move the export after the declaration: - // - // [Example 4] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export default class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | export default C; - // | var C_1; - // --------------------------------------------------------------------- - // - var location = ts.moveRangePastDecorators(node); - var classAlias = getClassAliasIfNeeded(node); - // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name - // without any block-scoped variable collision handling - var declName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? - factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); - // ... = class ${name} ${heritageClauses} { - // ${members} - // } - var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node); - var classExpression = factory.createClassExpression(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, location); - // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference - // or decoratedClassAlias if the class contain self-reference. - var statement = factory.createVariableStatement( - /*modifiers*/ undefined, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(declName, - /*exclamationToken*/ undefined, - /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) - ], 1 /* NodeFlags.Let */)); - ts.setOriginalNode(statement, node); - ts.setTextRange(statement, location); - ts.setCommentRange(statement, node); - return statement; - } function visitClassExpression(node) { - if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { - return ts.visitEachChild(node, visitor, context); - } - var classExpression = factory.createClassExpression( - /*decorators*/ undefined, - /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, node); - return classExpression; + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + return factory.updateClassExpression(node, decorators, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), isClassLikeDeclarationWithTypeScriptSyntax(node) ? + transformClassMembers(node) : + ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } /** * Transforms the members of a class. @@ -379576,7 +380858,6 @@ var ts; var parameter = parametersWithPropertyAssignments_1[_i]; if (ts.isIdentifier(parameter.name)) { members.push(ts.setOriginalNode(factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, parameter.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, @@ -379584,159 +380865,9 @@ var ts; } } } - ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + ts.addRange(members, ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); } - /** - * Gets either the static or instance members of a class that are decorated, or have - * parameters that are decorated. - * - * @param node The class containing the member. - * @param isStatic A value indicating whether to retrieve static or instance members of - * the class. - */ - function getDecoratedClassElements(node, isStatic) { - return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); - } - /** - * Determines whether a class member is a static member of a class that is decorated, or - * has parameters that are decorated. - * - * @param member The class member. - */ - function isStaticDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, /*isStaticElement*/ true, parent); - } - /** - * Determines whether a class member is an instance member of a class that is decorated, - * or has parameters that are decorated. - * - * @param member The class member. - */ - function isInstanceDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, /*isStaticElement*/ false, parent); - } - /** - * Determines whether a class member is either a static or an instance member of a class - * that is decorated, or has parameters that are decorated. - * - * @param member The class member. - */ - function isDecoratedClassElement(member, isStaticElement, parent) { - return ts.nodeOrChildIsDecorated(member, parent) - && isStaticElement === ts.isStatic(member); - } - /** - * Gets an array of arrays of decorators for the parameters of a function-like node. - * The offset into the result array should correspond to the offset of the parameter. - * - * @param node The function-like node. - */ - function getDecoratorsOfParameters(node) { - var decorators; - if (node) { - var parameters = node.parameters; - var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); - var firstParameterOffset = firstParameterIsThis ? 1 : 0; - var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i + firstParameterOffset]; - if (decorators || parameter.decorators) { - if (!decorators) { - decorators = new Array(numParameters); - } - decorators[i] = parameter.decorators; - } - } - } - return decorators; - } - /** - * Gets an AllDecorators object containing the decorators for the class and the decorators for the - * parameters of the constructor of the class. - * - * @param node The class node. - */ - function getAllDecoratorsOfConstructor(node) { - var decorators = node.decorators; - var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); - if (!decorators && !parameters) { - return undefined; - } - return { - decorators: decorators, - parameters: parameters - }; - } - /** - * Gets an AllDecorators object containing the decorators for the member and its parameters. - * - * @param node The class node that contains the member. - * @param member The class member. - */ - function getAllDecoratorsOfClassElement(node, member) { - switch (member.kind) { - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - return getAllDecoratorsOfAccessors(node, member); - case 169 /* SyntaxKind.MethodDeclaration */: - return getAllDecoratorsOfMethod(member); - case 167 /* SyntaxKind.PropertyDeclaration */: - return getAllDecoratorsOfProperty(member); - default: - return undefined; - } - } - /** - * Gets an AllDecorators object containing the decorators for the accessor and its parameters. - * - * @param node The class node that contains the accessor. - * @param accessor The class accessor member. - */ - function getAllDecoratorsOfAccessors(node, accessor) { - if (!accessor.body) { - return undefined; - } - var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; - if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { - return undefined; - } - var decorators = firstAccessorWithDecorators.decorators; - var parameters = getDecoratorsOfParameters(setAccessor); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - /** - * Gets an AllDecorators object containing the decorators for the method and its parameters. - * - * @param method The class method member. - */ - function getAllDecoratorsOfMethod(method) { - if (!method.body) { - return undefined; - } - var decorators = method.decorators; - var parameters = getDecoratorsOfParameters(method); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - /** - * Gets an AllDecorators object containing the decorators for the property. - * - * @param property The class property member. - */ - function getAllDecoratorsOfProperty(property) { - var decorators = property.decorators; - if (!decorators) { - return undefined; - } - return { decorators: decorators }; - } /** * Transforms all of the decorators for a declaration into an array of expressions. * @@ -379744,212 +380875,89 @@ var ts; * @param allDecorators An object containing all of the decorators for the declaration. */ function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { + var _a, _b, _c, _d; if (!allDecorators) { return undefined; } - var decoratorExpressions = []; - ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); - ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, container, decoratorExpressions); - return decoratorExpressions; - } - /** - * Generates statements used to apply decorators to either the static or instance members - * of a class. - * - * @param node The class node. - * @param isStatic A value indicating whether to generate statements for static or - * instance members. - */ - function addClassElementDecorationStatements(statements, node, isStatic) { - ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); - } - /** - * Generates expressions used to apply decorators to either the static or instance members - * of a class. - * - * @param node The class node. - * @param isStatic A value indicating whether to generate expressions for static or - * instance members. - */ - function generateClassElementDecorationExpressions(node, isStatic) { - var members = getDecoratedClassElements(node, isStatic); - var expressions; - for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { - var member = members_8[_i]; - var expression = generateClassElementDecorationExpression(node, member); - if (expression) { - if (!expressions) { - expressions = [expression]; - } - else { - expressions.push(expression); - } - } - } - return expressions; - } - /** - * Generates an expression used to evaluate class element decorators at runtime. - * - * @param node The class node that contains the member. - * @param member The class member. - */ - function generateClassElementDecorationExpression(node, member) { - var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - // Emit the call to __decorate. Given the following: - // - // class C { - // @dec method(@dec2 x) {} - // @dec get accessor() {} - // @dec prop; - // } - // - // The emit for a method is: - // - // __decorate([ - // dec, - // __param(0, dec2), - // __metadata("design:type", Function), - // __metadata("design:paramtypes", [Object]), - // __metadata("design:returntype", void 0) - // ], C.prototype, "method", null); - // - // The emit for an accessor is: - // - // __decorate([ - // dec - // ], C.prototype, "accessor", null); - // - // The emit for a property is: - // - // __decorate([ - // dec - // ], C.prototype, "prop"); - // - var prefix = getClassMemberPrefix(node, member); - var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* ModifierFlags.Ambient */)); - var descriptor = languageVersion > 0 /* ScriptTarget.ES3 */ - ? member.kind === 167 /* SyntaxKind.PropertyDeclaration */ - // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it - // should not invoke `Object.getOwnPropertyDescriptor`. - ? factory.createVoidZero() - // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. - // We have this extra argument here so that we can inject an explicit property descriptor at a later date. - : factory.createNull() - : undefined; - var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); - ts.setTextRange(helper, ts.moveRangePastDecorators(member)); - ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); - return helper; - } - /** - * Generates a __decorate helper call for a class constructor. - * - * @param node The class node. - */ - function addConstructorDecorationStatement(statements, node) { - var expression = generateConstructorDecorationExpression(node); - if (expression) { - statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); - } - } - /** - * Generates a __decorate helper call for a class constructor. - * - * @param node The class node. - */ - function generateConstructorDecorationExpression(node) { - var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; - // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name - // without any block-scoped variable collision handling - var localName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? - factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); - var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); - var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); - ts.setEmitFlags(expression, 1536 /* EmitFlags.NoComments */); - ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); - return expression; - } - /** - * Transforms a decorator into an expression. - * - * @param decorator The decorator node. - */ - function transformDecorator(decorator) { - return ts.visitNode(decorator.expression, visitor, ts.isExpression); + var decorators = ts.visitArray(allDecorators.decorators, visitor, ts.isDecorator); + var parameterDecorators = ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter); + var metadataDecorators = ts.some(decorators) || ts.some(parameterDecorators) ? getTypeMetadata(node, container) : undefined; + var result = factory.createNodeArray(ts.concatenate(ts.concatenate(decorators, parameterDecorators), metadataDecorators)); + var pos = (_b = (_a = ts.firstOrUndefined(allDecorators.decorators)) === null || _a === void 0 ? void 0 : _a.pos) !== null && _b !== void 0 ? _b : -1; + var end = (_d = (_c = ts.lastOrUndefined(allDecorators.decorators)) === null || _c === void 0 ? void 0 : _c.end) !== null && _d !== void 0 ? _d : -1; + ts.setTextRangePosEnd(result, pos, end); + return result; } /** - * Transforms the decorators of a parameter. + * Transforms the decorators of a parameter into decorators of the class/method. * - * @param decorators The decorators for the parameter at the provided offset. + * @param parameterDecorators The decorators for the parameter at the provided offset. * @param parameterOffset The offset of the parameter. */ - function transformDecoratorsOfParameter(decorators, parameterOffset) { - var expressions; - if (decorators) { - expressions = []; - for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { - var decorator = decorators_1[_i]; - var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); - ts.setTextRange(helper, decorator.expression); + function transformDecoratorsOfParameter(parameterDecorators, parameterOffset) { + if (parameterDecorators) { + var decorators = []; + for (var _i = 0, parameterDecorators_1 = parameterDecorators; _i < parameterDecorators_1.length; _i++) { + var parameterDecorator = parameterDecorators_1[_i]; + var expression = ts.visitNode(parameterDecorator.expression, visitor, ts.isExpression); + var helper = emitHelpers().createParamHelper(expression, parameterOffset); + ts.setTextRange(helper, parameterDecorator.expression); ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); - expressions.push(helper); + var decorator = factory.createDecorator(helper); + ts.setSourceMapRange(decorator, parameterDecorator.expression); + ts.setCommentRange(decorator, parameterDecorator.expression); + ts.setEmitFlags(decorator, 1536 /* EmitFlags.NoComments */); + decorators.push(decorator); } + return decorators; } - return expressions; } /** - * Adds optional type metadata for a declaration. + * Gets optional type metadata for a declaration. * * @param node The declaration node. - * @param decoratorExpressions The destination array to which to add new decorator expressions. */ - function addTypeMetadata(node, container, decoratorExpressions) { - if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, container, decoratorExpressions); - } - else { - addOldTypeMetadata(node, container, decoratorExpressions); - } + function getTypeMetadata(node, container) { + return USE_NEW_TYPE_METADATA_FORMAT ? + getNewTypeMetadata(node, container) : + getOldTypeMetadata(node, container); } - function addOldTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getOldTypeMetadata(node, container) { + if (typeSerializer) { + var decorators = void 0; if (shouldAddTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:type", serializeTypeOfNode(node))); + var typeMetadata = emitHelpers().createMetadataHelper("design:type", typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(typeMetadata)); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:paramtypes", serializeParameterTypesOfNode(node, container))); + var paramTypesMetadata = emitHelpers().createMetadataHelper("design:paramtypes", typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container)); + decorators = ts.append(decorators, factory.createDecorator(paramTypesMetadata)); } if (shouldAddReturnTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:returntype", serializeReturnTypeOfNode(node))); + var returnTypeMetadata = emitHelpers().createMetadataHelper("design:returntype", typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(returnTypeMetadata)); } + return decorators; } } - function addNewTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getNewTypeMetadata(node, container) { + if (typeSerializer) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + var typeProperty = factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, typeProperty); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + var paramTypeProperty = factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container))); + properties = ts.append(properties, paramTypeProperty); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + var returnTypeProperty = factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, returnTypeProperty); } if (properties) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true))); + var typeInfoMetadata = emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true)); + return [factory.createDecorator(typeInfoMetadata)]; } } } @@ -379996,347 +381004,6 @@ var ts; } return false; } - function getAccessorTypeNode(node) { - var accessors = resolver.getAllAccessorDeclarations(node); - return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) - || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); - } - /** - * Serializes the type of a node for use with decorator type metadata. - * - * @param node The node that should have its type serialized. - */ - function serializeTypeOfNode(node) { - switch (node.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 164 /* SyntaxKind.Parameter */: - return serializeTypeNode(node.type); - case 173 /* SyntaxKind.SetAccessor */: - case 172 /* SyntaxKind.GetAccessor */: - return serializeTypeNode(getAccessorTypeNode(node)); - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - return factory.createIdentifier("Function"); - default: - return factory.createVoidZero(); - } - } - /** - * Serializes the types of the parameters of a node for use with decorator type metadata. - * - * @param node The node that should have its parameter types serialized. - */ - function serializeParameterTypesOfNode(node, container) { - var valueDeclaration = ts.isClassLike(node) - ? ts.getFirstConstructorWithBody(node) - : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) - ? node - : undefined; - var expressions = []; - if (valueDeclaration) { - var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); - var numParameters = parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i]; - if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { - continue; - } - if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); - } - else { - expressions.push(serializeTypeOfNode(parameter)); - } - } - } - return factory.createArrayLiteralExpression(expressions); - } - function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 172 /* SyntaxKind.GetAccessor */) { - var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; - if (setAccessor) { - return setAccessor.parameters; - } - } - return node.parameters; - } - /** - * Serializes the return type of a node for use with decorator type metadata. - * - * @param node The node that should have its return type serialized. - */ - function serializeReturnTypeOfNode(node) { - if (ts.isFunctionLike(node) && node.type) { - return serializeTypeNode(node.type); - } - else if (ts.isAsyncFunction(node)) { - return factory.createIdentifier("Promise"); - } - return factory.createVoidZero(); - } - /** - * Serializes a type node for use with decorator type metadata. - * - * Types are serialized in the following fashion: - * - Void types point to "undefined" (e.g. "void 0") - * - Function and Constructor types point to the global "Function" constructor. - * - Interface types with a call or construct signature types point to the global - * "Function" constructor. - * - Array and Tuple types point to the global "Array" constructor. - * - Type predicates and booleans point to the global "Boolean" constructor. - * - String literal types and strings point to the global "String" constructor. - * - Enum and number types point to the global "Number" constructor. - * - Symbol types point to the global "Symbol" constructor. - * - Type references to classes (or class-like variables) point to the constructor for the class. - * - Anything else points to the global "Object" constructor. - * - * @param node The type node to serialize. - */ - function serializeTypeNode(node) { - if (node === undefined) { - return factory.createIdentifier("Object"); - } - switch (node.kind) { - case 114 /* SyntaxKind.VoidKeyword */: - case 153 /* SyntaxKind.UndefinedKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: - return factory.createVoidZero(); - case 191 /* SyntaxKind.ParenthesizedType */: - return serializeTypeNode(node.type); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - return factory.createIdentifier("Function"); - case 183 /* SyntaxKind.ArrayType */: - case 184 /* SyntaxKind.TupleType */: - return factory.createIdentifier("Array"); - case 177 /* SyntaxKind.TypePredicate */: - case 133 /* SyntaxKind.BooleanKeyword */: - return factory.createIdentifier("Boolean"); - case 198 /* SyntaxKind.TemplateLiteralType */: - case 150 /* SyntaxKind.StringKeyword */: - return factory.createIdentifier("String"); - case 148 /* SyntaxKind.ObjectKeyword */: - return factory.createIdentifier("Object"); - case 196 /* SyntaxKind.LiteralType */: - switch (node.literal.kind) { - case 10 /* SyntaxKind.StringLiteral */: - case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: - return factory.createIdentifier("String"); - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 8 /* SyntaxKind.NumericLiteral */: - return factory.createIdentifier("Number"); - case 9 /* SyntaxKind.BigIntLiteral */: - return getGlobalBigIntNameWithFallback(); - case 110 /* SyntaxKind.TrueKeyword */: - case 95 /* SyntaxKind.FalseKeyword */: - return factory.createIdentifier("Boolean"); - case 104 /* SyntaxKind.NullKeyword */: - return factory.createVoidZero(); - default: - return ts.Debug.failBadSyntaxKind(node.literal); - } - case 147 /* SyntaxKind.NumberKeyword */: - return factory.createIdentifier("Number"); - case 158 /* SyntaxKind.BigIntKeyword */: - return getGlobalBigIntNameWithFallback(); - case 151 /* SyntaxKind.SymbolKeyword */: - return languageVersion < 2 /* ScriptTarget.ES2015 */ - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case 178 /* SyntaxKind.TypeReference */: - return serializeTypeReferenceNode(node); - case 188 /* SyntaxKind.IntersectionType */: - case 187 /* SyntaxKind.UnionType */: - return serializeTypeList(node.types); - case 189 /* SyntaxKind.ConditionalType */: - return serializeTypeList([node.trueType, node.falseType]); - case 193 /* SyntaxKind.TypeOperator */: - if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { - return serializeTypeNode(node.type); - } - break; - case 181 /* SyntaxKind.TypeQuery */: - case 194 /* SyntaxKind.IndexedAccessType */: - case 195 /* SyntaxKind.MappedType */: - case 182 /* SyntaxKind.TypeLiteral */: - case 130 /* SyntaxKind.AnyKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: - case 192 /* SyntaxKind.ThisType */: - case 200 /* SyntaxKind.ImportType */: - break; - // handle JSDoc types from an invalid parse - case 312 /* SyntaxKind.JSDocAllType */: - case 313 /* SyntaxKind.JSDocUnknownType */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 318 /* SyntaxKind.JSDocVariadicType */: - case 319 /* SyntaxKind.JSDocNamepathType */: - break; - case 314 /* SyntaxKind.JSDocNullableType */: - case 315 /* SyntaxKind.JSDocNonNullableType */: - case 316 /* SyntaxKind.JSDocOptionalType */: - return serializeTypeNode(node.type); - default: - return ts.Debug.failBadSyntaxKind(node); - } - return factory.createIdentifier("Object"); - } - function serializeTypeList(types) { - // Note when updating logic here also update getEntityNameForDecoratorMetadata - // so that aliases can be marked as referenced - var serializedUnion; - for (var _i = 0, types_23 = types; _i < types_23.length; _i++) { - var typeNode = types_23[_i]; - while (typeNode.kind === 191 /* SyntaxKind.ParenthesizedType */) { - typeNode = typeNode.type; // Skip parens if need be - } - if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { - continue; // Always elide `never` from the union/intersection if possible - } - if (!strictNullChecks && (typeNode.kind === 196 /* SyntaxKind.LiteralType */ && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */ || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { - continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks - } - var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { - // One of the individual is global object, return immediately - return serializedIndividual; - } - // If there exists union that is not void 0 expression, check if the the common type is identifier. - // anything more complex and we will just default to Object - else if (serializedUnion) { - // Different types - if (!ts.isIdentifier(serializedUnion) || - !ts.isIdentifier(serializedIndividual) || - serializedUnion.escapedText !== serializedIndividual.escapedText) { - return factory.createIdentifier("Object"); - } - } - else { - // Initialize the union type - serializedUnion = serializedIndividual; - } - } - // If we were able to find common type, use it - return serializedUnion || factory.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never - } - /** - * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with - * decorator type metadata. - * - * @param node The type reference node. - */ - function serializeTypeReferenceNode(node) { - var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); - switch (kind) { - case ts.TypeReferenceSerializationKind.Unknown: - // From conditional type type reference that cannot be resolved is Similar to any or unknown - if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { - return factory.createIdentifier("Object"); - } - var serialized = serializeEntityNameAsExpressionFallback(node.typeName); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createConditionalExpression(factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"), - /*questionToken*/ undefined, temp, - /*colonToken*/ undefined, factory.createIdentifier("Object")); - case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName); - case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: - return factory.createVoidZero(); - case ts.TypeReferenceSerializationKind.BigIntLikeType: - return getGlobalBigIntNameWithFallback(); - case ts.TypeReferenceSerializationKind.BooleanType: - return factory.createIdentifier("Boolean"); - case ts.TypeReferenceSerializationKind.NumberLikeType: - return factory.createIdentifier("Number"); - case ts.TypeReferenceSerializationKind.StringLikeType: - return factory.createIdentifier("String"); - case ts.TypeReferenceSerializationKind.ArrayLikeType: - return factory.createIdentifier("Array"); - case ts.TypeReferenceSerializationKind.ESSymbolType: - return languageVersion < 2 /* ScriptTarget.ES2015 */ - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case ts.TypeReferenceSerializationKind.TypeWithCallSignature: - return factory.createIdentifier("Function"); - case ts.TypeReferenceSerializationKind.Promise: - return factory.createIdentifier("Promise"); - case ts.TypeReferenceSerializationKind.ObjectType: - return factory.createIdentifier("Object"); - default: - return ts.Debug.assertNever(kind); - } - } - function createCheckedValue(left, right) { - return factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), right); - } - /** - * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw - * - * @param node The entity name to serialize. - */ - function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 79 /* SyntaxKind.Identifier */) { - // A -> typeof A !== undefined && A - var copied = serializeEntityNameAsExpression(node); - return createCheckedValue(copied, copied); - } - if (node.left.kind === 79 /* SyntaxKind.Identifier */) { - // A.B -> typeof A !== undefined && A.B - return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); - } - // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C - var left = serializeEntityNameAsExpressionFallback(node.left); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createLogicalAnd(factory.createLogicalAnd(left.left, factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero())), factory.createPropertyAccessExpression(temp, node.right)); - } - /** - * Serializes an entity name as an expression for decorator type metadata. - * - * @param node The entity name to serialize. - */ - function serializeEntityNameAsExpression(node) { - switch (node.kind) { - case 79 /* SyntaxKind.Identifier */: - // Create a clone of the name with a new parent, and treat it as if it were - // a source tree node for the purposes of the checker. - var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); - name.original = undefined; - ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. - return name; - case 161 /* SyntaxKind.QualifiedName */: - return serializeQualifiedNameAsExpression(node); - } - } - /** - * Serializes an qualified name as an expression for decorator type metadata. - * - * @param node The qualified name to serialize. - * @param useFallback A value indicating whether to use logical operators to test for the - * qualified name at runtime. - */ - function serializeQualifiedNameAsExpression(node) { - return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); - } - /** - * Gets an expression that points to the global "Symbol" constructor at runtime if it is - * available. - */ - function getGlobalSymbolNameWithFallback() { - return factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("Symbol"), "function"), - /*questionToken*/ undefined, factory.createIdentifier("Symbol"), - /*colonToken*/ undefined, factory.createIdentifier("Object")); - } - /** - * Gets an expression that points to the global "BigInt" constructor at runtime if it is - * available. - */ - function getGlobalBigIntNameWithFallback() { - return languageVersion < 99 /* ScriptTarget.ESNext */ - ? factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("BigInt"), "function"), - /*questionToken*/ undefined, factory.createIdentifier("BigInt"), - /*colonToken*/ undefined, factory.createIdentifier("Object")) - : factory.createIdentifier("BigInt"); - } /** * Gets an expression that represents a property name (for decorated properties or enums). * For a computed property, a name is generated for the node. @@ -380373,7 +381040,7 @@ var ts; // The names are used more than once when: // - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments). // - the property has a decorator. - if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) { + if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.hasDecorators(member))) { var expression = ts.visitNode(name.expression, visitor, ts.isExpression); var innerExpression = ts.skipPartiallyEmittedExpressions(expression); if (!ts.isSimpleInlineableExpression(innerExpression)) { @@ -380421,28 +381088,29 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } - function visitPropertyDeclaration(node) { - if (node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)) { + function visitPropertyDeclaration(node, parent) { + var isAmbient = node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */); + if (isAmbient && !ts.hasDecorators(node)) { return undefined; } - var updated = factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), + var allDecorators = ts.getAllDecoratorsOfClassElement(node, parent); + var decorators = transformAllDecoratorsOfDeclaration(node, parent, allDecorators); + // Preserve a `declare x` property with decorators to be handled by the decorators transform + if (isAmbient) { + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, factory.createModifiersFromModifierFlags(2 /* ModifierFlags.Ambient */)), ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor)); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } function visitConstructor(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } return factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node)); } function transformConstructorBody(body, constructor) { @@ -380481,7 +381149,8 @@ var ts; statements = __spreadArray(__spreadArray(__spreadArray([], statements.slice(0, prologueStatementCount), true), parameterPropertyAssignments, true), statements.slice(prologueStatementCount), true); } // Add remaining statements from the body, skipping the super() call if it was found and any (already added) prologue statements - ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, superStatementIndex + 1 + prologueStatementCount)); + var start = superStatementIndex >= 0 ? superStatementIndex + 1 : prologueStatementCount; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, start)); // End the lexical environment. statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true); @@ -380507,22 +381176,19 @@ var ts; ts.setEmitFlags(localName, 1536 /* EmitFlags.NoComments */); return ts.startOnNewLine(ts.removeAllComments(ts.setTextRange(ts.setOriginalNode(factory.createExpressionStatement(factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createThis(), propertyName), node.name), localName)), node), ts.moveRangePos(node, -1)))); } - function visitMethodDeclaration(node) { + function visitMethodDeclaration(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - var updated = factory.updateMethodDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + var allDecorators = ts.isClassLike(parent) ? ts.getAllDecoratorsOfClassElement(node, parent) : undefined; + var decorators = ts.isClassLike(parent) ? transformAllDecoratorsOfDeclaration(node, parent, allDecorators) : undefined; + return factory.updateMethodDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), node.asteriskToken, visitPropertyNameOfClassElement(node), /*questionToken*/ undefined, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } /** * Determines whether to emit an accessor declaration. We should not emit the @@ -380533,41 +381199,36 @@ var ts; function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)); } - function visitGetAccessor(node) { + function visitGetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateGetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } - function visitSetAccessor(node) { + function visitSetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateSetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); } function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return factory.createNotEmittedStatement(node); } - var updated = factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + var updated = factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); if (isExportOfNamespace(node)) { @@ -380596,9 +381257,8 @@ var ts; if (ts.parameterIsThisKeyword(node)) { return undefined; } - var updated = factory.updateParameterDeclaration(node, - /*decorators*/ undefined, - /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), // preserve positions, if available + node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); if (updated !== node) { @@ -380758,7 +381418,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformEnumBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); @@ -380988,7 +381648,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformModuleBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); @@ -381101,7 +381761,6 @@ var ts; compilerOptions.importsNotUsedAsValues === 1 /* ImportsNotUsedAsValues.Preserve */ || compilerOptions.importsNotUsedAsValues === 2 /* ImportsNotUsedAsValues.Error */ ? factory.updateImportDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, importClause, node.moduleSpecifier, node.assertClause) : undefined; } @@ -381176,7 +381835,6 @@ var ts; var exportClause = ts.visitNode(node.exportClause, function (bindings) { return visitNamedExportBindings(bindings, allowEmpty); }, ts.isNamedExportBindings); return exportClause ? factory.updateExportDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.isTypeOnly, exportClause, node.moduleSpecifier, node.assertClause) : undefined; } @@ -381234,7 +381892,6 @@ var ts; // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'. if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* ImportsNotUsedAsValues.Preserve */) { return ts.setOriginalNode(ts.setTextRange(factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, node.moduleReference.expression, /*assertClause*/ undefined), node), node); @@ -381294,12 +381951,6 @@ var ts; return isExternalModuleExport(node) && ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */); } - /** - * Creates a statement for the provided expression. This is used in calls to `map`. - */ - function expressionToStatement(expression) { - return factory.createExpressionStatement(expression); - } function addExportMemberAssignment(statements, node) { var expression = factory.createAssignment(factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), factory.getLocalName(node)); ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); @@ -381331,44 +381982,12 @@ var ts; function getNamespaceContainerName(node) { return factory.getGeneratedNameForNode(node); } - /** - * Gets a local alias for a class declaration if it is a decorated class with an internal - * reference to the static side of the class. This is necessary to avoid issues with - * double-binding semantics for the class name. - */ - function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* NodeCheckFlags.ClassWithConstructorReference */) { - enableSubstitutionForClassAliases(); - var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); - classAliases[ts.getOriginalNodeId(node)] = classAlias; - hoistVariableDeclaration(classAlias); - return classAlias; - } - } - function getClassPrototype(node) { - return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); - } - function getClassMemberPrefix(node, member) { - return ts.isStatic(member) - ? factory.getDeclarationName(node) - : getClassPrototype(node); - } function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */) === 0) { enabledSubstitutions |= 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */; context.enableSubstitution(79 /* SyntaxKind.Identifier */); } } - function enableSubstitutionForClassAliases() { - if ((enabledSubstitutions & 1 /* TypeScriptSubstitutionFlags.ClassAliases */) === 0) { - enabledSubstitutions |= 1 /* TypeScriptSubstitutionFlags.ClassAliases */; - // We need to enable substitutions for identifiers. This allows us to - // substitute class names inside of a class declaration. - context.enableSubstitution(79 /* SyntaxKind.Identifier */); - // Keep track of class aliases. - classAliases = []; - } - } function enableSubstitutionForNamespaceExports() { if ((enabledSubstitutions & 2 /* TypeScriptSubstitutionFlags.NamespaceExports */) === 0) { enabledSubstitutions |= 2 /* TypeScriptSubstitutionFlags.NamespaceExports */; @@ -381453,32 +382072,9 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - return trySubstituteClassAlias(node) - || trySubstituteNamespaceExportedName(node) + return trySubstituteNamespaceExportedName(node) || node; } - function trySubstituteClassAlias(node) { - if (enabledSubstitutions & 1 /* TypeScriptSubstitutionFlags.ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 33554432 /* NodeCheckFlags.ConstructorReferenceInClass */) { - // Due to the emit for class decorators, any reference to the class from inside of the class body - // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind - // behavior of class names in ES6. - // Also, when emitting statics for class expressions, we must substitute a class alias for - // constructor references in static property initializers. - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration) { - var classAlias = classAliases[declaration.id]; // TODO: GH#18217 - if (classAlias) { - var clone_2 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; - } - } - } - } - return undefined; - } function trySubstituteNamespaceExportedName(node) { // If this is explicitly a local name, do not substitute. if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { @@ -381616,7 +382212,7 @@ var ts; return visited; } function visitorWorker(node, valueIsDiscarded) { - if (node.transformFlags & 8388608 /* TransformFlags.ContainsClassFields */) { + if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */) { switch (node.kind) { case 226 /* SyntaxKind.ClassExpression */: case 257 /* SyntaxKind.ClassDeclaration */: @@ -381631,8 +382227,8 @@ var ts; return visitClassStaticBlockDeclaration(node); } } - if (node.transformFlags & 8388608 /* TransformFlags.ContainsClassFields */ || - node.transformFlags & 33554432 /* TransformFlags.ContainsLexicalSuper */ && + if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */ || + node.transformFlags & 134217728 /* TransformFlags.ContainsLexicalSuper */ && shouldTransformSuperInStaticInitializers && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { @@ -381772,7 +382368,7 @@ var ts; return node; } function visitMethodOrAccessorDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (!shouldTransformPrivateElementsOrClassStaticBlocks || !ts.isPrivateIdentifier(node.name)) { return ts.visitEachChild(node, classElementVisitor, context); } @@ -381784,7 +382380,7 @@ var ts; } var functionName = getHoistedFunctionName(node); if (functionName) { - getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return ts.isModifier(m) && !ts.isStaticModifier(m); }), node.asteriskToken, functionName, /* typeParameters */ undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), /* type */ undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); } @@ -381808,7 +382404,7 @@ var ts; } } function visitPropertyDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (ts.isPrivateIdentifier(node.name)) { if (!shouldTransformPrivateElementsOrClassStaticBlocks) { if (ts.isStatic(node)) { @@ -381816,8 +382412,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } // Initializer is elided as the field is initialized in transformConstructor. - return factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + return factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); @@ -381839,9 +382434,7 @@ var ts; if (ts.isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) { var initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis()); if (initializerStatement) { - var staticBlock = factory.createClassStaticBlockDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, factory.createBlock([initializerStatement])); + var staticBlock = factory.createClassStaticBlockDeclaration(factory.createBlock([initializerStatement])); ts.setOriginalNode(staticBlock, node); ts.setCommentRange(staticBlock, node); // Set the comment range for the statement to an empty synthetic range @@ -381917,10 +382510,11 @@ var ts; } function visitPreOrPostfixUnaryExpression(node, valueIsDiscarded) { if (node.operator === 45 /* SyntaxKind.PlusPlusToken */ || node.operator === 46 /* SyntaxKind.MinusMinusToken */) { - if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + var operand = ts.skipParentheses(node.operand); + if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(operand)) { var info = void 0; - if (info = accessPrivateIdentifier(node.operand.name)) { - var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression); + if (info = accessPrivateIdentifier(operand.name)) { + var receiver = ts.visitNode(operand.expression, visitor, ts.isExpression); var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression; var expression = createPrivateIdentifierAccess(info, readExpression); var temp = ts.isPrefixUnaryExpression(node) || valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); @@ -381936,7 +382530,7 @@ var ts; } } else if (shouldTransformSuperInStaticInitializers && - ts.isSuperProperty(node.operand) && + ts.isSuperProperty(operand) && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { // converts `++super.a` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = ++_a), _classTemp), _b)` @@ -381949,31 +382543,31 @@ var ts; // converts `super[f()]--` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = _b--), _classTemp), _c)` var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts; if (facts & 1 /* ClassFacts.ClassWasDecorated */) { - var operand = visitInvalidSuperProperty(node.operand); + var expression = visitInvalidSuperProperty(operand); return ts.isPrefixUnaryExpression(node) ? - factory.updatePrefixUnaryExpression(node, operand) : - factory.updatePostfixUnaryExpression(node, operand); + factory.updatePrefixUnaryExpression(node, expression) : + factory.updatePostfixUnaryExpression(node, expression); } if (classConstructor && superClassReference) { var setterName = void 0; var getterName = void 0; - if (ts.isPropertyAccessExpression(node.operand)) { - if (ts.isIdentifier(node.operand.name)) { - getterName = setterName = factory.createStringLiteralFromNode(node.operand.name); + if (ts.isPropertyAccessExpression(operand)) { + if (ts.isIdentifier(operand.name)) { + getterName = setterName = factory.createStringLiteralFromNode(operand.name); } } else { - if (ts.isSimpleInlineableExpression(node.operand.argumentExpression)) { - getterName = setterName = node.operand.argumentExpression; + if (ts.isSimpleInlineableExpression(operand.argumentExpression)) { + getterName = setterName = operand.argumentExpression; } else { getterName = factory.createTempVariable(hoistVariableDeclaration); - setterName = factory.createAssignment(getterName, ts.visitNode(node.operand.argumentExpression, visitor, ts.isExpression)); + setterName = factory.createAssignment(getterName, ts.visitNode(operand.argumentExpression, visitor, ts.isExpression)); } } if (setterName && getterName) { var expression = factory.createReflectGetCall(superClassReference, getterName, classConstructor); - ts.setTextRange(expression, node.operand); + ts.setTextRange(expression, operand); var temp = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); expression = ts.expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp); expression = factory.createReflectSetCall(superClassReference, setterName, expression, classConstructor); @@ -382206,13 +382800,13 @@ var ts; facts |= 2 /* ClassFacts.NeedsClassConstructorReference */; } if (ts.isPropertyDeclaration(member) || ts.isClassStaticBlockDeclaration(member)) { - if (shouldTransformThisInStaticInitializers && member.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */) { + if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */) { facts |= 8 /* ClassFacts.NeedsSubstitutionForThisInClassStaticField */; if (!(facts & 1 /* ClassFacts.ClassWasDecorated */)) { facts |= 2 /* ClassFacts.NeedsClassConstructorReference */; } } - if (shouldTransformSuperInStaticInitializers && member.transformFlags & 33554432 /* TransformFlags.ContainsLexicalSuper */) { + if (shouldTransformSuperInStaticInitializers && member.transformFlags & 134217728 /* TransformFlags.ContainsLexicalSuper */) { if (!(facts & 1 /* ClassFacts.ClassWasDecorated */)) { facts |= 2 /* ClassFacts.NeedsClassConstructorReference */ | 4 /* ClassFacts.NeedsClassSuperReference */; } @@ -382250,8 +382844,7 @@ var ts; var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* SyntaxKind.NullKeyword */); var statements = [ - factory.updateClassDeclaration(node, - /*decorators*/ undefined, node.modifiers, node.name, + factory.updateClassDeclaration(node, node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) ]; if (pendingClassReferenceAssignment) { @@ -382303,7 +382896,7 @@ var ts; temp = createClassTempVar(); getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp); } - var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, + var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); var hasTransformableStatics = shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(staticPropertiesOrClassStaticBlocks, function (p) { return ts.isClassStaticBlockDeclaration(p) || !!p.initializer || ts.isPrivateIdentifier(p.name); }); if (hasTransformableStatics || ts.some(pendingExpressions)) { @@ -382371,9 +382964,7 @@ var ts; members.push(constructor); } if (!shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(pendingExpressions)) { - members.push(factory.createClassStaticBlockDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, factory.createBlock([ + members.push(factory.createClassStaticBlockDeclaration(factory.createBlock([ factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)) ]))); pendingExpressions = undefined; @@ -382410,7 +383001,6 @@ var ts; return undefined; } return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { @@ -382797,10 +383387,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_3 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_3, node); - ts.setCommentRange(clone_3, node); - return clone_3; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -383162,6 +383752,1001 @@ var ts; })(ts || (ts = {})); /*@internal*/ var ts; +(function (ts) { + function createRuntimeTypeSerializer(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var currentLexicalScope; + var currentNameScope; + return { + serializeTypeNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeNode, node); }, + serializeTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeOfNode, node); }, + serializeParameterTypesOfNode: function (serializerContext, node, container) { return setSerializerContextAnd(serializerContext, serializeParameterTypesOfNode, node, container); }, + serializeReturnTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeReturnTypeOfNode, node); }, + }; + function setSerializerContextAnd(serializerContext, cb, node, arg) { + var savedCurrentLexicalScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; + currentLexicalScope = serializerContext.currentLexicalScope; + currentNameScope = serializerContext.currentNameScope; + var result = arg === undefined ? cb(node) : cb(node, arg); + currentLexicalScope = savedCurrentLexicalScope; + currentNameScope = savedCurrentNameScope; + return result; + } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } + /** + * Serializes the type of a node for use with decorator type metadata. + * @param node The node that should have its type serialized. + */ + function serializeTypeOfNode(node) { + switch (node.kind) { + case 167 /* SyntaxKind.PropertyDeclaration */: + case 164 /* SyntaxKind.Parameter */: + return serializeTypeNode(node.type); + case 173 /* SyntaxKind.SetAccessor */: + case 172 /* SyntaxKind.GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); + case 257 /* SyntaxKind.ClassDeclaration */: + case 226 /* SyntaxKind.ClassExpression */: + case 169 /* SyntaxKind.MethodDeclaration */: + return ts.factory.createIdentifier("Function"); + default: + return ts.factory.createVoidZero(); + } + } + /** + * Serializes the type of a node for use with decorator type metadata. + * @param node The node that should have its type serialized. + */ + function serializeParameterTypesOfNode(node, container) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.factory.createArrayLiteralExpression(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 172 /* SyntaxKind.GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + /** + * Serializes the return type of a node for use with decorator type metadata. + * @param node The node that should have its return type serialized. + */ + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunction(node)) { + return ts.factory.createIdentifier("Promise"); + } + return ts.factory.createVoidZero(); + } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ + function serializeTypeNode(node) { + if (node === undefined) { + return ts.factory.createIdentifier("Object"); + } + node = ts.skipTypeParentheses(node); + switch (node.kind) { + case 114 /* SyntaxKind.VoidKeyword */: + case 153 /* SyntaxKind.UndefinedKeyword */: + case 143 /* SyntaxKind.NeverKeyword */: + return ts.factory.createVoidZero(); + case 179 /* SyntaxKind.FunctionType */: + case 180 /* SyntaxKind.ConstructorType */: + return ts.factory.createIdentifier("Function"); + case 183 /* SyntaxKind.ArrayType */: + case 184 /* SyntaxKind.TupleType */: + return ts.factory.createIdentifier("Array"); + case 177 /* SyntaxKind.TypePredicate */: + return node.assertsModifier ? + ts.factory.createVoidZero() : + ts.factory.createIdentifier("Boolean"); + case 133 /* SyntaxKind.BooleanKeyword */: + return ts.factory.createIdentifier("Boolean"); + case 198 /* SyntaxKind.TemplateLiteralType */: + case 150 /* SyntaxKind.StringKeyword */: + return ts.factory.createIdentifier("String"); + case 148 /* SyntaxKind.ObjectKeyword */: + return ts.factory.createIdentifier("Object"); + case 196 /* SyntaxKind.LiteralType */: + return serializeLiteralOfLiteralTypeNode(node.literal); + case 147 /* SyntaxKind.NumberKeyword */: + return ts.factory.createIdentifier("Number"); + case 158 /* SyntaxKind.BigIntKeyword */: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case 151 /* SyntaxKind.SymbolKeyword */: + return getGlobalConstructor("Symbol", 2 /* ScriptTarget.ES2015 */); + case 178 /* SyntaxKind.TypeReference */: + return serializeTypeReferenceNode(node); + case 188 /* SyntaxKind.IntersectionType */: + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ true); + case 187 /* SyntaxKind.UnionType */: + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ false); + case 189 /* SyntaxKind.ConditionalType */: + return serializeUnionOrIntersectionConstituents([node.trueType, node.falseType], /*isIntersection*/ false); + case 193 /* SyntaxKind.TypeOperator */: + if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { + return serializeTypeNode(node.type); + } + break; + case 181 /* SyntaxKind.TypeQuery */: + case 194 /* SyntaxKind.IndexedAccessType */: + case 195 /* SyntaxKind.MappedType */: + case 182 /* SyntaxKind.TypeLiteral */: + case 130 /* SyntaxKind.AnyKeyword */: + case 155 /* SyntaxKind.UnknownKeyword */: + case 192 /* SyntaxKind.ThisType */: + case 200 /* SyntaxKind.ImportType */: + break; + // handle JSDoc types from an invalid parse + case 312 /* SyntaxKind.JSDocAllType */: + case 313 /* SyntaxKind.JSDocUnknownType */: + case 317 /* SyntaxKind.JSDocFunctionType */: + case 318 /* SyntaxKind.JSDocVariadicType */: + case 319 /* SyntaxKind.JSDocNamepathType */: + break; + case 314 /* SyntaxKind.JSDocNullableType */: + case 315 /* SyntaxKind.JSDocNonNullableType */: + case 316 /* SyntaxKind.JSDocOptionalType */: + return serializeTypeNode(node.type); + default: + return ts.Debug.failBadSyntaxKind(node); + } + return ts.factory.createIdentifier("Object"); + } + function serializeLiteralOfLiteralTypeNode(node) { + switch (node.kind) { + case 10 /* SyntaxKind.StringLiteral */: + case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: + return ts.factory.createIdentifier("String"); + case 219 /* SyntaxKind.PrefixUnaryExpression */: { + var operand = node.operand; + switch (operand.kind) { + case 8 /* SyntaxKind.NumericLiteral */: + case 9 /* SyntaxKind.BigIntLiteral */: + return serializeLiteralOfLiteralTypeNode(operand); + default: + return ts.Debug.failBadSyntaxKind(operand); + } + } + case 8 /* SyntaxKind.NumericLiteral */: + return ts.factory.createIdentifier("Number"); + case 9 /* SyntaxKind.BigIntLiteral */: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case 110 /* SyntaxKind.TrueKeyword */: + case 95 /* SyntaxKind.FalseKeyword */: + return ts.factory.createIdentifier("Boolean"); + case 104 /* SyntaxKind.NullKeyword */: + return ts.factory.createVoidZero(); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function serializeUnionOrIntersectionConstituents(types, isIntersection) { + // Note when updating logic here also update `getEntityNameForDecoratorMetadata` in checker.ts so that aliases can be marked as referenced + var serializedType; + for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { + var typeNode = types_22[_i]; + typeNode = ts.skipTypeParentheses(typeNode); + if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { + if (isIntersection) + return ts.factory.createVoidZero(); // Reduce to `never` in an intersection + continue; // Elide `never` in a union + } + if (typeNode.kind === 155 /* SyntaxKind.UnknownKeyword */) { + if (!isIntersection) + return ts.factory.createIdentifier("Object"); // Reduce to `unknown` in a union + continue; // Elide `unknown` in an intersection + } + if (typeNode.kind === 130 /* SyntaxKind.AnyKeyword */) { + return ts.factory.createIdentifier("Object"); // Reduce to `any` in a union or intersection + } + if (!strictNullChecks && ((ts.isLiteralTypeNode(typeNode) && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */) || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var serializedConstituent = serializeTypeNode(typeNode); + if (ts.isIdentifier(serializedConstituent) && serializedConstituent.escapedText === "Object") { + // One of the individual is global object, return immediately + return serializedConstituent; + } + // If there exists union that is not `void 0` expression, check if the the common type is identifier. + // anything more complex and we will just default to Object + if (serializedType) { + // Different types + if (!equateSerializedTypeNodes(serializedType, serializedConstituent)) { + return ts.factory.createIdentifier("Object"); + } + } + else { + // Initialize the union type + serializedType = serializedConstituent; + } + } + // If we were able to find common type, use it + return serializedType !== null && serializedType !== void 0 ? serializedType : (ts.factory.createVoidZero()); // Fallback is only hit if all union constituents are null/undefined/never + } + function equateSerializedTypeNodes(left, right) { + return ( + // temp vars used in fallback + ts.isGeneratedIdentifier(left) ? ts.isGeneratedIdentifier(right) : + // entity names + ts.isIdentifier(left) ? ts.isIdentifier(right) + && left.escapedText === right.escapedText : + ts.isPropertyAccessExpression(left) ? ts.isPropertyAccessExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) + && equateSerializedTypeNodes(left.name, right.name) : + // `void 0` + ts.isVoidExpression(left) ? ts.isVoidExpression(right) + && ts.isNumericLiteral(left.expression) && left.expression.text === "0" + && ts.isNumericLiteral(right.expression) && right.expression.text === "0" : + // `"undefined"` or `"function"` in `typeof` checks + ts.isStringLiteral(left) ? ts.isStringLiteral(right) + && left.text === right.text : + // used in `typeof` checks for fallback + ts.isTypeOfExpression(left) ? ts.isTypeOfExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // parens in `typeof` checks with temps + ts.isParenthesizedExpression(left) ? ts.isParenthesizedExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // conditionals used in fallback + ts.isConditionalExpression(left) ? ts.isConditionalExpression(right) + && equateSerializedTypeNodes(left.condition, right.condition) + && equateSerializedTypeNodes(left.whenTrue, right.whenTrue) + && equateSerializedTypeNodes(left.whenFalse, right.whenFalse) : + // logical binary and assignments used in fallback + ts.isBinaryExpression(left) ? ts.isBinaryExpression(right) + && left.operatorToken.kind === right.operatorToken.kind + && equateSerializedTypeNodes(left.left, right.left) + && equateSerializedTypeNodes(left.right, right.right) : + false); + } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with decorator type metadata. + * @param node The type reference node. + */ + function serializeTypeReferenceNode(node) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope !== null && currentNameScope !== void 0 ? currentNameScope : currentLexicalScope); + switch (kind) { + case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.factory.createIdentifier("Object"); + } + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createAssignment(temp, serialized), "function"), + /*questionToken*/ undefined, temp, + /*colonToken*/ undefined, ts.factory.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.factory.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.factory.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.factory.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.factory.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.factory.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return getGlobalConstructor("Symbol", 2 /* ScriptTarget.ES2015 */); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.factory.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.factory.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + return ts.factory.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); + } + } + /** + * Produces an expression that results in `right` if `left` is not undefined at runtime: + * + * ``` + * typeof left !== "undefined" && right + * ``` + * + * We use `typeof L !== "undefined"` (rather than `L !== undefined`) since `L` may not be declared. + * It's acceptable for this expression to result in `false` at runtime, as the result is intended to be + * further checked by any containing expression. + */ + function createCheckedValue(left, right) { + return ts.factory.createLogicalAnd(ts.factory.createStrictInequality(ts.factory.createTypeOfExpression(left), ts.factory.createStringLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 79 /* SyntaxKind.Identifier */) { + // A -> typeof A !== "undefined" && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 79 /* SyntaxKind.Identifier */) { + // A.B -> typeof A !== "undefined" && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== "undefined" && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createLogicalAnd(ts.factory.createLogicalAnd(left.left, ts.factory.createStrictInequality(ts.factory.createAssignment(temp, left.right), ts.factory.createVoidZero())), ts.factory.createPropertyAccessExpression(temp, node.right)); + } + /** + * Serializes an entity name as an expression for decorator type metadata. + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 79 /* SyntaxKind.Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); + name.original = undefined; + ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. + return name; + case 161 /* SyntaxKind.QualifiedName */: + return serializeQualifiedNameAsExpression(node); + } + } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * @param node The qualified name to serialize. + */ + function serializeQualifiedNameAsExpression(node) { + return ts.factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); + } + function getGlobalConstructorWithFallback(name) { + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createIdentifier(name), "function"), + /*questionToken*/ undefined, ts.factory.createIdentifier(name), + /*colonToken*/ undefined, ts.factory.createIdentifier("Object")); + } + function getGlobalConstructor(name, minLanguageVersion) { + return languageVersion < minLanguageVersion ? + getGlobalConstructorWithFallback(name) : + ts.factory.createIdentifier(name); + } + } + ts.createRuntimeTypeSerializer = createRuntimeTypeSerializer; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformLegacyDecorators(context) { + var factory = context.factory, emitHelpers = context.getEmitHelperFactory, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + // Save the previous transformation hooks. + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onSubstituteNode = onSubstituteNode; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ + var classAliases; + return ts.chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function modifierVisitor(node) { + return ts.isDecorator(node) ? undefined : node; + } + function visitor(node) { + if (!(node.transformFlags & 33554432 /* TransformFlags.ContainsDecorators */)) { + return node; + } + switch (node.kind) { + case 165 /* SyntaxKind.Decorator */: + // Decorators are elided. They will be emitted as part of `visitClassDeclaration`. + return undefined; + case 257 /* SyntaxKind.ClassDeclaration */: + return visitClassDeclaration(node); + case 226 /* SyntaxKind.ClassExpression */: + return visitClassExpression(node); + case 171 /* SyntaxKind.Constructor */: + return visitConstructorDeclaration(node); + case 169 /* SyntaxKind.MethodDeclaration */: + return visitMethodDeclaration(node); + case 173 /* SyntaxKind.SetAccessor */: + return visitSetAccessorDeclaration(node); + case 172 /* SyntaxKind.GetAccessor */: + return visitGetAccessorDeclaration(node); + case 167 /* SyntaxKind.PropertyDeclaration */: + return visitPropertyDeclaration(node); + case 164 /* SyntaxKind.Parameter */: + return visitParameterDeclaration(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitClassDeclaration(node) { + if (!(ts.classOrConstructorParameterIsDecorated(node) || ts.childIsDecorated(node))) + return ts.visitEachChild(node, visitor, context); + var statements = ts.hasDecorators(node) ? + transformClassDeclarationWithClassDecorators(node, node.name) : + transformClassDeclarationWithoutClassDecorators(node, node.name); + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(factory.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statements[0], ts.getEmitFlags(statements[0]) | 4194304 /* EmitFlags.HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + function decoratorContainsPrivateIdentifierInExpression(decorator) { + return !!(decorator.transformFlags & 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); + } + function parameterDecoratorsContainPrivateIdentifierInExpression(parameterDecorators) { + return ts.some(parameterDecorators, decoratorContainsPrivateIdentifierInExpression); + } + function hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.canHaveDecorators(member)) + continue; + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.decorators, decoratorContainsPrivateIdentifierInExpression)) + return true; + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.parameters, parameterDecoratorsContainPrivateIdentifierInExpression)) + return true; + } + return false; + } + function transformDecoratorsOfClassElements(node, members) { + var decorationStatements = []; + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ false); + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ true); + if (hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node)) { + members = ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray([], members, true), [ + factory.createClassStaticBlockDeclaration(factory.createBlock(decorationStatements, /*multiLine*/ true)) + ], false)), members); + decorationStatements = undefined; + } + return { decorationStatements: decorationStatements, members: members }; + } + /** + * Transforms a non-decorated class declaration. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + */ + function transformClassDeclarationWithoutClassDecorators(node, name) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var _a; + var modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var updated = factory.updateClassDeclaration(node, modifiers, name, + /*typeParameters*/ undefined, heritageClauses, members); + return ts.addRange([updated], decorationStatements); + } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + */ + function transformClassDeclarationWithClassDecorators(node, name) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export { C }; + // | var C_1; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export default C; + // | var C_1; + // --------------------------------------------------------------------- + // + var _a; + var location = ts.moveRangePastModifiers(node); + var classAlias = getClassAliasIfNeeded(node); + // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name + // without any block-scoped variable collision handling + var declName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? + factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : + factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var classExpression = factory.createClassExpression( + /*modifiers*/ undefined, name, + /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, location); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var statement = factory.createVariableStatement( + /*modifiers*/ undefined, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(declName, + /*exclamationToken*/ undefined, + /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) + ], 1 /* NodeFlags.Let */)); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, location); + ts.setCommentRange(statement, node); + var statements = [statement]; + ts.addRange(statements, decorationStatements); + addConstructorDecorationStatement(statements, node); + return statements; + } + function visitClassExpression(node) { + // Legacy decorators were not supported on class expressions + return factory.updateClassExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)); + } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)); + } + function finishClassElement(updated, original) { + if (updated !== original) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, original); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(original)); + } + return updated; + } + function visitMethodDeclaration(node) { + return finishClassElement(factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitGetAccessorDeclaration(node) { + return finishClassElement(factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitSetAccessorDeclaration(node) { + return finishClassElement(factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitPropertyDeclaration(node) { + if (node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 2 /* ModifierFlags.Ambient */)) { + return undefined; + } + return finishClassElement(factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + function visitParameterDeclaration(node) { + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32 /* EmitFlags.NoTrailingSourceMap */); + } + return updated; + } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param allDecorators An object containing all of the decorators for the declaration. + */ + function transformAllDecoratorsOfDeclaration(allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + return decoratorExpressions; + } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), function (expr) { return factory.createExpressionStatement(expr); })); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStaticElement, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStaticElement === ts.isStatic(member); + } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, function (m) { return isDecoratedClassElement(m, isStatic, node); }); + } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { + var member = members_8[_i]; + expressions = ts.append(expressions, generateClassElementDecorationExpression(node, member)); + } + return expressions; + } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function generateClassElementDecorationExpression(node, member) { + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", null); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", null); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* ModifierFlags.Ambient */)); + var descriptor = languageVersion > 0 /* ScriptTarget.ES3 */ + ? member.kind === 167 /* SyntaxKind.PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. + ? factory.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. + : factory.createNull() + : undefined; + var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); + ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(helper, ts.moveRangePastModifiers(member)); + return helper; + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); + } + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function generateConstructorDecorationExpression(node) { + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name + // without any block-scoped variable collision handling + var localName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? + factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : + factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); + var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(node)); + return expression; + } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); + ts.setTextRange(helper, decorator.expression); + ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); + expressions.push(helper); + } + } + return expressions; + } + /** + * Gets an expression that represents a property name (for decorated properties or enums). + * For a computed property, a name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isPrivateIdentifier(name)) { + return factory.createIdentifier(""); + } + else if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression) + ? factory.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return factory.createStringLiteral(ts.idText(name)); + } + else { + return factory.cloneNode(name); + } + } + function enableSubstitutionForClassAliases() { + if (!classAliases) { + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(79 /* SyntaxKind.Identifier */); + // Keep track of class aliases. + classAliases = []; + } + } + /** + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. + */ + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* NodeCheckFlags.ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; + } + } + function getClassPrototype(node) { + return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.isStatic(member) + ? factory.getDeclarationName(node) + : getClassPrototype(node); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* EmitHint.Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 79 /* SyntaxKind.Identifier */: + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + var _a; + return (_a = trySubstituteClassAlias(node)) !== null && _a !== void 0 ? _a : node; + } + function trySubstituteClassAlias(node) { + if (classAliases) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* NodeCheckFlags.ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 + if (classAlias) { + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; + } + } + } + } + return undefined; + } + } + ts.transformLegacyDecorators = transformLegacyDecorators; +})(ts || (ts = {})); +/*@internal*/ +var ts; (function (ts) { var ES2017SubstitutionFlags; (function (ES2017SubstitutionFlags) { @@ -383380,8 +384965,7 @@ var ts; * @param node The node to visit. */ function visitMethodDeclaration(node) { - return factory.updateMethodDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ @@ -383397,8 +384981,7 @@ var ts; * @param node The node to visit. */ function visitFunctionDeclaration(node) { - return factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -383413,7 +384996,7 @@ var ts; * @param node The node to visit. */ function visitFunctionExpression(node) { - return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -383428,7 +385011,7 @@ var ts; * @param node The node to visit. */ function visitArrowFunction(node) { - return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -383730,7 +385313,6 @@ var ts; /* typeParameters */ undefined, /* parameters */ [ factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "v", /* questionToken */ undefined, @@ -384010,7 +385592,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign(__assign({a}, o), {b}); @@ -384083,7 +385665,7 @@ var ts; * expression of an `ExpressionStatement`). */ function visitBinaryExpression(node, expressionResultIsUnused) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* FlattenLevel.ObjectRest */, !expressionResultIsUnused); } if (node.operatorToken.kind === 27 /* SyntaxKind.CommaToken */) { @@ -384114,7 +385696,7 @@ var ts; function visitCatchClause(node) { if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + node.variableDeclaration.name.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { var name = factory.getGeneratedNameForNode(node.variableDeclaration.name); var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name); var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* FlattenLevel.ObjectRest */); @@ -384155,7 +385737,7 @@ var ts; } function visitVariableDeclarationWorker(node, exportedVariableStatement) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* FlattenLevel.ObjectRest */, /*rval*/ undefined, exportedVariableStatement); } @@ -384174,7 +385756,7 @@ var ts; */ function visitForOfStatement(node, outermostLabeledStatement) { var ancestorFacts = enterSubtree(0 /* HierarchyFacts.IterationStatementExcludes */, 2 /* HierarchyFacts.IterationStatementIncludes */); - if (node.initializer.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } var result = node.awaitModifier ? @@ -384281,17 +385863,15 @@ var ts; function visitParameter(node) { if (parametersWithPrecedingObjectRestOrSpread === null || parametersWithPrecedingObjectRestOrSpread === void 0 ? void 0 : parametersWithPrecedingObjectRestOrSpread.has(node)) { return factory.updateParameterDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); } - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return factory.updateParameterDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); @@ -384305,7 +385885,7 @@ var ts; if (parameters) { parameters.add(parameter); } - else if (parameter.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + else if (parameter.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { parameters = new ts.Set(); } } @@ -384316,8 +385896,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateConstructorDeclaration(node, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -384327,8 +385906,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), + var updated = factory.updateGetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; @@ -384339,8 +385917,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateSetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -384350,9 +385927,8 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateMethodDeclaration(node, - /*decorators*/ undefined, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ - ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + var updated = factory.updateMethodDeclaration(node, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifierLike) : node.modifiers, enclosingFunctionFlags & 2 /* FunctionFlags.Async */ ? undefined : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), @@ -384369,8 +385945,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ + var updated = factory.updateFunctionDeclaration(node, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* FunctionFlags.Async */ ? undefined @@ -384528,7 +386103,7 @@ var ts; statements = ts.append(statements, statement); } } - else if (parameter.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + else if (parameter.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { containsPrecedingObjectRestOrSpread = true; var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* FlattenLevel.ObjectRest */, factory.getGeneratedNameForNode(parameter), /*doNotRecordTempVariablesInLine*/ false, @@ -385025,7 +386600,7 @@ var ts; var _b = _a[_i], importSource = _b[0], importSpecifiersMap = _b[1]; if (ts.isExternalModule(node)) { // Add `import` statement - var importStatement = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined); + var importStatement = factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined); ts.setParentRecursive(importStatement, /*incremental*/ false); statements = ts.insertStatementAfterCustomPrologue(statements.slice(), importStatement); } @@ -385256,22 +386831,29 @@ var ts; if (node === undefined) { return factory.createTrue(); } - else if (node.kind === 10 /* SyntaxKind.StringLiteral */) { + if (node.kind === 10 /* SyntaxKind.StringLiteral */) { // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which // Need to be escaped to be handled correctly in a normal string var singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - else if (node.kind === 288 /* SyntaxKind.JsxExpression */) { + if (node.kind === 288 /* SyntaxKind.JsxExpression */) { if (node.expression === undefined) { return factory.createTrue(); } return ts.visitNode(node.expression, visitor, ts.isExpression); } - else { - return ts.Debug.failBadSyntaxKind(node); + if (ts.isJsxElement(node)) { + return visitJsxElement(node, /*isChild*/ false); + } + if (ts.isJsxSelfClosingElement(node)) { + return visitJsxSelfClosingElement(node, /*isChild*/ false); } + if (ts.isJsxFragment(node)) { + return visitJsxFragment(node, /*isChild*/ false); + } + return ts.Debug.failBadSyntaxKind(node); } function visitJsxText(node) { var fixed = fixupWhitespaceAndDecodeEntities(node.text); @@ -385893,7 +387475,7 @@ var ts; && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */ + return node.transformFlags & 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */ && (ts.isReturnStatement(node) || ts.isIfStatement(node) || ts.isWithStatement(node) @@ -386266,7 +387848,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */))] : [], + /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */))] : [], /*type*/ undefined, transformClassBody(node, extendsClauseElement)); // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier @@ -386344,7 +387926,6 @@ var ts; var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); var constructorFunction = factory.createFunctionDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), @@ -386457,7 +388038,7 @@ var ts; factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); if (isDerivedClass || superCallExpression) { - if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */)) { + if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */)) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -386609,7 +388190,6 @@ var ts; // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, @@ -386621,7 +388201,6 @@ var ts; else if (node.initializer) { // Initializers are elided return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, node.name, /*questionToken*/ undefined, @@ -387002,7 +388581,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* HierarchyFacts.StaticInitializer */)) { + if (node.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* HierarchyFacts.StaticInitializer */)) { hierarchyFacts |= 65536 /* HierarchyFacts.CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; @@ -387061,8 +388640,7 @@ var ts; : node.name; exitSubtree(ancestorFacts, 98304 /* HierarchyFacts.FunctionSubtreeExcludes */, 0 /* HierarchyFacts.None */); convertedLoopState = savedConvertedLoopState; - return factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, + return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); } @@ -387288,7 +388866,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.flags & 3 /* NodeFlags.BlockScoped */ || node.transformFlags & 262144 /* TransformFlags.ContainsBindingPattern */) { + if (node.flags & 3 /* NodeFlags.BlockScoped */ || node.transformFlags & 524288 /* TransformFlags.ContainsBindingPattern */) { if (node.flags & 3 /* NodeFlags.BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -387301,7 +388879,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 262144 /* TransformFlags.ContainsBindingPattern */ + if (node.transformFlags & 524288 /* TransformFlags.ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -387625,7 +389203,7 @@ var ts; var numInitialProperties = -1, hasComputed = false; for (var i = 0; i < properties.length; i++) { var property = properties[i]; - if ((property.transformFlags & 524288 /* TransformFlags.ContainsYield */ && + if ((property.transformFlags & 1048576 /* TransformFlags.ContainsYield */ && hierarchyFacts & 4 /* HierarchyFacts.AsyncFunctionBody */) || (hasComputed = ts.Debug.checkDefined(property.name).kind === 162 /* SyntaxKind.ComputedPropertyName */)) { numInitialProperties = i; @@ -387898,7 +389476,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = factory.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; var emitFlags = 0 /* EmitFlags.None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* EmitFlags.CapturesThis */; @@ -388013,7 +389591,7 @@ var ts; var loopBody = factory.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; var emitFlags = 524288 /* EmitFlags.ReuseTempVariableScope */; if (currentState.containsLexicalThis) emitFlags |= 8 /* EmitFlags.CapturesThis */; @@ -388156,7 +389734,7 @@ var ts; } } else { - loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + loopParameters.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); var checkFlags = resolver.getNodeCheckFlags(decl); if (checkFlags & 4194304 /* NodeCheckFlags.NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { var outParamName = factory.createUniqueName("out_" + ts.idText(name)); @@ -388313,10 +389891,10 @@ var ts; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); if (node.kind === 172 /* SyntaxKind.GetAccessor */) { - updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + updated = factory.updateGetAccessorDeclaration(node, node.modifiers, node.name, parameters, node.type, body); } else { - updated = factory.updateSetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, body); + updated = factory.updateSetAccessorDeclaration(node, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 98304 /* HierarchyFacts.FunctionSubtreeExcludes */, 0 /* HierarchyFacts.None */); convertedLoopState = savedConvertedLoopState; @@ -388495,7 +390073,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */ || + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */ || node.expression.kind === 106 /* SyntaxKind.SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -388503,7 +390081,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* EmitFlags.NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */) { + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -389345,10 +390923,10 @@ var ts; case 247 /* SyntaxKind.ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) { + if (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (2048 /* TransformFlags.ContainsGenerator */ | 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (2048 /* TransformFlags.ContainsGenerator */ | 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -389412,8 +390990,7 @@ var ts; function visitFunctionDeclaration(node) { // Currently, we only support generators that were originally async functions. if (node.asteriskToken) { - node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration( - /*decorators*/ undefined, node.modifiers, + node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(node.modifiers, /*asteriskToken*/ undefined, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, transformGeneratorFunctionBody(node.body)), @@ -389553,7 +391130,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) { + if (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -390611,7 +392188,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + return !!node && (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -391242,7 +392819,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], /*type*/ undefined, factory.createBlock(buildResult, /*multiLine*/ buildResult.length > 0)), 524288 /* EmitFlags.ReuseTempVariableScope */)); } @@ -391660,7 +393237,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 4194304 /* TransformFlags.ContainsDynamicImport */ || + node.transformFlags & 8388608 /* TransformFlags.ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) { return node; } @@ -391761,8 +393338,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, __spreadArray([ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") ], importAliasNames, true), /*type*/ undefined, transformAsynchronousModuleBody(node)) ], false))) @@ -391783,7 +393360,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], /*type*/ undefined, ts.setTextRange(factory.createBlock([ factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("module"), "object"), factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object")), factory.createBlock([ factory.createVariableStatement( @@ -391832,8 +393409,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, __spreadArray([ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") ], importAliasNames, true), /*type*/ undefined, transformAsynchronousModuleBody(node)) ])) @@ -391862,7 +393439,7 @@ var ts; var amdDependency = _a[_i]; if (amdDependency.name) { aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); - importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); } else { unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); @@ -391883,7 +393460,7 @@ var ts; // This is so that when printer will not substitute the identifier ts.setEmitFlags(importAliasName, 4 /* EmitFlags.NoSubstitution */); aliasedModuleNames.push(externalModuleName); - importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); } else { unaliasedModuleNames.push(externalModuleName); @@ -391997,7 +393574,7 @@ var ts; function visitorWorker(node, valueIsDiscarded) { // This visitor does not need to descend into the tree if there is no dynamic import, destructuring assignment, or update expression // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & (4194304 /* TransformFlags.ContainsDynamicImport */ | 4096 /* TransformFlags.ContainsDestructuringAssignment */ | 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (8388608 /* TransformFlags.ContainsDynamicImport */ | 4096 /* TransformFlags.ContainsDestructuringAssignment */ | 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -392148,7 +393725,7 @@ var ts; var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), visitor); // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output. var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - var containsLexicalThis = !!(node.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -392203,8 +393780,8 @@ var ts; var resolve = factory.createUniqueName("resolve"); var reject = factory.createUniqueName("reject"); var parameters = [ - factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), - factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) ]; var body = factory.createBlock([ factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("require"), @@ -392492,8 +394069,7 @@ var ts; function visitFunctionDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor), /*type*/ undefined, ts.visitEachChild(node.body, visitor, context)), /*location*/ node), @@ -392520,8 +394096,7 @@ var ts; function visitClassDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor), ts.visitNodes(node.members, visitor)), node), node)); } else { @@ -393135,7 +394710,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304 /* TransformFlags.ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 8388608 /* TransformFlags.ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -393168,8 +394743,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, [ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) ], /*type*/ undefined, moduleBodyBlock); // Write the call to `System.register` @@ -393304,7 +394879,7 @@ var ts; // - Temporary variables will appear at the top rather than at the bottom of the file ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 - var modifiers = node.transformFlags & 1048576 /* TransformFlags.ContainsAwait */ ? + var modifiers = node.transformFlags & 2097152 /* TransformFlags.ContainsAwait */ ? factory.createModifiersFromModifierFlags(256 /* ModifierFlags.Async */) : undefined; var moduleObject = factory.createObjectLiteralExpression([ @@ -393391,10 +394966,9 @@ var ts; /*typeArguments*/ undefined, [n]))); } return factory.createFunctionDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, exportStarFunction, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], /*type*/ undefined, factory.createBlock([ factory.createVariableStatement( /*modifiers*/ undefined, factory.createVariableDeclarationList([ @@ -393485,7 +395059,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, factory.createBlock(statements, /*multiLine*/ true))); } return factory.createArrayLiteralExpression(setters, /*multiLine*/ true); @@ -393583,7 +395157,7 @@ var ts; */ function visitFunctionDeclaration(node) { if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock))); } @@ -393611,8 +395185,7 @@ var ts; var name = factory.getLocalName(node); hoistVariableDeclaration(name); // Rewrite the class declaration into an assignment of a class expression. - statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.decorators, visitor, ts.isDecorator), - /*modifiers*/ undefined, node.name, + statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -394213,7 +395786,7 @@ var ts; * @param node The node to visit. */ function visitorWorker(node, valueIsDiscarded) { - if (!(node.transformFlags & (4096 /* TransformFlags.ContainsDestructuringAssignment */ | 4194304 /* TransformFlags.ContainsDynamicImport */ | 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (4096 /* TransformFlags.ContainsDestructuringAssignment */ | 8388608 /* TransformFlags.ContainsDynamicImport */ | 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -394660,7 +396233,7 @@ var ts; // Though an error in es2020 modules, in node-flavor es2020 modules, we can helpfully transform this to a synthetic `require` call // To give easy access to a synchronous `require` in node-flavor esm. We do the transform even in scenarios where we error, but `import.meta.url` // is available, just because the output is reasonable for a node-like runtime. - return ts.getEmitScriptTarget(compilerOptions) >= ts.ModuleKind.ES2020 ? visitImportEqualsDeclaration(node) : undefined; + return ts.getEmitModuleKind(compilerOptions) >= ts.ModuleKind.Node16 ? visitImportEqualsDeclaration(node) : undefined; case 271 /* SyntaxKind.ExportAssignment */: return visitExportAssignment(node); case 272 /* SyntaxKind.ExportDeclaration */: @@ -394683,7 +396256,6 @@ var ts; if (!importRequireStatements) { var createRequireName = factory.createUniqueName("_createRequire", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */); var importStatement = factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause( /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamedImports([ @@ -394726,7 +396298,6 @@ var ts; function appendExportsOfImportEqualsDeclaration(statements, node) { if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { statements = ts.append(statements, factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, node.isTypeOnly, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, ts.idText(node.name))]))); } return statements; @@ -394747,13 +396318,11 @@ var ts; var oldIdentifier = node.exportClause.name; var synthName = factory.getGeneratedNameForNode(oldIdentifier); var importDecl = factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause( /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamespaceImport(synthName)), node.moduleSpecifier, node.assertClause); ts.setOriginalNode(importDecl, node.exportClause); var exportDecl = ts.isExportNamespaceAsDefaultDeclaration(node) ? factory.createExportDefault(synthName) : factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, synthName, oldIdentifier)])); ts.setOriginalNode(exportDecl, node); @@ -395005,7 +396574,7 @@ var ts; return getTypeAliasDeclarationVisibilityError; } else { - return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.SyntaxKind[node.kind])); + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(node.kind))); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 254 /* SyntaxKind.VariableDeclaration */ || node.kind === 203 /* SyntaxKind.BindingElement */) { @@ -395216,7 +396785,7 @@ var ts; ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1; default: - return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.SyntaxKind[node.parent.kind])); + return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind))); } } function getTypeParameterConstraintVisibilityError() { @@ -395553,7 +397122,7 @@ var ts; resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; var statements = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([], [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -395696,7 +397265,7 @@ var ts; }); return ret; } - function filterBindingPatternInitializers(name) { + function filterBindingPatternInitializersAndRenamings(name) { if (name.kind === 79 /* SyntaxKind.Identifier */) { return name; } @@ -395712,7 +397281,12 @@ var ts; if (elem.kind === 227 /* SyntaxKind.OmittedExpression */) { return elem; } - return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + if (elem.propertyName && ts.isIdentifier(elem.propertyName) && ts.isIdentifier(elem.name) && !elem.symbol.isReferenced) { + // Unnecessary property renaming is forbidden in types, so remove renaming + return factory.updateBindingElement(elem, elem.dotDotDotToken, + /* propertyName */ undefined, elem.propertyName, shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializersAndRenamings(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); } } function ensureParameter(p, modifierMask, type) { @@ -395721,8 +397295,7 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); } - var newParam = factory.updateParameterDeclaration(p, - /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57 /* SyntaxKind.QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + var newParam = factory.updateParameterDeclaration(p, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializersAndRenamings(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57 /* SyntaxKind.QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; @@ -395773,7 +397346,7 @@ var ts; if (node.kind === 164 /* SyntaxKind.Parameter */ || node.kind === 167 /* SyntaxKind.PropertyDeclaration */ || node.kind === 166 /* SyntaxKind.PropertySignature */) { - if (!node.initializer) + if (ts.isPropertySignature(node) || !node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } @@ -395859,7 +397432,6 @@ var ts; } if (!newValueParameter) { newValueParameter = factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "value"); } @@ -395917,8 +397489,7 @@ var ts; if (decl.moduleReference.kind === 277 /* SyntaxKind.ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); - return factory.updateImportEqualsDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + return factory.updateImportEqualsDeclaration(decl, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); } else { var oldDiag = getSymbolAccessibilityDiagnostic; @@ -395931,31 +397502,28 @@ var ts; function transformImportDeclaration(decl) { if (!decl.importClause) { // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // The `importClause` visibility corresponds to the default's visibility. var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; if (!decl.importClause.namedBindings) { // No named bindings (either namespace or list), meaning the import is just default or should be elided - return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, + return visibleDefaultBinding && factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } if (decl.importClause.namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; - return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; + return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; } // Named imports (optionally with visible default) var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); if ((bindingList && bindingList.length) || visibleDefaultBinding) { - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // Augmentation of export depends on import if (resolver.isImportRequiredByAugmentation(decl)) { - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, + return factory.updateImportDeclaration(decl, decl.modifiers, /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // Nothing visible @@ -395988,7 +397556,7 @@ var ts; while (ts.length(lateMarkedStatements)) { var i = lateMarkedStatements.shift(); if (!ts.isLateVisibilityPaintedStatement(i)) { - return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.Debug.formatSyntaxKind(i.kind))); } var priorNeedsDeclare = needsDeclare; needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); @@ -396052,7 +397620,7 @@ var ts; if (ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)) { if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; // Elide all but the first overload - return cleanup(factory.createPropertyDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + return cleanup(factory.createPropertyDeclaration(ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); } } if (canProduceDiagnostic && !suppressNewDiagnosticContexts) { @@ -396084,7 +397652,6 @@ var ts; case 171 /* SyntaxKind.Constructor */: { // A constructor declaration may not have a type annotation var ctor = factory.createConstructorDeclaration( - /*decorators*/ undefined, /*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* ModifierFlags.None */), /*body*/ undefined); return cleanup(ctor); @@ -396093,8 +397660,7 @@ var ts; if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - var sig = factory.createMethodDeclaration( - /*decorators*/ undefined, ensureModifiers(input), + var sig = factory.createMethodDeclaration(ensureModifiers(input), /*asteriskToken*/ undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined); return cleanup(sig); @@ -396104,24 +397670,21 @@ var ts; return cleanup(/*returnValue*/ undefined); } var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input)); - return cleanup(factory.updateGetAccessorDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), ensureType(input, accessorType), + return cleanup(factory.updateGetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), ensureType(input, accessorType), /*body*/ undefined)); } case 173 /* SyntaxKind.SetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - return cleanup(factory.updateSetAccessorDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), + return cleanup(factory.updateSetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), /*body*/ undefined)); } case 167 /* SyntaxKind.PropertyDeclaration */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - return cleanup(factory.updatePropertyDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); + return cleanup(factory.updatePropertyDeclaration(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); case 166 /* SyntaxKind.PropertySignature */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); @@ -396137,8 +397700,7 @@ var ts; return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } case 176 /* SyntaxKind.IndexSignature */: { - return cleanup(factory.updateIndexSignature(input, - /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */))); + return cleanup(factory.updateIndexSignature(input, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */))); } case 254 /* SyntaxKind.VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { @@ -396177,7 +397739,7 @@ var ts; return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.assertions, input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); } - default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.SyntaxKind[input.kind])); + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(input.kind))); } } if (ts.isTupleTypeNode(input) && (ts.getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === ts.getLineAndCharacterOfPosition(currentSourceFile, input.end).line)) { @@ -396221,8 +397783,7 @@ var ts; resultHasScopeMarker = true; // Always visible if the parent node isn't dropped for being not visible // Rewrite external module names if necessary - return factory.updateExportDeclaration(input, - /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); + return factory.updateExportDeclaration(input, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); } case 271 /* SyntaxKind.ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible @@ -396245,7 +397806,7 @@ var ts; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* NodeFlags.Const */)); preserveJsDoc(statement, input); ts.removeAllComments(input); - return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + return [statement, factory.updateExportAssignment(input, input.modifiers, newId)]; } } } @@ -396260,7 +397821,7 @@ var ts; // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (125951 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (257023 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { @@ -396296,22 +397857,19 @@ var ts; var previousNeedsDeclare = needsDeclare; switch (input.kind) { case 259 /* SyntaxKind.TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all - return cleanup(factory.updateTypeAliasDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + return cleanup(factory.updateTypeAliasDeclaration(input, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); case 258 /* SyntaxKind.InterfaceDeclaration */: { - return cleanup(factory.updateInterfaceDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + return cleanup(factory.updateInterfaceDeclaration(input, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 256 /* SyntaxKind.FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - var clean = cleanup(factory.updateFunctionDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), + var clean = cleanup(factory.updateFunctionDeclaration(input, ensureModifiers(input), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); if (clean && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) { var props = resolver.getPropertiesOfContainerFunction(input); // Use parseNodeFactory so it is usable as an enclosing declaration - var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); + var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); ts.setParent(fakespace_1, enclosingDeclaration); fakespace_1.locals = ts.createSymbolTable(props); fakespace_1.symbol = props[0].parent; @@ -396337,26 +397895,22 @@ var ts; } else { declarations.push(factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports(ts.map(exportMappings_1, function (_a) { var gen = _a[0], exp = _a[1]; return factory.createExportSpecifier(/*isTypeOnly*/ false, gen, exp); })))); } - var namespaceDecl = factory.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* NodeFlags.Namespace */); + var namespaceDecl = factory.createModuleDeclaration(ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* NodeFlags.Namespace */); if (!ts.hasEffectiveModifier(clean, 512 /* ModifierFlags.Default */)) { return [clean, namespaceDecl]; } var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~513 /* ModifierFlags.ExportDefault */) | 2 /* ModifierFlags.Ambient */); - var cleanDeclaration = factory.updateFunctionDeclaration(clean, - /*decorators*/ undefined, modifiers, + var cleanDeclaration = factory.updateFunctionDeclaration(clean, modifiers, /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, /*body*/ undefined); - var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, - /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body); + var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, modifiers, namespaceDecl.name, namespaceDecl.body); var exportDefaultDeclaration = factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, namespaceDecl.name); if (ts.isSourceFile(input.parent)) { @@ -396399,8 +397953,7 @@ var ts; needsScopeFixMarker = oldNeedsScopeFix; resultHasScopeMarker = oldHasScopeFix; var mods = ensureModifiers(input); - return cleanup(factory.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); } else { needsDeclare = previousNeedsDeclare; @@ -396411,8 +397964,7 @@ var ts; var id = ts.getOriginalNodeId(inner); // TODO: GH#18217 var body = lateStatementReplacementMap.get(id); lateStatementReplacementMap.delete(id); - return cleanup(factory.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, input.name, body)); } } case 257 /* SyntaxKind.ClassDeclaration */: { @@ -396429,8 +397981,7 @@ var ts; return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 79 /* SyntaxKind.Identifier */) { - return preserveJsDoc(factory.createPropertyDeclaration( - /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + return preserveJsDoc(factory.createPropertyDeclaration(ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); } else { // Pattern - this is currently an error, but we emit declarations for it somewhat correctly @@ -396446,8 +397997,7 @@ var ts; elems = ts.concatenate(elems, walkBindingPattern(elem.name)); } elems = elems || []; - elems.push(factory.createPropertyDeclaration( - /*decorators*/ undefined, ensureModifiers(param), elem.name, + elems.push(factory.createPropertyDeclaration(ensureModifiers(param), elem.name, /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), /*initializer*/ undefined)); } @@ -396461,7 +398011,6 @@ var ts; // Prevents other classes with the same public members from being used in place of the current class var privateIdentifier = hasPrivateIdentifier ? [ factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createPrivateIdentifier("#private"), /*questionToken*/ undefined, /*type*/ undefined, @@ -396491,20 +398040,18 @@ var ts; } return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 104 /* SyntaxKind.NullKeyword */; })), visitDeclarationSubtree)); })); - return [statement, cleanup(factory.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 + return [statement, cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 } else { var heritageClauses = transformHeritageClauses(input.heritageClauses); - return cleanup(factory.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + return cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members)); } } case 237 /* SyntaxKind.VariableStatement */: { return cleanup(transformVariableStatement(input)); } case 260 /* SyntaxKind.EnumDeclaration */: { - return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { + return cleanup(factory.updateEnumDeclaration(input, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; // Rewrite enum values to their constants, if available @@ -396514,7 +398061,7 @@ var ts; } } // Anything left unhandled is an error, so this should be unreachable - return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.SyntaxKind[input.kind])); + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.Debug.formatSyntaxKind(input.kind))); function cleanup(node) { if (isEnclosingDeclaration(input)) { enclosingDeclaration = previousEnclosingDeclaration; @@ -396588,12 +398135,12 @@ var ts; var currentFlags = ts.getEffectiveModifierFlags(node); var newFlags = ensureModifierFlags(node); if (currentFlags === newFlags) { - return node.modifiers; + return ts.visitArray(node.modifiers, function (n) { return ts.tryCast(n, ts.isModifier); }, ts.isModifier); } return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 125951 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 256 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files + var mask = 257023 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 256 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* ModifierFlags.Ambient */ : 0 /* ModifierFlags.None */; var parentIsFile = node.parent.kind === 305 /* SyntaxKind.SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { @@ -396634,7 +398181,7 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 125951 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } + if (modifierMask === void 0) { modifierMask = 257023 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* ModifierFlags.None */; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; if (flags & 512 /* ModifierFlags.Default */ && !(flags & 1 /* ModifierFlags.Export */)) { @@ -396756,6 +398303,7 @@ var ts; var transformers = []; ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory)); transformers.push(ts.transformTypeScript); + transformers.push(ts.transformLegacyDecorators); transformers.push(ts.transformClassFields); if (ts.getJSXTransformEnabled(compilerOptions)) { transformers.push(ts.transformJsx); @@ -397516,7 +399064,6 @@ var ts; var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit; var bundleBuildInfo; var emitSkipped = false; - var exportedModulesFromDeclarationEmit; // Emit each output file enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); @@ -397526,7 +399073,6 @@ var ts; diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList, - exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath; @@ -397580,14 +399126,16 @@ var ts; return; } var version = ts.version; // Extracted into a const so the form is stable between namespace and module - ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false); + var buildInfo = { bundle: bundle, program: program, version: version }; + // Pass buildinfo as additional data to avoid having to reparse + ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText(buildInfo), /*writeByteOrderMark*/ false, /*sourceFiles*/ undefined, { buildInfo: buildInfo }); } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) { if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) { return; } // Make sure not to write js file and source map file if any of them cannot be written - if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit) { emitSkipped = true; return; } @@ -397616,7 +399164,7 @@ var ts; substituteNode: transform.substituteNode, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, compilerOptions); // Clean up emit nodes on parse tree transform.dispose(); if (bundleBuildInfo) @@ -397652,7 +399200,7 @@ var ts; noEmitHelpers: true, module: compilerOptions.module, target: compilerOptions.target, - sourceMap: compilerOptions.sourceMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, inlineSourceMap: compilerOptions.inlineSourceMap, extendedDiagnostics: compilerOptions.extendedDiagnostics, onlyPrintJsDocStyle: true, @@ -397672,17 +399220,13 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || forceDtsEmit) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { - sourceMap: !forceDtsEmit && compilerOptions.declarationMap, + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform, declarationPrinter, { + sourceMap: printerOptions.sourceMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, // Explicitly do not passthru either `inline` option }); - if (forceDtsEmit && declarationTransform.transformed[0].kind === 305 /* SyntaxKind.SourceFile */) { - var sourceFile = declarationTransform.transformed[0]; - exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; - } } declarationTransform.dispose(); if (bundleBuildInfo) @@ -397701,7 +399245,8 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, mapOptions) { + var sourceFileOrBundle = transform.transformed[0]; var bundle = sourceFileOrBundle.kind === 306 /* SyntaxKind.Bundle */ ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 305 /* SyntaxKind.SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; @@ -397734,13 +399279,20 @@ var ts; if (sourceMapFilePath) { var sourceMap = sourceMapGenerator.toString(); ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + if (printer.bundleFileInfo) + printer.bundleFileInfo.mapHash = ts.computeSignature(sourceMap, ts.maybeBind(host, host.createHash)); } } else { writer.writeLine(); } // Write the output file - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos }); + var text = writer.getText(); + ts.writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos, diagnostics: transform.diagnostics }); + // We store the hash of the text written in the buildinfo to ensure that text of the referenced d.ts file is same as whats in the buildinfo + // This is needed because incremental can be toggled between two runs and we might use stale file text to do text manipulation in prepend mode + if (printer.bundleFileInfo) + printer.bundleFileInfo.hash = ts.computeSignature(text, ts.maybeBind(host, host.createHash)); // Reset state writer.clear(); } @@ -397883,34 +399435,56 @@ var ts; } /*@internal*/ function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) { + var createHash = ts.maybeBind(host, host.createHash); var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; - var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath)); - if (!buildInfoText) + var buildInfo; + if (host.getBuildInfo) { + // If host directly provides buildinfo we can get it directly. This allows host to cache the buildinfo + var hostBuildInfo = host.getBuildInfo(buildInfoPath, config.options.configFilePath); + if (!hostBuildInfo) + return buildInfoPath; + buildInfo = hostBuildInfo; + } + else { + var buildInfoText = host.readFile(buildInfoPath); + if (!buildInfoText) + return buildInfoPath; + buildInfo = getBuildInfo(buildInfoText); + } + if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationFilePath && !buildInfo.bundle.dts)) return buildInfoPath; var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath)); if (!jsFileText) return jsFilePath; + // If the jsFileText is not same has what it was created with, tsbuildinfo is stale so dont use it + if (ts.computeSignature(jsFileText, createHash) !== buildInfo.bundle.js.hash) + return jsFilePath; var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath); // error if no source map or for now if inline sourcemap if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap) return sourceMapFilePath || "inline sourcemap decoding"; + if (sourceMapFilePath && ts.computeSignature(sourceMapText, createHash) !== buildInfo.bundle.js.mapHash) + return sourceMapFilePath; // read declaration text var declarationText = declarationFilePath && host.readFile(declarationFilePath); if (declarationFilePath && !declarationText) return declarationFilePath; + if (declarationFilePath && ts.computeSignature(declarationText, createHash) !== buildInfo.bundle.dts.hash) + return declarationFilePath; var declarationMapText = declarationMapPath && host.readFile(declarationMapPath); // error if no source map or for now if inline sourcemap if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap) return declarationMapPath || "inline sourcemap decoding"; - var buildInfo = getBuildInfo(buildInfoText); - if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts)) - return buildInfoPath; + if (declarationMapPath && ts.computeSignature(declarationMapText, createHash) !== buildInfo.bundle.dts.mapHash) + return declarationMapPath; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, /*onlyOwnText*/ true); var outputFiles = []; var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); }); var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host); + var changedDtsText; + var changedDtsData; var emitHost = { getPrependNodes: ts.memoize(function () { return __spreadArray(__spreadArray([], prependNodes, true), [ownPrependInput], false); }), getCanonicalFileName: host.getCanonicalFileName, @@ -397926,7 +399500,7 @@ var ts; getResolvedProjectReferenceToRedirect: ts.returnUndefined, getProjectReferenceRedirect: ts.returnUndefined, isSourceOfProjectReferenceRedirect: ts.returnFalse, - writeFile: function (name, text, writeByteOrderMark) { + writeFile: function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { switch (name) { case jsFilePath: if (jsFileText === text) @@ -397937,8 +399511,12 @@ var ts; return; break; case buildInfoPath: - var newBuildInfo = getBuildInfo(text); + var newBuildInfo = data.buildInfo; newBuildInfo.program = buildInfo.program; + if (newBuildInfo.program && changedDtsText !== undefined && config.options.composite) { + // Update the output signature + newBuildInfo.program.outSignature = ts.computeSignature(changedDtsText, createHash, changedDtsData); + } // Update sourceFileInfo var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles; newBuildInfo.bundle.js.sources = js.sources; @@ -397946,11 +399524,13 @@ var ts; newBuildInfo.bundle.dts.sources = dts.sources; } newBuildInfo.bundle.sourceFiles = sourceFiles; - outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark }); + outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark, buildInfo: newBuildInfo }); return; case declarationFilePath: if (declarationText === text) return; + changedDtsText = text; + changedDtsData = data; break; case declarationMapPath: if (declarationMapText === text) @@ -397969,6 +399549,7 @@ var ts; getSourceFileFromReference: ts.returnUndefined, redirectTargetsMap: ts.createMultiMap(), getFileIncludeReasons: ts.notImplemented, + createHash: createHash, }; emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers)); @@ -399056,8 +400637,7 @@ var ts; } } function emitParameter(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); @@ -399068,7 +400648,7 @@ var ts; emitTypeAnnotation(node.type); } // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator) { writePunctuation("@"); @@ -399078,7 +400658,6 @@ var ts; // Type members // function emitPropertySignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); @@ -399086,8 +400665,7 @@ var ts; writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); emit(node.exclamationToken); @@ -399097,7 +400675,6 @@ var ts; } function emitMethodSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); @@ -399108,16 +400685,13 @@ var ts; popNameGenerationScope(node); } function emitMethodDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.asteriskToken); emit(node.name); emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitClassStaticBlockDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("static"); emitBlockFunctionBody(node.body); } @@ -399127,8 +400701,7 @@ var ts; emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword(node.kind === 172 /* SyntaxKind.GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); @@ -399136,8 +400709,6 @@ var ts; } function emitCallSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); @@ -399146,8 +400717,6 @@ var ts; } function emitConstructSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -399157,7 +400726,6 @@ var ts; popNameGenerationScope(node); } function emitIndexSignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); @@ -399550,7 +401118,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitSignatureAndBody(node, emitArrowFunctionHead); } @@ -400031,7 +401598,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitFunctionDeclarationOrExpression(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); emit(node.asteriskToken); @@ -400089,8 +401655,8 @@ var ts; if (!ts.nodeIsSynthesized(body) && currentSourceFile && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { return false; } - if (getLeadingLineTerminatorCount(body, body.statements, 2 /* ListFormat.PreserveLines */) - || getClosingLineTerminatorCount(body, body.statements, 2 /* ListFormat.PreserveLines */)) { + if (getLeadingLineTerminatorCount(body, ts.firstOrUndefined(body.statements), 2 /* ListFormat.PreserveLines */) + || getClosingLineTerminatorCount(body, ts.lastOrUndefined(body.statements), 2 /* ListFormat.PreserveLines */, body.statements)) { return false; } var previousStatement; @@ -400138,8 +401704,7 @@ var ts; } function emitClassDeclarationOrExpression(node) { ts.forEach(node.members, generateMemberNames); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword("class"); if (node.name) { writeSpace(); @@ -400160,7 +401725,6 @@ var ts; } } function emitInterfaceDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("interface"); writeSpace(); @@ -400173,7 +401737,6 @@ var ts; writePunctuation("}"); } function emitTypeAliasDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("type"); writeSpace(); @@ -400800,8 +402363,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* BundleFileSectionKind.Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_24 = types; _d < types_24.length; _d++) { - var directive = types_24[_d]; + for (var _d = 0, types_23 = types; _d < types_23.length; _d++) { + var directive = types_23[_d]; var pos = writer.getTextPos(); var resolutionMode = directive.resolutionMode && directive.resolutionMode !== (currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.impliedNodeFormat) ? "resolution-mode=\"".concat(directive.resolutionMode === ts.ModuleKind.ESNext ? "import" : "require", "\"") @@ -400975,12 +402538,52 @@ var ts; emit(node); write = savedWrite; } - function emitModifiers(node, modifiers) { - if (modifiers && modifiers.length) { - emitList(node, modifiers, 262656 /* ListFormat.Modifiers */); - writeSpace(); + function emitDecoratorsAndModifiers(node, modifiers) { + if (modifiers === null || modifiers === void 0 ? void 0 : modifiers.length) { + if (ts.every(modifiers, ts.isModifier)) { + // if all modifier-likes are `Modifier`, simply emit the array as modifiers. + return emitModifiers(node, modifiers); + } + if (ts.every(modifiers, ts.isDecorator)) { + // if all modifier-likes are `Decorator`, simply emit the array as decorators. + return emitDecorators(node, modifiers); + } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(modifiers); + // partition modifiers into contiguous chunks of `Modifier` or `Decorator` + var lastMode = void 0; + var mode = void 0; + var start = 0; + var pos = 0; + while (start < modifiers.length) { + while (pos < modifiers.length) { + var modifier = modifiers[pos]; + mode = ts.isDecorator(modifier) ? "decorators" : "modifiers"; + if (lastMode === undefined) { + lastMode = mode; + } + else if (mode !== lastMode) { + break; + } + pos++; + } + var textRange = { pos: -1, end: -1 }; + if (start === 0) + textRange.pos = modifiers.pos; + if (pos === modifiers.length - 1) + textRange.end = modifiers.end; + emitNodeListItems(emit, node, modifiers, lastMode === "modifiers" ? 2359808 /* ListFormat.Modifiers */ : 2146305 /* ListFormat.Decorators */, + /*parenthesizerRule*/ undefined, start, pos - start, + /*hasTrailingComma*/ false, textRange); + start = pos; + lastMode = mode; + pos++; + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(modifiers); } } + function emitModifiers(node, modifiers) { + emitList(node, modifiers, 2359808 /* ListFormat.Modifiers */); + } function emitTypeAnnotation(node) { if (node) { writePunctuation(":"); @@ -401058,11 +402661,9 @@ var ts; && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head && !parentNode.type // arrow function may not have return type annotation - && !ts.some(parentNode.decorators) // parent may not have decorators - && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.modifiers) // parent may not have decorators or modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters - && !ts.some(parameter.decorators) // parameter may not have decorators - && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !ts.some(parameter.modifiers) // parameter may not have decorators or modifiers && !parameter.dotDotDotToken // parameter may not be rest && !parameter.questionToken // parameter may not be optional && !parameter.type // parameter may not have a type annotation @@ -401117,12 +402718,8 @@ var ts; } var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 32768 /* ListFormat.OptionalIfEmpty */) { - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); return; } if (format & 15360 /* ListFormat.BracketsMask */) { @@ -401131,9 +402728,7 @@ var ts; emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); if (isEmpty) { // Write a line terminator if the parent node was multi-line if (format & 1 /* ListFormat.MultiLine */ && !(preserveSourceNewlines && (!parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) { @@ -401144,123 +402739,128 @@ var ts; } } else { - ts.Debug.type(children); - // Write the opening line terminator or leading whitespace. - var mayEmitInterveningComments = (format & 262144 /* ListFormat.NoInterveningComments */) === 0; - var shouldEmitInterveningComments = mayEmitInterveningComments; - var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217 - if (leadingLineTerminatorCount) { - writeLine(leadingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (format & 256 /* ListFormat.SpaceBetweenBraces */) { - writeSpace(); - } - // Increase the indent, if requested. - if (format & 128 /* ListFormat.Indented */) { - increaseIndent(); + emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, children.hasTrailingComma, children); + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); + if (format & 15360 /* ListFormat.BracketsMask */) { + if (isEmpty && children) { + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } - var emitListItem = getEmitListItem(emit, parenthesizerRule); - // Emit each child. - var previousSibling = void 0; - var previousSourceFileTextKind = void 0; - var shouldDecreaseIndentAfterEmit = false; - for (var i = 0; i < count; i++) { - var child = children[start + i]; - // Write the delimiter if this is not the first node. - if (format & 32 /* ListFormat.AsteriskDelimited */) { - // always write JSDoc in the format "\n *" - writeLine(); - writeDelimiter(format); - } - else if (previousSibling) { - // i.e - // function commentedParameters( - // /* Parameter a */ - // a - // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline - // , - if (format & 60 /* ListFormat.DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { - emitLeadingCommentsOfPosition(previousSibling.end); - } - writeDelimiter(format); - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - // Write either a line terminator or whitespace to separate the elements. - var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); - if (separatingLineTerminatorCount > 0) { - // If a synthesized node in a single-line list starts on a new - // line, we should increase the indent. - if ((format & (3 /* ListFormat.LinesMask */ | 128 /* ListFormat.Indented */)) === 0 /* ListFormat.SingleLine */) { - increaseIndent(); - shouldDecreaseIndentAfterEmit = true; - } - writeLine(separatingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (previousSibling && format & 512 /* ListFormat.SpaceBetweenSiblings */) { - writeSpace(); - } - } - // Emit this child. - previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); - if (shouldEmitInterveningComments) { - var commentRange = ts.getCommentRange(child); - emitTrailingCommentsOfPosition(commentRange.pos); - } - else { - shouldEmitInterveningComments = mayEmitInterveningComments; - } - nextListElementPos = child.pos; - emitListItem(child, emit, parenthesizerRule, i); - if (shouldDecreaseIndentAfterEmit) { - decreaseIndent(); - shouldDecreaseIndentAfterEmit = false; + writePunctuation(getClosingBracket(format)); + } + } + /** + * Emits a list without brackets or raising events. + * + * NOTE: You probably don't want to call this directly and should be using `emitList` or `emitExpressionList` instead. + */ + function emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, hasTrailingComma, childrenTextRange) { + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 262144 /* ListFormat.NoInterveningComments */) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children[start], format); + if (leadingLineTerminatorCount) { + writeLine(leadingLineTerminatorCount); + shouldEmitInterveningComments = false; + } + else if (format & 256 /* ListFormat.SpaceBetweenBraces */) { + writeSpace(); + } + // Increase the indent, if requested. + if (format & 128 /* ListFormat.Indented */) { + increaseIndent(); + } + var emitListItem = getEmitListItem(emit, parenthesizerRule); + // Emit each child. + var previousSibling; + var previousSourceFileTextKind; + var shouldDecreaseIndentAfterEmit = false; + for (var i = 0; i < count; i++) { + var child = children[start + i]; + // Write the delimiter if this is not the first node. + if (format & 32 /* ListFormat.AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , + if (format & 60 /* ListFormat.DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + writeDelimiter(format); + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + // Write either a line terminator or whitespace to separate the elements. + var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); + if (separatingLineTerminatorCount > 0) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* ListFormat.LinesMask */ | 128 /* ListFormat.Indented */)) === 0 /* ListFormat.SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(separatingLineTerminatorCount); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 512 /* ListFormat.SpaceBetweenSiblings */) { + writeSpace(); } - previousSibling = child; } - // Write a trailing comma, if requested. - var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; - var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* EmitFlags.NoTrailingComments */); - var hasTrailingComma = (children === null || children === void 0 ? void 0 : children.hasTrailingComma) && (format & 64 /* ListFormat.AllowTrailingComma */) && (format & 16 /* ListFormat.CommaDelimited */); - if (hasTrailingComma) { - if (previousSibling && !skipTrailingComments) { - emitTokenWithComment(27 /* SyntaxKind.CommaToken */, previousSibling.end, writePunctuation, previousSibling); - } - else { - writePunctuation(","); - } + // Emit this child. + previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); + if (shouldEmitInterveningComments) { + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); } - // Emit any trailing comment of the last element in the list - // i.e - // var array = [... - // 2 - // /* end of element 2 */ - // ]; - if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* ListFormat.DelimitersMask */) && !skipTrailingComments) { - emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end); + else { + shouldEmitInterveningComments = mayEmitInterveningComments; } - // Decrease the indent, if requested. - if (format & 128 /* ListFormat.Indented */) { + nextListElementPos = child.pos; + emitListItem(child, emit, parenthesizerRule, i); + if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; } - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - // Write the closing line terminator or closing whitespace. - var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format); - if (closingLineTerminatorCount) { - writeLine(closingLineTerminatorCount); + previousSibling = child; + } + // Write a trailing comma, if requested. + var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; + var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* EmitFlags.NoTrailingComments */); + var emitTrailingComma = hasTrailingComma && (format & 64 /* ListFormat.AllowTrailingComma */) && (format & 16 /* ListFormat.CommaDelimited */); + if (emitTrailingComma) { + if (previousSibling && !skipTrailingComments) { + emitTokenWithComment(27 /* SyntaxKind.CommaToken */, previousSibling.end, writePunctuation, previousSibling); } - else if (format & (2097152 /* ListFormat.SpaceAfterList */ | 256 /* ListFormat.SpaceBetweenBraces */)) { - writeSpace(); + else { + writePunctuation(","); } } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* ListFormat.DelimitersMask */) && !skipTrailingComments) { + emitLeadingCommentsOfPosition(emitTrailingComma && (childrenTextRange === null || childrenTextRange === void 0 ? void 0 : childrenTextRange.end) ? childrenTextRange.end : previousSibling.end); } - if (format & 15360 /* ListFormat.BracketsMask */) { - if (isEmpty && children) { - emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists - } - writePunctuation(getClosingBracket(format)); + // Decrease the indent, if requested. + if (format & 128 /* ListFormat.Indented */) { + decreaseIndent(); + } + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + // Write the closing line terminator or closing whitespace. + var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children[start + count - 1], format, childrenTextRange); + if (closingLineTerminatorCount) { + writeLine(closingLineTerminatorCount); + } + else if (format & (2097152 /* ListFormat.SpaceAfterList */ | 256 /* ListFormat.SpaceBetweenBraces */)) { + writeSpace(); } } // Writers @@ -401390,16 +402990,15 @@ var ts; decreaseIndent(); } } - function getLeadingLineTerminatorCount(parentNode, children, format) { + function getLeadingLineTerminatorCount(parentNode, firstChild, format) { if (format & 2 /* ListFormat.PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* ListFormat.PreferNewLine */) { return 1; } - var firstChild_1 = children[0]; - if (firstChild_1 === undefined) { + if (firstChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - if (firstChild_1.pos === nextListElementPos) { + if (firstChild.pos === nextListElementPos) { // If this child starts at the beginning of a list item in a parent list, its leading // line terminators have already been written as the separating line terminators of the // parent list. Example: @@ -401417,20 +403016,20 @@ var ts; // leading newline to start the modifiers. return 0; } - if (firstChild_1.kind === 11 /* SyntaxKind.JsxText */) { + if (firstChild.kind === 11 /* SyntaxKind.JsxText */) { // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && - !ts.nodeIsSynthesized(firstChild_1) && - (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) { + !ts.nodeIsSynthesized(firstChild) && + (!firstChild.parent || ts.getOriginalNode(firstChild.parent) === ts.getOriginalNode(parentNode))) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild.pos, parentNode.pos, currentSourceFile, includeComments); }); } - return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; + return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile) ? 0 : 1; } - if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) { + if (synthesizedNodeStartsOnNewLine(firstChild, format)) { return 1; } } @@ -401470,18 +403069,17 @@ var ts; } return format & 1 /* ListFormat.MultiLine */ ? 1 : 0; } - function getClosingLineTerminatorCount(parentNode, children, format) { + function getClosingLineTerminatorCount(parentNode, lastChild, format, childrenTextRange) { if (format & 2 /* ListFormat.PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* ListFormat.PreferNewLine */) { return 1; } - var lastChild = ts.lastOrUndefined(children); if (lastChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { - var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end; + var end_1 = childrenTextRange && !ts.positionIsSynthesized(childrenTextRange.end) ? childrenTextRange.end : lastChild.end; return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); }); } return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1; @@ -401519,14 +403117,14 @@ var ts; return lines; } function writeLineSeparatorsAndIndentBefore(node, parent) { - var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* ListFormat.None */); + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, node, 0 /* ListFormat.None */); if (leadingNewlines) { writeLinesAndIndent(leadingNewlines, /*writeSpaceIfNotIndenting*/ false); } return !!leadingNewlines; } function writeLineSeparatorsAfter(node, parent) { - var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* ListFormat.None */); + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, node, 0 /* ListFormat.None */, /*childrenTextRange*/ undefined); if (trailingNewlines) { writeLine(trailingNewlines); } @@ -403053,12 +404651,10 @@ var ts; } ts.createCompilerHost = createCompilerHost; /*@internal*/ - // TODO(shkamat): update this after reworking ts build API function createCompilerHostWorker(options, setParentNodes, system) { if (system === void 0) { system = ts.sys; } var existingDirectories = new ts.Map(); var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); - var computeHash = ts.maybeBind(system, system.createHash) || ts.generateDjb2Hash; function getSourceFile(fileName, languageVersionOrOptions, onError) { var text; try { @@ -403091,7 +404687,7 @@ var ts; // NOTE: If patchWriteFileEnsuringDirectory has been called, // the system.writeFile will do its own directory creation and // the ensureDirectoriesExist call will always be redundant. - ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); + ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } @@ -403101,35 +404697,6 @@ var ts; } } } - var outputFingerprints; - function writeFileWorker(fileName, data, writeByteOrderMark) { - if (!ts.isWatchSet(options) || !system.getModifiedTime) { - system.writeFile(fileName, data, writeByteOrderMark); - return; - } - if (!outputFingerprints) { - outputFingerprints = new ts.Map(); - } - var hash = computeHash(data); - var mtimeBefore = system.getModifiedTime(fileName); - if (mtimeBefore) { - var fingerprint = outputFingerprints.get(fileName); - // If output has not been changed, and the file has no external modification - if (fingerprint && - fingerprint.byteOrderMark === writeByteOrderMark && - fingerprint.hash === hash && - fingerprint.mtime.getTime() === mtimeBefore.getTime()) { - return; - } - } - system.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; - outputFingerprints.set(fileName, { - hash: hash, - byteOrderMark: writeByteOrderMark, - mtime: mtimeAfter - }); - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } @@ -403236,7 +404803,7 @@ var ts; }; } // directoryExists - if (originalDirectoryExists && originalCreateDirectory) { + if (originalDirectoryExists) { host.directoryExists = function (directory) { var key = toPath(directory); var value = directoryExistsCache.get(key); @@ -403246,11 +404813,13 @@ var ts; directoryExistsCache.set(key, !!newValue); return newValue; }; - host.createDirectory = function (directory) { - var key = toPath(directory); - directoryExistsCache.delete(key); - originalCreateDirectory.call(host, directory); - }; + if (originalCreateDirectory) { + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } } return { originalReadFile: originalReadFile, @@ -403753,6 +405322,12 @@ var ts; * @returns `undefined` if the path has no relevant implied format, `ModuleKind.ESNext` for esm format, and `ModuleKind.CommonJS` for cjs format */ function getImpliedNodeFormatForFile(fileName, packageJsonInfoCache, host, options) { + var result = getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options); + return typeof result === "object" ? result.impliedNodeFormat : result; + } + ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + /*@internal*/ + function getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options) { switch (ts.getEmitModuleResolutionKind(options)) { case ts.ModuleResolutionKind.Node16: case ts.ModuleResolutionKind.NodeNext: @@ -403764,11 +405339,16 @@ var ts; return undefined; } function lookupFromPackageJson() { - var scope = ts.getPackageScopeForPath(fileName, packageJsonInfoCache, host, options); - return (scope === null || scope === void 0 ? void 0 : scope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + var state = ts.getTemporaryModuleResolutionState(packageJsonInfoCache, host, options); + var packageJsonLocations = []; + state.failedLookupLocations = packageJsonLocations; + state.affectingLocations = packageJsonLocations; + var packageJsonScope = ts.getPackageScopeForPath(fileName, state); + var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.contents.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope }; } } - ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + ts.getImpliedNodeFormatForFileWorker = getImpliedNodeFormatForFileWorker; /** @internal */ ts.plainJSErrors = new ts.Set([ // binder errors @@ -403861,6 +405441,9 @@ var ts; ts.Diagnostics.extends_clause_already_seen.code, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, + ts.Diagnostics.Class_constructor_may_not_be_a_generator.code, + ts.Diagnostics.Class_constructor_may_not_be_an_accessor.code, + ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]); /** * Determine if source file needs to be re-created even if its text hasn't changed @@ -404090,7 +405673,7 @@ var ts; for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { var oldSourceFile = oldSourceFiles_1[_i]; var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); - if (shouldCreateNewSourceFile || !newFile || + if (shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || // old file wasn't redirect but new file is (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); @@ -404427,7 +406010,7 @@ var ts; // `result[i]` is either a `ResolvedModuleFull` or a marker. // If it is the former, we can leave it as is. if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; // TODO: GH#18217 + result[i] = undefined; } } else { @@ -404483,7 +406066,7 @@ var ts; }); } function tryReuseStructureFromOldProgram() { - var _a; + var _a, _b; if (!oldProgram) { return 0 /* StructureIsReused.Not */; } @@ -404524,12 +406107,15 @@ var ts; var seenPackageNames = new ts.Map(); for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; + var sourceFileOptions = getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options); var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), /*onError*/ undefined, shouldCreateNewSourceFile) - : host.getSourceFile(oldSourceFile.fileName, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, sourceFileOptions, /*onError*/ undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat) + : host.getSourceFile(oldSourceFile.fileName, sourceFileOptions, /*onError*/ undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat); // TODO: GH#18217 if (!newSourceFile) { return 0 /* StructureIsReused.Not */; } + newSourceFile.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + newSourceFile.packageJsonScope = sourceFileOptions.packageJsonScope; ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); var fileChanged = void 0; if (oldSourceFile.redirectInfo) { @@ -404569,38 +406155,43 @@ var ts; seenPackageNames.set(packageName, newKind); } if (fileChanged) { + if (oldSourceFile.impliedNodeFormat !== newSourceFile.impliedNodeFormat) { + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } // The `newSourceFile` object was created for the new program. - if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { // 'lib' references has changed. Matches behavior in changesAffectModuleResolution structureIsReused = 1 /* StructureIsReused.SafeModules */; } - if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + else if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files structureIsReused = 1 /* StructureIsReused.SafeModules */; } // check tripleslash references - if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed structureIsReused = 1 /* StructureIsReused.SafeModules */; } - // check imports and module augmentations - collectExternalModuleReferences(newSourceFile); - if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - // imports has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - // moduleAugmentations has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if ((oldSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */)) { - // dynamicImport has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - // 'types' references has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; + else { + // check imports and module augmentations + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if ((oldSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */)) { + // dynamicImport has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + // 'types' references has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } } // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); @@ -404618,18 +406209,18 @@ var ts; return structureIsReused; } var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); - for (var _b = 0, oldSourceFiles_3 = oldSourceFiles; _b < oldSourceFiles_3.length; _b++) { - var oldFile = oldSourceFiles_3[_b]; + for (var _c = 0, oldSourceFiles_3 = oldSourceFiles; _c < oldSourceFiles_3.length; _c++) { + var oldFile = oldSourceFiles_3[_c]; if (!ts.contains(modifiedFiles, oldFile)) { - for (var _c = 0, _d = oldFile.ambientModuleNames; _c < _d.length; _c++) { - var moduleName = _d[_c]; + for (var _d = 0, _e = oldFile.ambientModuleNames; _d < _e.length; _d++) { + var moduleName = _e[_d]; ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); } } } // try to verify results of module resolution - for (var _e = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _e < modifiedSourceFiles_1.length; _e++) { - var _f = modifiedSourceFiles_1[_e], oldSourceFile = _f.oldFile, newSourceFile = _f.newFile; + for (var _f = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _f < modifiedSourceFiles_1.length; _f++) { + var _g = modifiedSourceFiles_1[_f], oldSourceFile = _g.oldFile, newSourceFile = _g.newFile; var moduleNames = getModuleNames(newSourceFile); var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile); // ensure that module resolution results are still correct @@ -404656,14 +406247,14 @@ var ts; if (structureIsReused !== 2 /* StructureIsReused.Completely */) { return structureIsReused; } - if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_a = host.hasChangedAutomaticTypeDirectiveNames) === null || _a === void 0 ? void 0 : _a.call(host))) { + if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_b = host.hasChangedAutomaticTypeDirectiveNames) === null || _b === void 0 ? void 0 : _b.call(host))) { return 1 /* StructureIsReused.SafeModules */; } missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length); - for (var _g = 0, newSourceFiles_1 = newSourceFiles; _g < newSourceFiles_1.length; _g++) { - var newSourceFile = newSourceFiles_1[_g]; + for (var _h = 0, newSourceFiles_1 = newSourceFiles; _h < newSourceFiles_1.length; _h++) { + var newSourceFile = newSourceFiles_1[_h]; filesByName.set(newSourceFile.path, newSourceFile); } var oldFilesByNameMap = oldProgram.getFilesByNameMap(); @@ -404725,6 +406316,7 @@ var ts; getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); }, redirectTargetsMap: redirectTargetsMap, getFileIncludeReasons: program.getFileIncludeReasons, + createHash: ts.maybeBind(host, host.createHash), }; } function writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data) { @@ -405078,7 +406670,7 @@ var ts; } } function walkArray(nodes, parent) { - if (parent.decorators === nodes && !options.experimentalDecorators) { + if (ts.canHaveModifiers(parent) && parent.modifiers === nodes && ts.some(nodes, ts.isDecorator) && !options.experimentalDecorators) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { @@ -405109,7 +406701,7 @@ var ts; if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 124 /* SyntaxKind.StaticKeyword */) { + if (ts.isModifier(modifier) && modifier.kind !== 124 /* SyntaxKind.StaticKeyword */) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); } } @@ -405118,7 +406710,7 @@ var ts; break; case 164 /* SyntaxKind.Parameter */: // Check modifiers of parameter declaration - if (nodes === parent.modifiers) { + if (nodes === parent.modifiers && ts.some(nodes, ts.isModifier)) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } @@ -405237,7 +406829,7 @@ var ts; } function createSyntheticImport(text, file) { var externalHelpersModuleReference = ts.factory.createStringLiteral(text); - var importDecl = ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined); + var importDecl = ts.factory.createImportDeclaration(/*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined); ts.addEmitFlags(importDecl, 67108864 /* EmitFlags.NeverApplyImportHelper */); ts.setParent(externalHelpersModuleReference, importDecl); ts.setParent(importDecl, file); @@ -405445,13 +407037,16 @@ var ts; addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, [fileName, existingFile.fileName]); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName, sourceFileOptions) { + var _a; var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; redirect.resolvedPath = resolvedPath; redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + redirect.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + redirect.packageJsonScope = sourceFileOptions.packageJsonScope; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { @@ -405480,14 +407075,14 @@ var ts; // It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache // and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way // to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront. - var impliedNodeFormat = getImpliedNodeFormatForFile(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); - return { - languageVersion: ts.getEmitScriptTarget(options), - impliedNodeFormat: impliedNodeFormat, - setExternalModuleIndicator: ts.getSetExternalModuleIndicator(options) - }; + var result = getImpliedNodeFormatForFileWorker(ts.getNormalizedAbsolutePath(fileName, currentDirectory), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); + var languageVersion = ts.getEmitScriptTarget(options); + var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options); + return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) : + { languageVersion: languageVersion, impliedNodeFormat: result, setExternalModuleIndicator: setExternalModuleIndicator }; } function findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { + var _a, _b; var path = toPath(fileName); if (useSourceOfProjectReferenceRedirect) { var source = getSourceOfProjectReferenceRedirect(path); @@ -405574,14 +407169,15 @@ var ts; } } // We haven't looked for this file, do so now and cache result - var file = host.getSourceFile(fileName, getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options), function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile); + var sourceFileOptions = getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options); + var file = host.getSourceFile(fileName, sourceFileOptions, function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile || (((_a = oldProgram === null || oldProgram === void 0 ? void 0 : oldProgram.getSourceFileByPath(toPath(fileName))) === null || _a === void 0 ? void 0 : _a.impliedNodeFormat) !== sourceFileOptions.impliedNodeFormat)); if (packageId) { var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName, sourceFileOptions); redirectTargetsMap.add(fileFromPackageId.path, fileName); addFileToFilesByName(dupFile, path, redirectedPath); addFileIncludeReason(dupFile, reason); @@ -405602,6 +407198,8 @@ var ts; file.path = path; file.resolvedPath = toPath(fileName); file.originalFileName = originalFileName; + file.packageJsonLocations = ((_b = sourceFileOptions.packageJsonLocations) === null || _b === void 0 ? void 0 : _b.length) ? sourceFileOptions.packageJsonLocations : undefined; + file.packageJsonScope = sourceFileOptions.packageJsonScope; addFileIncludeReason(file, reason); if (host.useCaseSensitiveFileNames()) { var pathLowerCase = ts.toFileNameLowerCase(path); @@ -405747,7 +407345,7 @@ var ts; } } function processTypeReferenceDirective(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolvedTypeReferenceDirective, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -406232,7 +407830,7 @@ var ts; fileIncludeReasons = undefined; var location = locationReason && getReferencedFileLocation(getSourceFileByPath, locationReason); var fileIncludeReasonDetails = fileIncludeReasons && ts.chainDiagnosticMessages(fileIncludeReasons, ts.Diagnostics.The_file_is_in_the_program_because_Colon); - var redirectInfo = file && ts.explainIfFileIsRedirect(file); + var redirectInfo = file && ts.explainIfFileIsRedirectAndImpliedFormat(file); var chain = ts.chainDiagnosticMessages.apply(void 0, __spreadArray([redirectInfo ? fileIncludeReasonDetails ? __spreadArray([fileIncludeReasonDetails], redirectInfo, true) : redirectInfo : fileIncludeReasonDetails, diagnostic], args || ts.emptyArray, false)); return location && isReferenceFileLocation(location) ? ts.createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) : @@ -406302,7 +407900,7 @@ var ts; } var matchedByInclude = ts.getMatchedIncludeSpec(program, fileName); // Could be additional files specified as roots - if (!matchedByInclude) + if (!matchedByInclude || !ts.isString(matchedByInclude)) return undefined; configFileNode = ts.getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude); message = ts.Diagnostics.File_is_matched_by_include_pattern_specified_here; @@ -406826,8 +408424,8 @@ var ts; (function (ts) { function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) { var outputFiles = []; - var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit; - return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; + var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics; + return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -406838,13 +408436,9 @@ var ts; function createManyToManyPathMap() { function create(forward, reverse, deleted) { var map = { - clone: function () { return create(new ts.Map(forward), new ts.Map(reverse), deleted && new ts.Set(deleted)); }, - forEach: function (fn) { return forward.forEach(fn); }, getKeys: function (v) { return reverse.get(v); }, getValues: function (k) { return forward.get(k); }, - hasKey: function (k) { return forward.has(k); }, keys: function () { return forward.keys(); }, - deletedKeys: function () { return deleted; }, deleteKey: function (k) { (deleted || (deleted = new ts.Set())).add(k); var set = forward.get(k); @@ -406871,11 +408465,6 @@ var ts; }); return map; }, - clear: function () { - forward.clear(); - reverse.clear(); - deleted === null || deleted === void 0 ? void 0 : deleted.clear(); - } }; return map; } @@ -407003,18 +408592,21 @@ var ts; * Creates the state of file references and signature for the new program from oldState if it is safe */ function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b, _c; var fileInfos = new ts.Map(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? createManyToManyPathMap() : undefined; var exportedModulesMap = referencedMap ? createManyToManyPathMap() : undefined; - var hasCalledUpdateShapeSignature = new ts.Set(); var useOldState = canReuseOldState(referencedMap, oldState); // Ensure source files have parent pointers set newProgram.getTypeChecker(); // Create the reference map, and set the file infos - for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; + for (var _i = 0, _d = newProgram.getSourceFiles(); _i < _d.length; _i++) { + var sourceFile = _d[_i]; var version_2 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); - var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined; + var oldUncommittedSignature = useOldState ? (_a = oldState.oldSignatures) === null || _a === void 0 ? void 0 : _a.get(sourceFile.resolvedPath) : undefined; + var signature = oldUncommittedSignature === undefined ? + useOldState ? (_b = oldState.fileInfos.get(sourceFile.resolvedPath)) === null || _b === void 0 ? void 0 : _b.signature : undefined : + oldUncommittedSignature || undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); if (newReferences) { @@ -407022,19 +408614,26 @@ var ts; } // Copy old visible to outside files map if (useOldState) { - var exportedModules = oldState.exportedModulesMap.getValues(sourceFile.resolvedPath); + var oldUncommittedExportedModules = (_c = oldState.oldExportedModulesMap) === null || _c === void 0 ? void 0 : _c.get(sourceFile.resolvedPath); + var exportedModules = oldUncommittedExportedModules === undefined ? + oldState.exportedModulesMap.getValues(sourceFile.resolvedPath) : + oldUncommittedExportedModules || undefined; if (exportedModules) { exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, impliedFormat: sourceFile.impliedNodeFormat }); + fileInfos.set(sourceFile.resolvedPath, { + version: version_2, + signature: signature, + affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, + impliedFormat: sourceFile.impliedNodeFormat + }); } return { fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } @@ -407048,120 +408647,95 @@ var ts; } BuilderState.releaseCache = releaseCache; /** - * Creates a clone of the state + * Gets the files affected by the path from the program */ - function clone(state) { + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var _a, _b; - // Dont need to backup allFiles info since its cache anyway - return { - fileInfos: new ts.Map(state.fileInfos), - referencedMap: (_a = state.referencedMap) === null || _a === void 0 ? void 0 : _a.clone(), - exportedModulesMap: (_b = state.exportedModulesMap) === null || _b === void 0 ? void 0 : _b.clone(), - hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature), - useFileVersionAsSignature: state.useFileVersionAsSignature, - }; + var result = getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); + return result; } - BuilderState.clone = clone; - /** - * Gets the files affected by the path from the program - */ - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { - // Since the operation could be cancelled, the signatures are always stored in the cache - // They will be committed once it is safe to use them - // eg when calling this api from tsserver, if there is no cancellation of the operation - // In the other cases the affected files signatures are committed only after the iteration through the result is complete - var signatureCache = cacheToUpdateSignature || new ts.Map(); + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + function getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var sourceFile = programOfThisState.getSourceFileByPath(path); if (!sourceFile) { return ts.emptyArray; } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { + if (!updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName)) { return [sourceFile]; } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); - if (!cacheToUpdateSignature) { - // Commit all the signatures in the signature cache - updateSignaturesFromCache(state, signatureCache); - } - return result; + return (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName); } - BuilderState.getFilesAffectedBy = getFilesAffectedBy; - /** - * Updates the signatures from the cache into state's fileinfo signatures - * This should be called whenever it is safe to commit the state of the builder - */ - function updateSignaturesFromCache(state, signatureCache) { - signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); }); - } - BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + BuilderState.getFilesAffectedByWithOldState = getFilesAffectedByWithOldState; function updateSignatureOfFile(state, signature, path) { state.fileInfos.get(path).signature = signature; - state.hasCalledUpdateShapeSignature.add(path); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(path); } BuilderState.updateSignatureOfFile = updateSignatureOfFile; /** * Returns if the shape of the signature has changed since last emit */ - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache, useFileVersionAsSignature) { + function updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName, useFileVersionAsSignature) { + var _a; if (useFileVersionAsSignature === void 0) { useFileVersionAsSignature = state.useFileVersionAsSignature; } - ts.Debug.assert(!!sourceFile); - ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate - if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) { + if ((_a = state.hasCalledUpdateShapeSignature) === null || _a === void 0 ? void 0 : _a.has(sourceFile.resolvedPath)) return false; - } var info = state.fileInfos.get(sourceFile.resolvedPath); - if (!info) - return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; if (!sourceFile.isDeclarationFile && !useFileVersionAsSignature) { - var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, - /*emitOnlyDtsFiles*/ true, cancellationToken, + programOfThisState.emit(sourceFile, function (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) { + ts.Debug.assert(ts.isDeclarationFileName(fileName), "File extension for signature expected to be dts: Got:: ".concat(fileName)); + latestSignature = ts.computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data); + if (latestSignature !== prevSignature) { + updateExportedModules(state, sourceFile, sourceFiles[0].exportedModulesFromDeclarationEmit); + } + }, cancellationToken, + /*emitOnlyDtsFiles*/ true, /*customTransformers*/ undefined, /*forceDtsEmit*/ true); - var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); - if (firstDts_1) { - ts.Debug.assert(ts.isDeclarationFileName(firstDts_1.name), "File extension for signature expected to be dts", function () { return "Found: ".concat(ts.getAnyExtensionFromPath(firstDts_1.name), " for ").concat(firstDts_1.name, ":: All output files: ").concat(JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; }))); }); - latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); - if (exportedModulesMapCache && latestSignature !== prevSignature) { - updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); - } - } } // Default is to use file version as signature if (latestSignature === undefined) { latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { + if (state.exportedModulesMap && latestSignature !== prevSignature) { + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); // All the references in this file are exported var references = state.referencedMap ? state.referencedMap.getValues(sourceFile.resolvedPath) : undefined; if (references) { - exportedModulesMapCache.set(sourceFile.resolvedPath, references); + state.exportedModulesMap.set(sourceFile.resolvedPath, references); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } } } - cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); + (state.oldSignatures || (state.oldSignatures = new ts.Map())).set(sourceFile.resolvedPath, prevSignature || false); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(sourceFile.resolvedPath); + info.signature = latestSignature; return latestSignature !== prevSignature; } BuilderState.updateShapeSignature = updateShapeSignature; /** * Coverts the declaration emit result into exported modules map */ - function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + function updateExportedModules(state, sourceFile, exportedModulesFromDeclarationEmit) { + if (!state.exportedModulesMap) + return; + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); if (!exportedModulesFromDeclarationEmit) { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); return; } var exportedModules; exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFilesFromImportedModuleSymbol(symbol)); }); if (exportedModules) { - exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules); + state.exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } function addExportedModule(exportedModulePaths) { if (exportedModulePaths === null || exportedModulePaths === void 0 ? void 0 : exportedModulePaths.length) { @@ -407173,19 +408747,6 @@ var ts; } } BuilderState.updateExportedModules = updateExportedModules; - /** - * Updates the exported modules from cache into state's exported modules map - * This should be called whenever it is safe to commit the state of the builder - */ - function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { - var _a; - if (exportedModulesMapCache) { - ts.Debug.assert(!!state.exportedModulesMap); - (_a = exportedModulesMapCache.deletedKeys()) === null || _a === void 0 ? void 0 : _a.forEach(function (path) { return state.exportedModulesMap.deleteKey(path); }); - exportedModulesMapCache.forEach(function (exportedModules, path) { return state.exportedModulesMap.set(path, exportedModules); }); - } - } - BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; /** * Get all the dependencies of the sourceFile */ @@ -407306,7 +408867,7 @@ var ts; /** * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cancellationToken, computeHash, getCanonicalFileName) { if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -407326,7 +408887,7 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cancellationToken, computeHash, getCanonicalFileName)) { queue.push.apply(queue, getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } @@ -407352,32 +408913,33 @@ var ts; * Create the state so that we can iterate on changedFiles/affected files */ function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b; var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; + var outFilePath = ts.outFile(compilerOptions); // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them - if (!ts.outFile(compilerOptions)) { + if (!outFilePath) { state.semanticDiagnosticsPerFile = new ts.Map(); } + else if (compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.outSignature) && outFilePath === ts.outFile(oldState === null || oldState === void 0 ? void 0 : oldState.compilerOptions)) { + state.outSignature = oldState === null || oldState === void 0 ? void 0 : oldState.outSignature; + } state.changedFilesSet = new ts.Set(); + state.latestChangedDtsFile = compilerOptions.composite ? oldState === null || oldState === void 0 ? void 0 : oldState.latestChangedDtsFile : undefined; var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + var canCopyEmitSignatures = compilerOptions.composite && + (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && + !outFilePath && + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); if (useOldState) { - // Verify the sanity of old state - if (!oldState.currentChangedFilePath) { - var affectedSignatures = oldState.currentAffectedFilesSignatures; - ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); - } - var changedFilesSet = oldState.changedFilesSet; - if (canCopySemanticDiagnostics) { - ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); - } // Copy old state's changed files set - changedFilesSet === null || changedFilesSet === void 0 ? void 0 : changedFilesSet.forEach(function (value) { return state.changedFilesSet.add(value); }); - if (!ts.outFile(compilerOptions) && oldState.affectedFilesPendingEmit) { + (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); + if (!outFilePath && oldState.affectedFilesPendingEmit) { state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice(); state.affectedFilesPendingEmitKind = oldState.affectedFilesPendingEmitKind && new ts.Map(oldState.affectedFilesPendingEmitKind); state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; @@ -407398,6 +408960,8 @@ var ts; !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || // versions dont match oldInfo.version !== info.version || + // Implied formats dont match + oldInfo.impliedFormat !== info.impliedFormat || // Referenced files changed !hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) || // Referenced file was deleted in the new program @@ -407421,27 +408985,25 @@ var ts; state.semanticDiagnosticsFromOldState.add(sourceFilePath); } } + if (canCopyEmitSignatures) { + var oldEmitSignature = oldState.emitSignatures.get(sourceFilePath); + if (oldEmitSignature) + (state.emitSignatures || (state.emitSignatures = new ts.Map())).set(sourceFilePath, oldEmitSignature); + } }); // If the global file is removed, add all files as changed if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) { ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined) .forEach(function (file) { return state.changedFilesSet.add(file.resolvedPath); }); } - else if (oldCompilerOptions && !ts.outFile(compilerOptions) && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { + else if (oldCompilerOptions && !outFilePath && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { // Add all files to affectedFilesPendingEmit since emit changed newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* BuilderFileEmit.Full */); }); ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size); state.seenAffectedFiles = state.seenAffectedFiles || new ts.Set(); } - if (useOldState) { - // Any time the interpretation of a source file changes, mark it as changed - ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { - if (state.fileInfos.has(sourceFilePath) && state.fileInfos.get(sourceFilePath).impliedFormat !== info.impliedFormat) { - state.changedFilesSet.add(sourceFilePath); - } - }); - } - state.buildInfoEmitPending = !!state.changedFilesSet.size; + // Since old states change files set is copied, any additional change means we would need to emit build info + state.buildInfoEmitPending = !useOldState || state.changedFilesSet.size !== (((_b = oldState.changedFilesSet) === null || _b === void 0 ? void 0 : _b.size) || 0); return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -407477,30 +409039,35 @@ var ts; ts.BuilderState.releaseCache(state); state.program = undefined; } - /** - * Creates a clone of the state - */ - function cloneBuilderProgramState(state) { - var _a; - var newState = ts.BuilderState.clone(state); - newState.semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile && new ts.Map(state.semanticDiagnosticsPerFile); - newState.changedFilesSet = new ts.Set(state.changedFilesSet); - newState.affectedFiles = state.affectedFiles; - newState.affectedFilesIndex = state.affectedFilesIndex; - newState.currentChangedFilePath = state.currentChangedFilePath; - newState.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures && new ts.Map(state.currentAffectedFilesSignatures); - newState.currentAffectedFilesExportedModulesMap = (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clone(); - newState.seenAffectedFiles = state.seenAffectedFiles && new ts.Set(state.seenAffectedFiles); - newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; - newState.semanticDiagnosticsFromOldState = state.semanticDiagnosticsFromOldState && new ts.Set(state.semanticDiagnosticsFromOldState); - newState.program = state.program; - newState.compilerOptions = state.compilerOptions; - newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(); - newState.affectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind); - newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; - newState.seenEmittedFiles = state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles); - newState.programEmitComplete = state.programEmitComplete; - return newState; + function backupBuilderProgramEmitState(state) { + var outFilePath = ts.outFile(state.compilerOptions); + // Only in --out changeFileSet is kept around till emit + ts.Debug.assert(!state.changedFilesSet.size || outFilePath); + return { + affectedFilesPendingEmit: state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(), + affectedFilesPendingEmitKind: state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind), + affectedFilesPendingEmitIndex: state.affectedFilesPendingEmitIndex, + seenEmittedFiles: state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles), + programEmitComplete: state.programEmitComplete, + emitSignatures: state.emitSignatures && new ts.Map(state.emitSignatures), + outSignature: state.outSignature, + latestChangedDtsFile: state.latestChangedDtsFile, + hasChangedEmitSignature: state.hasChangedEmitSignature, + changedFilesSet: outFilePath ? new ts.Set(state.changedFilesSet) : undefined, + }; + } + function restoreBuilderProgramEmitState(state, savedEmitState) { + state.affectedFilesPendingEmit = savedEmitState.affectedFilesPendingEmit; + state.affectedFilesPendingEmitKind = savedEmitState.affectedFilesPendingEmitKind; + state.affectedFilesPendingEmitIndex = savedEmitState.affectedFilesPendingEmitIndex; + state.seenEmittedFiles = savedEmitState.seenEmittedFiles; + state.programEmitComplete = savedEmitState.programEmitComplete; + state.emitSignatures = savedEmitState.emitSignatures; + state.outSignature = savedEmitState.outSignature; + state.latestChangedDtsFile = savedEmitState.latestChangedDtsFile; + state.hasChangedEmitSignature = savedEmitState.hasChangedEmitSignature; + if (savedEmitState.changedFilesSet) + state.changedFilesSet = savedEmitState.changedFilesSet; } /** * Verifies that source file is ok to be used in calls that arent handled by next @@ -407514,8 +409081,8 @@ var ts; * This is to allow the callers to be able to actually remove affected file only when the operation is complete * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained */ - function getNextAffectedFile(state, cancellationToken, computeHash, host) { - var _a; + function getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; while (true) { var affectedFiles = state.affectedFiles; if (affectedFiles) { @@ -407526,7 +409093,7 @@ var ts; if (!seenAffectedFiles.has(affectedFile.resolvedPath)) { // Set the next affected file as seen and remove the cached semantic diagnostics state.affectedFilesIndex = affectedFilesIndex; - handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); return affectedFile; } affectedFilesIndex++; @@ -407535,10 +409102,8 @@ var ts; state.changedFilesSet.delete(state.currentChangedFilePath); state.currentChangedFilePath = undefined; // Commit the changes in file signature - ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); - state.currentAffectedFilesSignatures.clear(); - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); - (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clear(); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); state.affectedFiles = undefined; } // Get next changed file @@ -407556,12 +409121,7 @@ var ts; return program; } // Get next batch of affected files - if (!state.currentAffectedFilesSignatures) - state.currentAffectedFilesSignatures = new ts.Map(); - if (state.exportedModulesMap) { - state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap()); - } - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = ts.BuilderState.getFilesAffectedByWithOldState(state, program, nextKey.value, cancellationToken, computeHash, getCanonicalFileName); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; if (!state.seenAffectedFiles) @@ -407612,8 +409172,7 @@ var ts; * Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change */ - function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); // If affected files is everything except default library, then nothing more to do if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { @@ -407621,19 +409180,18 @@ var ts; // When a change affects the global scope, all files are considered to be affected without updating their signature // That means when affected file is handled, its signature can be out of date // To avoid this, ensure that we update the signature for any affected file in this scenario. - ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); + ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, cancellationToken, computeHash, getCanonicalFileName); return; } - ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: ".concat(affectedFile.fileName)); if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) return; - handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); } /** * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled, * Also we need to make sure signature is updated for these files */ - function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, host) { + function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, path); if (!state.changedFilesSet.has(path)) { var program = ts.Debug.checkDefined(state.program); @@ -407644,7 +409202,7 @@ var ts; // This ensures that we dont later during incremental builds considering wrong signature. // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build // But we avoid expensive full shape computation, as using file version as shape is enough for correctness. - ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap, !host.disableUseFileVersionAsSignature); + ts.BuilderState.updateShapeSignature(state, program, sourceFile, cancellationToken, computeHash, getCanonicalFileName, !host.disableUseFileVersionAsSignature); // If not dts emit, nothing more to do if (ts.getEmitDeclarations(state.compilerOptions)) { addToAffectedFilesPendingEmit(state, path, 0 /* BuilderFileEmit.DtsOnly */); @@ -407665,41 +409223,25 @@ var ts; return !state.semanticDiagnosticsFromOldState.size; } function isChangedSignature(state, path) { - var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path); - var oldSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; + var oldSignature = ts.Debug.checkDefined(state.oldSignatures).get(path) || undefined; + var newSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; return newSignature !== oldSignature; } - function forEachKeyOfExportedModulesMap(state, filePath, fn) { - // Go through exported modules from cache first - var keys = state.currentAffectedFilesExportedModulesMap.getKeys(filePath); - var result = keys && ts.forEachKey(keys, fn); - if (result) - return result; - // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected - keys = state.exportedModulesMap.getKeys(filePath); - return keys && ts.forEachKey(keys, function (exportedFromPath) { - var _a; - // If the cache had an updated value, skip - return !state.currentAffectedFilesExportedModulesMap.hasKey(exportedFromPath) && - !((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(exportedFromPath)) ? - fn(exportedFromPath) : - undefined; - }); - } - function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host) { var _a; if (!((_a = state.fileInfos.get(filePath)) === null || _a === void 0 ? void 0 : _a.affectsGlobalScope)) return false; // Every file needs to be handled ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, state.program, /*firstSourceFile*/ undefined) - .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, host); }); + .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, getCanonicalFileName, host); }); removeDiagnosticsOfLibraryFiles(state); return true; } /** * Iterate on referencing modules that export entities from affected file and delete diagnostics and add pending emit */ - function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a; // If there was change in signature (dts output) for the changed file, // then only we need to handle pending file emit if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) @@ -407716,9 +409258,9 @@ var ts; var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { seenFileNamesMap.set(currentPath, true); - if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host)) return; - handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, host); + handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host); if (isChangedSignature(state, currentPath)) { var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath); queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath)); @@ -407726,16 +409268,15 @@ var ts; } } } - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); var seenFileAndExportsOfFile = new ts.Set(); // Go through exported modules from cache first // If exported modules has path, all files referencing file exported from are affected - forEachKeyOfExportedModulesMap(state, affectedFile.resolvedPath, function (exportedFromPath) { - if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, host)) + (_a = state.exportedModulesMap.getKeys(affectedFile.resolvedPath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; var references = state.referencedMap.getKeys(exportedFromPath); return references && ts.forEachKey(references, function (filePath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); }); } @@ -407743,23 +409284,22 @@ var ts; * handle dts and semantic diagnostics on file and iterate on anything that exports this file * return true when all work is done and we can exit handling dts emit and semantic diagnostics */ - function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; if (!ts.tryAddToSet(seenFileAndExportsOfFile, filePath)) return undefined; - if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; - handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, host); - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host); // If exported modules has path, all files referencing file exported from are affected - forEachKeyOfExportedModulesMap(state, filePath, function (exportedFromPath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + (_a = state.exportedModulesMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); // Remove diagnostics of files that import this file (without going to exports of referencing files) - (_a = state.referencedMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (referencingFilePath) { + (_b = state.referencedMap.getKeys(filePath)) === null || _b === void 0 ? void 0 : _b.forEach(function (referencingFilePath) { return !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file handleDtsMayChangeOf(// Dont add to seen since this is not yet done with the export removal - state, referencingFilePath, cancellationToken, computeHash, host); + state, referencingFilePath, cancellationToken, computeHash, getCanonicalFileName, host); }); return undefined; } @@ -407777,12 +409317,13 @@ var ts; } else { state.seenAffectedFiles.add(affected.resolvedPath); + // Change in changeSet/affectedFilesPendingEmit, buildInfo needs to be emitted + state.buildInfoEmitPending = true; if (emitKind !== undefined) { (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map())).set(affected.resolvedPath, emitKind); } if (isPendingEmit) { state.affectedFilesPendingEmitIndex++; - state.buildInfoEmitPending = true; } else { state.affectedFilesIndex++; @@ -407830,25 +409371,62 @@ var ts; } return ts.filterSemanticDiagnostics(diagnostics, state.compilerOptions); } + function isProgramBundleEmitBuildInfo(info) { + return !!ts.outFile(info.options || {}); + } + ts.isProgramBundleEmitBuildInfo = isProgramBundleEmitBuildInfo; /** * Gets the program information to be emitted in buildInfo so that we can use it to create new program */ function getProgramBuildInfo(state, getCanonicalFileName) { - if (ts.outFile(state.compilerOptions)) - return undefined; + var outFilePath = ts.outFile(state.compilerOptions); + if (outFilePath && !state.compilerOptions.composite) + return; var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); + // Convert the file name to Path here if we set the fileName instead to optimize multiple d.ts file emits and having to compute Canonical path + var latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : undefined; + if (outFilePath) { + var fileNames_1 = []; + var fileInfos_1 = []; + state.program.getRootFileNames().forEach(function (f) { + var sourceFile = state.program.getSourceFile(f); + if (!sourceFile) + return; + fileNames_1.push(relativeToBuildInfo(sourceFile.resolvedPath)); + fileInfos_1.push(sourceFile.version); + }); + var result_15 = { + fileNames: fileNames_1, + fileInfos: fileInfos_1, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsBundleEmitBuildInfo"), + outSignature: state.outSignature, + latestChangedDtsFile: latestChangedDtsFile, + }; + return result_15; + } var fileNames = []; var fileNameToFileId = new ts.Map(); var fileIdsList; var fileNamesToFileIdListId; + var emitSignatures; var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) { + var _b, _c; var key = _a[0], value = _a[1]; // Ensure fileId var fileId = toFileId(key); ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); - var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + var oldSignature = (_b = state.oldSignatures) === null || _b === void 0 ? void 0 : _b.get(key); + var actualSignature = oldSignature !== undefined ? oldSignature || undefined : value.signature; + if (state.compilerOptions.composite) { + var file = state.program.getSourceFileByPath(key); + if (!ts.isJsonSourceFile(file) && ts.sourceFileMayBeEmitted(file, state.program)) { + var emitSignature = (_c = state.emitSignatures) === null || _c === void 0 ? void 0 : _c.get(key); + if (emitSignature !== actualSignature) { + (emitSignatures || (emitSignatures = [])).push(emitSignature === undefined ? fileId : [fileId, emitSignature]); + } + } + } return value.version === actualSignature ? value.affectsGlobalScope || value.impliedFormat ? // If file version is same as signature, dont serialize signature @@ -407856,11 +409434,11 @@ var ts; // If file info only contains version and signature and both are same we can just write string value.version : actualSignature !== undefined ? // If signature is not same as version, encode signature in the fileInfo - signature === undefined ? + oldSignature === undefined ? // If we havent computed signature, use fileInfo as is value : // Serialize fileInfo with new updated signature - { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : + { version: value.version, signature: actualSignature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : // Signature of the FileInfo is undefined, serialize it as false { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat }; }); @@ -407875,17 +409453,13 @@ var ts; if (state.exportedModulesMap) { exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) { var _a; - if (state.currentAffectedFilesExportedModulesMap) { - if ((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(key)) { - return undefined; - } - var newValue = state.currentAffectedFilesExportedModulesMap.getValues(key); - if (newValue) { - return [toFileId(key), toFileIdListId(newValue)]; - } - } + var oldValue = (_a = state.oldExportedModulesMap) === null || _a === void 0 ? void 0 : _a.get(key); // Not in temporary cache, use existing value - return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue === undefined) + return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue) + return [toFileId(key), toFileIdListId(oldValue)]; + return undefined; }); } var semanticDiagnosticsPerFile; @@ -407896,9 +409470,7 @@ var ts; (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [ toFileId(key), - state.hasReusableDiagnostic ? - value : - convertToReusableDiagnostics(value, relativeToBuildInfo) + convertToReusableDiagnostics(value, relativeToBuildInfo) ] : toFileId(key)); } @@ -407913,16 +409485,27 @@ var ts; } } } - return { + var changeFileSet; + if (state.changedFilesSet.size) { + for (var _d = 0, _e = ts.arrayFrom(state.changedFilesSet.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { + var path = _e[_d]; + (changeFileSet || (changeFileSet = [])).push(toFileId(path)); + } + } + var result = { fileNames: fileNames, fileInfos: fileInfos, - options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsMultiFileEmitBuildInfo"), fileIdsList: fileIdsList, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, semanticDiagnosticsPerFile: semanticDiagnosticsPerFile, affectedFilesPendingEmit: affectedFilesPendingEmit, + changeFileSet: changeFileSet, + emitSignatures: emitSignatures, + latestChangedDtsFile: latestChangedDtsFile, }; + return result; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory)); } @@ -407947,24 +409530,21 @@ var ts; } return fileIdListId; } - } - function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { - var result; - var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { - var name = _a[_i]; - var optionKey = name.toLowerCase(); - var optionInfo = optionsNameMap.get(optionKey); - if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || - // We need to store `strict`, even though it won't be examined directly, so that the - // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly from the buildinfo - optionKey === "strict" || - // We need to store these to determine whether `lib` files need to be rechecked. - optionKey === "skiplibcheck" || optionKey === "skipdefaultlibcheck") { - (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); + /** + * @param optionKey key of CommandLineOption to use to determine if the option should be serialized in tsbuildinfo + */ + function convertToProgramBuildInfoCompilerOptions(options, optionKey) { + var result; + var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; + for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var name = _a[_i]; + var optionInfo = optionsNameMap.get(name.toLowerCase()); + if (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo[optionKey]) { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfoEnsuringAbsolutePath); + } } + return result; } - return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { if (option) { @@ -408038,6 +409618,41 @@ var ts; return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; } ts.getBuilderCreationParameters = getBuilderCreationParameters; + function getTextHandlingSourceMapForSignature(text, data) { + return (data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text; + } + function computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data) { + var _a; + text = getTextHandlingSourceMapForSignature(text, data); + var sourceFileDirectory; + if ((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length) { + text += data.diagnostics.map(function (diagnostic) { + return "".concat(locationInfo(diagnostic)).concat(ts.DiagnosticCategory[diagnostic.category]).concat(diagnostic.code, ": ").concat(flattenDiagnosticMessageText(diagnostic.messageText)); + }).join("\n"); + } + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(text); + function flattenDiagnosticMessageText(diagnostic) { + return ts.isString(diagnostic) ? + diagnostic : + diagnostic === undefined ? + "" : + !diagnostic.next ? + diagnostic.messageText : + diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText).join("\n"); + } + function locationInfo(diagnostic) { + if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) + return "(".concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + if (sourceFileDirectory === undefined) + sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath); + return "".concat(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceFileDirectory, diagnostic.file.resolvedPath, getCanonicalFileName)), "(").concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + } + } + ts.computeSignatureWithDiagnostics = computeSignatureWithDiagnostics; + function computeSignature(text, computeHash, data) { + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data)); + } + ts.computeSignature = computeSignature; function createBuilderProgram(kind, _a) { var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; // Return same program if underlying program doesnt change @@ -408056,7 +409671,6 @@ var ts; */ var computeHash = ts.maybeBind(host, host.createHash); var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); - var backupState; newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); }; // To ensure that we arent storing any references to old program or new program without state newProgram = undefined; // TODO: GH#18217 @@ -408065,21 +409679,13 @@ var ts; var getState = function () { return state; }; var builderProgram = createRedirectedBuilderProgram(getState, configFileParsingDiagnostics); builderProgram.getState = getState; - builderProgram.backupState = function () { - ts.Debug.assert(backupState === undefined); - backupState = cloneBuilderProgramState(state); - }; - builderProgram.restoreState = function () { - state = ts.Debug.checkDefined(backupState); - backupState = undefined; - }; + builderProgram.saveEmitState = function () { return backupBuilderProgramEmitState(state); }; + builderProgram.restoreEmitState = function (saved) { return restoreBuilderProgramEmitState(state, saved); }; + builderProgram.hasChangedEmitSignature = function () { return !!state.hasChangedEmitSignature; }; builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); }; builderProgram.getSemanticDiagnostics = getSemanticDiagnostics; builderProgram.emit = emit; - builderProgram.releaseProgram = function () { - releaseCache(state); - backupState = undefined; - }; + builderProgram.releaseProgram = function () { return releaseCache(state); }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; } @@ -408106,7 +409712,7 @@ var ts; * in that order would be used to write the files */ function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); var emitKind = 1 /* BuilderFileEmit.Full */; var isPendingEmitFile = false; if (!affected) { @@ -408137,34 +409743,68 @@ var ts; return toAffectedFileEmitResult(state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file - ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, affected !== state.program && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles || emitKind === 0 /* BuilderFileEmit.DtsOnly */, customTransformers), affected, emitKind, isPendingEmitFile); } - function getWriteFileUpdatingSignatureCallback(writeFile) { + function getWriteFileCallback(writeFile, customTransformers) { return function (fileName, text, writeByteOrderMark, onError, sourceFiles, data) { - var _a; + var _a, _b, _c, _d, _e, _f, _g; if (ts.isDeclarationFileName(fileName)) { - ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); - var file = sourceFiles[0]; - var info = state.fileInfos.get(file.resolvedPath); - var signature = ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.get(file.resolvedPath)) || info.signature; - if (signature === file.version) { - var newSignature = (computeHash || ts.generateDjb2Hash)((data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text); - if (newSignature !== file.version) { // Update it - if (host.storeFilesChangingSignatureDuringEmit) - (state.filesChangingSignature || (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); - if (state.exportedModulesMap) - ts.BuilderState.updateExportedModules(file, file.exportedModulesFromDeclarationEmit, state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap())); - if (state.affectedFiles && state.affectedFilesIndex < state.affectedFiles.length) { - state.currentAffectedFilesSignatures.set(file.resolvedPath, newSignature); - } - else { - info.signature = newSignature; - if (state.exportedModulesMap) - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); + if (!ts.outFile(state.compilerOptions)) { + ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); + var emitSignature = void 0; + if (!customTransformers) { + var file = sourceFiles[0]; + var info = state.fileInfos.get(file.resolvedPath); + if (info.signature === file.version) { + var signature = computeSignatureWithDiagnostics(file, text, computeHash, getCanonicalFileName, data); + // With d.ts diagnostics they are also part of the signature so emitSignature will be different from it since its just hash of d.ts + if (!((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length)) + emitSignature = signature; + if (signature !== file.version) { // Update it + if (host.storeFilesChangingSignatureDuringEmit) + ((_b = state.filesChangingSignature) !== null && _b !== void 0 ? _b : (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); + if (state.exportedModulesMap) + ts.BuilderState.updateExportedModules(state, file, file.exportedModulesFromDeclarationEmit); + if (state.affectedFiles) { + // Keep old signature so we know what to undo if cancellation happens + var existing = (_c = state.oldSignatures) === null || _c === void 0 ? void 0 : _c.get(file.resolvedPath); + if (existing === undefined) + ((_d = state.oldSignatures) !== null && _d !== void 0 ? _d : (state.oldSignatures = new ts.Map())).set(file.resolvedPath, info.signature || false); + info.signature = signature; + } + else { + // These are directly commited + info.signature = signature; + (_e = state.oldExportedModulesMap) === null || _e === void 0 ? void 0 : _e.clear(); + } + } } } + // Store d.ts emit hash so later can be compared to check if d.ts has changed. + // Currently we do this only for composite projects since these are the only projects that can be referenced by other projects + // and would need their d.ts change time in --build mode + if (state.compilerOptions.composite) { + var filePath = sourceFiles[0].resolvedPath; + var oldSignature = (_f = state.emitSignatures) === null || _f === void 0 ? void 0 : _f.get(filePath); + emitSignature !== null && emitSignature !== void 0 ? emitSignature : (emitSignature = computeSignature(text, computeHash, data)); + // Dont write dts files if they didn't change + if (emitSignature === oldSignature) + return; + ((_g = state.emitSignatures) !== null && _g !== void 0 ? _g : (state.emitSignatures = new ts.Map())).set(filePath, emitSignature); + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; + } + } + else if (state.compilerOptions.composite) { + var newSignature = computeSignature(text, computeHash, data); + // Dont write dts files if they didn't change + if (newSignature === state.outSignature) + return; + state.outSignature = newSignature; + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; } } if (writeFile) @@ -408230,8 +409870,8 @@ var ts; } } } - return ts.Debug.checkDefined(state.program).emit(targetSourceFile, !ts.outFile(state.compilerOptions) && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + return ts.Debug.checkDefined(state.program).emit(targetSourceFile, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers); } /** @@ -408240,7 +409880,7 @@ var ts; */ function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { while (true) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); if (!affected) { // Done return undefined; @@ -408320,29 +409960,59 @@ var ts; { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat }; } ts.toBuilderStateFileInfo = toBuilderStateFileInfo; - function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { - var _a; + function createBuilderProgramUsingProgramBuildInfo(program, buildInfoPath, host) { + var _a, _b, _c, _d; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var filePaths = program.fileNames.map(toPath); - var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); - var fileInfos = new ts.Map(); - program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); - var state = { - fileInfos: fileInfos, - compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, - referencedMap: toManyToManyPathMap(program.referencedMap), - exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), - hasReusableDiagnostic: true, - affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), - affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, - }; + var state; + var filePaths; + var filePathsSetList; + var latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : undefined; + if (isProgramBundleEmitBuildInfo(program)) { + state = { + fileInfos: new ts.Map(), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + latestChangedDtsFile: latestChangedDtsFile, + outSignature: program.outSignature, + }; + } + else { + filePaths = (_a = program.fileNames) === null || _a === void 0 ? void 0 : _a.map(toPath); + filePathsSetList = (_b = program.fileIdsList) === null || _b === void 0 ? void 0 : _b.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); + var fileInfos_2 = new ts.Map(); + var emitSignatures_1 = ((_c = program.options) === null || _c === void 0 ? void 0 : _c.composite) && !ts.outFile(program.options) ? new ts.Map() : undefined; + program.fileInfos.forEach(function (fileInfo, index) { + var path = toFilePath(index + 1); + var stateFileInfo = toBuilderStateFileInfo(fileInfo); + fileInfos_2.set(path, stateFileInfo); + if (emitSignatures_1 && stateFileInfo.signature) + emitSignatures_1.set(path, stateFileInfo.signature); + }); + (_d = program.emitSignatures) === null || _d === void 0 ? void 0 : _d.forEach(function (value) { + if (ts.isNumber(value)) + emitSignatures_1.delete(toFilePath(value)); + else + emitSignatures_1.set(toFilePath(value[0]), value[1]); + }); + state = { + fileInfos: fileInfos_2, + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toManyToManyPathMap(program.referencedMap), + exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), + hasReusableDiagnostic: true, + affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), + affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, + changedFilesSet: new ts.Set(ts.map(program.changeFileSet, toFilePath)), + latestChangedDtsFile: latestChangedDtsFile, + emitSignatures: (emitSignatures_1 === null || emitSignatures_1 === void 0 ? void 0 : emitSignatures_1.size) ? emitSignatures_1 : undefined, + }; + } return { getState: function () { return state; }, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: ts.notImplemented, getProgramOrUndefined: ts.returnUndefined, releaseProgram: ts.noop, @@ -408362,6 +410032,7 @@ var ts; getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented, emitBuildInfo: ts.notImplemented, close: ts.noop, + hasChangedEmitSignature: ts.returnFalse, }; function toPath(path) { return ts.toPath(path, buildInfoDirectory, getCanonicalFileName); @@ -408387,12 +410058,24 @@ var ts; return map; } } - ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; + ts.createBuilderProgramUsingProgramBuildInfo = createBuilderProgramUsingProgramBuildInfo; + function getBuildInfoFileVersionMap(program, buildInfoPath, host) { + var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var fileInfos = new ts.Map(); + program.fileInfos.forEach(function (fileInfo, index) { + var path = ts.toPath(program.fileNames[index], buildInfoDirectory, getCanonicalFileName); + var version = ts.isString(fileInfo) ? fileInfo : fileInfo.version; // eslint-disable-line @typescript-eslint/no-unnecessary-type-assertion + fileInfos.set(path, version); + }); + return fileInfos; + } + ts.getBuildInfoFileVersionMap = getBuildInfoFileVersionMap; function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) { return { getState: ts.notImplemented, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: getProgram, getProgramOrUndefined: function () { return getState().program; }, releaseProgram: function () { return getState().program = undefined; }, @@ -408452,7 +410135,7 @@ var ts; * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" * @param dirPath */ - function canWatchDirectory(dirPath) { + function canWatchDirectoryOrFile(dirPath) { var rootLength = ts.getRootLength(dirPath); if (dirPath.length === rootLength) { // Ignore "/", "c:/" @@ -408489,15 +410172,19 @@ var ts; } return true; } - ts.canWatchDirectory = canWatchDirectory; + ts.canWatchDirectoryOrFile = canWatchDirectoryOrFile; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var nonRelativeExternalModuleResolutions = ts.createMultiMap(); var resolutionsWithFailedLookups = []; + var resolutionsWithOnlyAffectingLocations = []; var resolvedFileToResolution = ts.createMultiMap(); + var impliedFormatPackageJsons = new ts.Map(); var hasChangedAutomaticTypeDirectiveNames = false; + var affectingPathChecksForFile; + var affectingPathChecks; var failedLookupChecks; var startsWithPathChecks; var isInDirectoryChecks; @@ -408524,6 +410211,7 @@ var ts; var failedLookupDefaultExtensions = [".ts" /* Extension.Ts */, ".tsx" /* Extension.Tsx */, ".js" /* Extension.Js */, ".jsx" /* Extension.Jsx */, ".json" /* Extension.Json */]; var customFailedLookupPaths = new ts.Map(); var directoryWatchesOfFailedLookups = new ts.Map(); + var fileWatchesOfAffectingLocations = new ts.Map(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0; @@ -408535,7 +410223,7 @@ var ts; finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) - startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + startCachingPerDirectoryResolution: startCachingPerDirectoryResolution, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, @@ -408566,6 +410254,7 @@ var ts; } function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + ts.clearMap(fileWatchesOfAffectingLocations, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); @@ -408573,12 +410262,15 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; + resolutionsWithOnlyAffectingLocations.length = 0; failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; - // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update - // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) - clearPerDirectoryResolutions(); + affectingPathChecks = undefined; + affectingPathChecksForFile = undefined; + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); + impliedFormatPackageJsons.clear(); hasChangedAutomaticTypeDirectiveNames = false; } function startRecordingFilesWithChangedResolutions() { @@ -408610,25 +410302,60 @@ var ts; return function (path) { return (!!collected && collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } - function clearPerDirectoryResolutions() { - moduleResolutionCache.clear(); - typeReferenceDirectiveResolutionCache.clear(); + function startCachingPerDirectoryResolution() { + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } - function finishCachingPerDirectoryResolution() { + function finishCachingPerDirectoryResolution(newProgram, oldProgram) { filesWithInvalidatedNonRelativeUnresolvedImports = undefined; - clearPerDirectoryResolutions(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); + // Update file watches + if (newProgram !== oldProgram) { + newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFiles().forEach(function (newFile) { + var _a, _b, _c; + var expected = ts.isExternalOrCommonJsModule(newFile) ? (_b = (_a = newFile.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0 : 0; + var existing = (_c = impliedFormatPackageJsons.get(newFile.path)) !== null && _c !== void 0 ? _c : ts.emptyArray; + for (var i = existing.length; i < expected; i++) { + createFileWatcherOfAffectingLocation(newFile.packageJsonLocations[i], /*forResolution*/ false); + } + if (existing.length > expected) { + for (var i = expected; i < existing.length; i++) { + fileWatchesOfAffectingLocations.get(existing[i]).files--; + } + } + if (expected) + impliedFormatPackageJsons.set(newFile.path, newFile.packageJsonLocations); + else + impliedFormatPackageJsons.delete(newFile.path); + }); + impliedFormatPackageJsons.forEach(function (existing, path) { + if (!(newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFileByPath(path))) { + existing.forEach(function (location) { return fileWatchesOfAffectingLocations.get(location).files--; }); + impliedFormatPackageJsons.delete(path); + } + }); + } directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); + fileWatchesOfAffectingLocations.forEach(function (watcher, path) { + if (watcher.files === 0 && watcher.resolutions === 0) { + fileWatchesOfAffectingLocations.delete(path); + watcher.watcher.close(); + } + }); hasChangedAutomaticTypeDirectiveNames = false; } function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference, _containingSourceFile, mode) { - var _a; + var _a, _b; var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { @@ -408639,11 +410366,12 @@ var ts; if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results - var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _c = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _c.resolvedModule, failedLookupLocations = _c.failedLookupLocations, affectingLocations = _c.affectingLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = primaryResult.affectingLocations).push.apply(_b, affectingLocations); return primaryResult; } } @@ -408848,7 +410576,7 @@ var ts; } // If the directory is node_modules use it to watch, always watch it recursively if (ts.isNodeModulesDirectory(dirPath)) { - return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; + return canWatchDirectoryOrFile(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; // Use some ancestor of the root directory @@ -408866,7 +410594,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; + return canWatchDirectoryOrFile(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -408894,10 +410622,11 @@ var ts; } function watchFailedLookupLocationOfResolution(resolution) { ts.Debug.assert(!!resolution.refCount); - var failedLookupLocations = resolution.failedLookupLocations; - if (!failedLookupLocations.length) + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (!failedLookupLocations.length && !affectingLocations.length) return; - resolutionsWithFailedLookups.push(resolution); + if (failedLookupLocations.length) + resolutionsWithFailedLookups.push(resolution); var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; @@ -408924,12 +410653,87 @@ var ts; // This is always non recursive setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 } + watchAffectingLocationsOfResolution(resolution, !failedLookupLocations.length); + } + function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { + ts.Debug.assert(!!resolution.refCount); + var affectingLocations = resolution.affectingLocations; + if (!affectingLocations.length) + return; + if (addToResolutionsWithOnlyAffectingLocations) + resolutionsWithOnlyAffectingLocations.push(resolution); + // Watch package json + for (var _i = 0, affectingLocations_1 = affectingLocations; _i < affectingLocations_1.length; _i++) { + var affectingLocation = affectingLocations_1[_i]; + createFileWatcherOfAffectingLocation(affectingLocation, /*forResolution*/ true); + } + } + function createFileWatcherOfAffectingLocation(affectingLocation, forResolution) { + var fileWatcher = fileWatchesOfAffectingLocations.get(affectingLocation); + if (fileWatcher) { + if (forResolution) + fileWatcher.resolutions++; + else + fileWatcher.files++; + return; + } + var locationToWatch = affectingLocation; + if (resolutionHost.realpath) { + locationToWatch = resolutionHost.realpath(affectingLocation); + if (affectingLocation !== locationToWatch) { + var fileWatcher_1 = fileWatchesOfAffectingLocations.get(locationToWatch); + if (fileWatcher_1) { + if (forResolution) + fileWatcher_1.resolutions++; + else + fileWatcher_1.files++; + fileWatcher_1.paths.add(affectingLocation); + fileWatchesOfAffectingLocations.set(affectingLocation, fileWatcher_1); + return; + } + } + } + var paths = new ts.Set(); + paths.add(locationToWatch); + var actualWatcher = canWatchDirectoryOrFile(resolutionHost.toPath(locationToWatch)) ? + resolutionHost.watchAffectingFileLocation(locationToWatch, function (fileName, eventKind) { + cachedDirectoryStructureHost === null || cachedDirectoryStructureHost === void 0 ? void 0 : cachedDirectoryStructureHost.addOrDeleteFile(fileName, resolutionHost.toPath(locationToWatch), eventKind); + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + paths.forEach(function (path) { + if (watcher.resolutions) + (affectingPathChecks !== null && affectingPathChecks !== void 0 ? affectingPathChecks : (affectingPathChecks = new ts.Set())).add(path); + if (watcher.files) + (affectingPathChecksForFile !== null && affectingPathChecksForFile !== void 0 ? affectingPathChecksForFile : (affectingPathChecksForFile = new ts.Set())).add(path); + packageJsonMap === null || packageJsonMap === void 0 ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path)); + }); + resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); + }) : ts.noopFileWatcher; + var watcher = { + watcher: actualWatcher !== ts.noopFileWatcher ? { + close: function () { + actualWatcher.close(); + // Ensure when watching symlinked package.json, we can close the actual file watcher only once + actualWatcher = ts.noopFileWatcher; + } + } : actualWatcher, + resolutions: forResolution ? 1 : 0, + files: forResolution ? 0 : 1, + paths: paths, + }; + fileWatchesOfAffectingLocations.set(locationToWatch, watcher); + if (affectingLocation !== locationToWatch) { + fileWatchesOfAffectingLocations.set(affectingLocation, watcher); + paths.add(affectingLocation); + } } function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { var program = resolutionHost.getCurrentProgram(); if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) { resolutions.forEach(watchFailedLookupLocationOfResolution); } + else { + resolutions.forEach(function (resolution) { return watchAffectingLocationsOfResolution(resolution, /*addToResolutionWithOnlyAffectingLocations*/ true); }); + } } function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); @@ -408951,38 +410755,44 @@ var ts; if (resolved && resolved.resolvedFileName) { resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution); } - if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { - // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups - return; - } - var failedLookupLocations = resolution.failedLookupLocations; - var removeAtRoot = false; - for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { - var failedLookupLocation = failedLookupLocations_2[_i]; - var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); - if (toWatch) { - var dirPath = toWatch.dirPath; - var refCount = customFailedLookupPaths.get(failedLookupLocationPath); - if (refCount) { - if (refCount === 1) { - customFailedLookupPaths.delete(failedLookupLocationPath); + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; } else { - ts.Debug.assert(refCount > 1); - customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + removeDirectoryWatcher(dirPath); } } - if (dirPath === rootPath) { - removeAtRoot = true; - } - else { - removeDirectoryWatcher(dirPath); - } + } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); } } - if (removeAtRoot) { - removeDirectoryWatcher(rootPath); + else if (affectingLocations.length) { + ts.unorderedRemoveItem(resolutionsWithOnlyAffectingLocations, resolution); + } + for (var _a = 0, affectingLocations_2 = affectingLocations; _a < affectingLocations_2.length; _a++) { + var affectingLocation = affectingLocations_2[_a]; + var watcher = fileWatchesOfAffectingLocations.get(affectingLocation); + watcher.resolutions--; } } function removeDirectoryWatcher(dirPath) { @@ -409036,7 +410846,7 @@ var ts; resolution.isInvalidated = invalidated = true; for (var _a = 0, _b = ts.Debug.checkDefined(resolution.files); _a < _b.length; _a++) { var containingFilePath = _b[_a]; - (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); // When its a file with inferred types resolution, invalidate type reference directive resolution hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || ts.endsWith(containingFilePath, ts.inferredTypesContainingFile); } @@ -409061,7 +410871,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = new ts.Set())).add(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -409079,7 +410889,7 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { @@ -409091,7 +410901,7 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); // If the invalidated file is from a node_modules package, invalidate everything else // in the package since we might not get notifications for other files in the package. // This hardens our logic against unreliable file watchers. @@ -409103,22 +410913,46 @@ var ts; resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { - return false; + var _a; + var invalidated = false; + if (affectingPathChecksForFile) { + (_a = resolutionHost.getCurrentProgram()) === null || _a === void 0 ? void 0 : _a.getSourceFiles().forEach(function (f) { + if (ts.some(f.packageJsonLocations, function (location) { return affectingPathChecksForFile.has(location); })) { + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(f.path); + invalidated = true; + } + }); + affectingPathChecksForFile = undefined; + } + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks && !affectingPathChecks) { + return invalidated; + } + invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated; + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { + packageJsonMap.forEach(function (_value, path) { return isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : undefined; }); } - var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; + invalidated = invalidateResolutions(resolutionsWithOnlyAffectingLocations, canInvalidatedFailedLookupResolutionWithAffectingLocation) || invalidated; + affectingPathChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { - return resolution.failedLookupLocations.some(function (location) { - var locationPath = resolutionHost.toPath(location); - return ts.contains(failedLookupChecks, locationPath) || - ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || - (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); })); - }); + if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution)) + return true; + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) + return false; + return resolution.failedLookupLocations.some(function (location) { return isInvalidatedFailedLookup(resolutionHost.toPath(location)); }); + } + function isInvalidatedFailedLookup(locationPath) { + return (failedLookupChecks === null || failedLookupChecks === void 0 ? void 0 : failedLookupChecks.has(locationPath)) || + ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || + ts.firstDefinedIterator((isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath) ? true : undefined; }); + } + function canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution) { + return !!affectingPathChecks && resolution.affectingLocations.some(function (location) { return affectingPathChecks.has(location); }); } function closeTypeRootsWatch() { ts.clearMap(typeRootsWatches, ts.closeFileWatcher); @@ -409184,7 +411018,7 @@ var ts; function directoryExistsForTypeRootWatch(nodeTypesDirectory) { var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); var dirPath = resolutionHost.toPath(dir); - return dirPath === rootPath || canWatchDirectory(dirPath); + return dirPath === rootPath || canWatchDirectoryOrFile(dirPath); } } ts.createResolutionCache = createResolutionCache; @@ -409295,7 +411129,7 @@ var ts; var info = getInfo(importingSourceFileName, host); var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host, userPreferences, options); return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ undefined, options.overrideImportMode); }) || - getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences); + getLocalModuleSpecifier(toFileName, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); } function tryGetModuleSpecifiersFromCache(moduleSymbol, importingSourceFile, host, userPreferences, options) { if (options === void 0) { options = {}; } @@ -409378,7 +411212,7 @@ var ts; return nodeModulesSpecifiers; } if (!specifier && !modulePath.isRedirect) { - var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, preferences); + var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); if (ts.pathIsBareSpecifier(local)) { pathsSpecifiers = ts.append(pathsSpecifiers, local); } @@ -409406,7 +411240,7 @@ var ts; var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); return { getCanonicalFileName: getCanonicalFileName, importingSourceFileName: importingSourceFileName, sourceDirectory: sourceDirectory }; } - function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, _a) { + function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, _a) { var ending = _a.ending, relativePreference = _a.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var sourceDirectory = info.sourceDirectory, getCanonicalFileName = info.getCanonicalFileName; @@ -409420,9 +411254,8 @@ var ts; if (!relativeToBaseUrl) { return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); - var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - var nonRelative = fromPaths === undefined && baseUrl !== undefined ? importRelativeToBaseUrl : fromPaths; + var fromPaths = paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, getAllowedEndings(ending, compilerOptions, importMode), host, compilerOptions); + var nonRelative = fromPaths === undefined && baseUrl !== undefined ? removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) : fromPaths; if (!nonRelative) { return relativePath; } @@ -409508,9 +411341,9 @@ var ts; if (!preferSymlinks) { // Symlinks inside ignored paths are already filtered out of the symlink cache, // so we only need to remove them from the realpath filenames. - var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_16 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_16) + return result_16; } var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); @@ -409530,10 +411363,10 @@ var ts; for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { var symlinkDirectory = symlinkDirectories_1[_i]; var option = ts.resolvePath(symlinkDirectory, relative); - var result_16 = cb(option, target === referenceRedirect); + var result_17 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths - if (result_16) - return result_16; + if (result_17) + return result_17; } }); }); @@ -409575,7 +411408,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_32 = function (directory) { + var _loop_35 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -409599,9 +411432,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { - var state_10 = _loop_32(directory); + var state_11 = _loop_35(directory); directory = out_directory_1; - if (state_10 === "break") + if (state_11 === "break") break; } if (allFileNames.size) { @@ -409657,28 +411490,102 @@ var ts; return ambientModuleDeclare.name.text; } } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + function getAllowedEndings(preferredEnding, compilerOptions, importMode) { + if (ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && importMode === ts.ModuleKind.ESNext) { + return [2 /* Ending.JsExtension */]; + } + switch (preferredEnding) { + case 2 /* Ending.JsExtension */: return [2 /* Ending.JsExtension */, 0 /* Ending.Minimal */, 1 /* Ending.Index */]; + case 1 /* Ending.Index */: return [1 /* Ending.Index */, 0 /* Ending.Minimal */, 2 /* Ending.JsExtension */]; + case 0 /* Ending.Minimal */: return [0 /* Ending.Minimal */, 1 /* Ending.Index */, 2 /* Ending.JsExtension */]; + default: ts.Debug.assertNever(preferredEnding); + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var _loop_36 = function (patternText_1) { + var pattern = ts.normalizePath(patternText_1); var indexOfStar = pattern.indexOf("*"); + // In module resolution, if `pattern` itself has an extension, a file with that extension is looked up directly, + // meaning a '.ts' or '.d.ts' extension is allowed to resolve. This is distinct from the case where a '*' substitution + // causes a module specifier to have an extension, i.e. the extension comes from the module specifier in a JS/TS file + // and matches the '*'. For example: + // + // Module Specifier | Path Mapping (key: [pattern]) | Interpolation | Resolution Action + // ---------------------->------------------------------->--------------------->--------------------------------------------------------------- + // import "@app/foo" -> "@app/*": ["./src/app/*.ts"] -> "./src/app/foo.ts" -> tryFile("./src/app/foo.ts") || [continue resolution algorithm] + // import "@app/foo.ts" -> "@app/*": ["./src/app/*"] -> "./src/app/foo.ts" -> [continue resolution algorithm] + // + // (https://github.com/microsoft/TypeScript/blob/ad4ded80e1d58f0bf36ac16bea71bc10d9f09895/src/compiler/moduleNameResolver.ts#L2509-L2516) + // + // The interpolation produced by both scenarios is identical, but only in the former, where the extension is encoded in + // the path mapping rather than in the module specifier, will we prioritize a file lookup on the interpolation result. + // (In fact, currently, the latter scenario will necessarily fail since no resolution mode recognizes '.ts' as a valid + // extension for a module specifier.) + // + // Here, this means we need to be careful about whether we generate a match from the target filename (typically with a + // .ts extension) or the possible relative module specifiers representing that file: + // + // Filename | Relative Module Specifier Candidates | Path Mapping | Filename Result | Module Specifier Results + // --------------------<----------------------------------------------<------------------------------<-------------------||---------------------------- + // dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*.d.ts"] <- @app/haha || (none) + // dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*"] <- (none) || @app/haha, @app/haha.js + // dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*.d.ts"] <- @app/foo/index || (none) + // dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*"] <- (none) || @app/foo, @app/foo/index, @app/foo/index.js + // dist/wow.js.js <- dist/wow.js, dist/wow.js.js <- "@app/*": ["./dist/*.js"] <- @app/wow.js || @app/wow, @app/wow.js + // + // The "Filename Result" can be generated only if `pattern` has an extension. Care must be taken that the list of + // relative module specifiers to run the interpolation (a) is actually valid for the module resolution mode, (b) takes + // into account the existence of other files (e.g. 'dist/wow.js' cannot refer to 'dist/wow.js.js' if 'dist/wow.js' + // exists) and (c) that they are ordered by preference. The last row shows that the filename result and module + // specifier results are not mutually exclusive. Note that the filename result is a higher priority in module + // resolution, but as long criteria (b) above is met, I don't think its result needs to be the highest priority result + // in module specifier generation. I have included it last, as it's difficult to tell exactly where it should be + // sorted among the others for a particular value of `importModuleSpecifierEnding`. + var candidates = allowedEndings.map(function (ending) { return ({ + ending: ending, + value: removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) + }); }); + if (ts.tryGetExtensionFromPath(pattern)) { + candidates.push({ ending: undefined, value: relativeToBaseUrl }); + } if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix) || - !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); - return key.replace("*", matchedStar); + var prefix = pattern.substring(0, indexOfStar); + var suffix = pattern.substring(indexOfStar + 1); + for (var _b = 0, candidates_3 = candidates; _b < candidates_3.length; _b++) { + var _c = candidates_3[_b], ending = _c.ending, value = _c.value; + if (value.length >= prefix.length + suffix.length && + ts.startsWith(value, prefix) && + ts.endsWith(value, suffix) && + validateEnding({ ending: ending, value: value })) { + var matchedStar = value.substring(prefix.length, value.length - suffix.length); + return { value: key.replace("*", matchedStar) }; + } } } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; + else if (ts.some(candidates, function (c) { return c.ending !== 0 /* Ending.Minimal */ && pattern === c.value; }) || + ts.some(candidates, function (c) { return c.ending === 0 /* Ending.Minimal */ && pattern === c.value && validateEnding(c); })) { + return { value: key }; } + }; + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var state_12 = _loop_36(patternText_1); + if (typeof state_12 === "object") + return state_12.value; } } + function validateEnding(_a) { + var ending = _a.ending, value = _a.value; + // Optimization: `removeExtensionAndIndexPostFix` can query the file system (a good bit) if `ending` is `Minimal`, the basename + // is 'index', and a `host` is provided. To avoid that until it's unavoidable, we ran the function with no `host` above. Only + // here, after we've checked that the minimal ending is indeed a match (via the length and prefix/suffix checks / `some` calls), + // do we check that the host-validated result is consistent with the answer we got before. If it's not, it falls back to the + // `Ending.Index` result, which should already be in the list of candidates if `Minimal` was. (Note: the assumption here is + // that every module resolution mode that supports dropping extensions also supports dropping `/index`. Like literally + // everything else in this file, this logic needs to be updated if that's not true in some future module resolution mode.) + return ending !== 0 /* Ending.Minimal */ || value === removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions, host); + } } var MatchingMode; (function (MatchingMode) { @@ -409774,10 +411681,10 @@ var ts; return undefined; } // Simplify the full file path to something that can be resolved by Node. + var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var moduleSpecifier = path; var isPackageRootPath = false; if (!packageNameOnly) { - var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var packageRootIndex = parts.packageRootIndex; var moduleFileName = void 0; while (true) { @@ -409826,15 +411733,13 @@ var ts; var packageRootPath = path.substring(0, packageRootIndex); var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); var moduleFileToTry = path; + var maybeBlockedByTypesVersions = false; var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) { - var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath)); + var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.contents.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath)); + var importMode = overrideMode || importingSourceFile.impliedNodeFormat; if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { - // `conditions` *could* be made to go against `importingSourceFile.impliedNodeFormat` if something wanted to generate - // an ImportEqualsDeclaration in an ESM-implied file or an ImportCall in a CJS-implied file. But since this function is - // usually called to conjure an import out of thin air, we don't have an existing usage to call `getModeForUsageAtIndex` - // with, so for now we just stick with the mode of the file. - var conditions = ["node", overrideMode || importingSourceFile.impliedNodeFormat === ts.ModuleKind.ESNext ? "import" : "require", "types"]; + var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"]; var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, ts.getPackageNameFromTypesPackageName(packageJsonContent.name), packageJsonContent.exports, conditions) : undefined; @@ -409853,16 +411758,26 @@ var ts; : undefined; if (versionPaths) { var subModuleName = path.slice(packageRootPath.length + 1); - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Ending.Minimal */, options), versionPaths.paths); - if (fromPaths !== undefined) { + var fromPaths = tryGetModuleNameFromPaths(subModuleName, versionPaths.paths, getAllowedEndings(preferences.ending, options, importMode), host, options); + if (fromPaths === undefined) { + maybeBlockedByTypesVersions = true; + } + else { moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths); } } // If the file is the main module, it can be imported by the package name var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main || "index.js"; - if (ts.isString(mainFileRelative)) { + if (ts.isString(mainFileRelative) && !(maybeBlockedByTypesVersions && ts.matchPatternOrExact(ts.tryParsePatterns(versionPaths.paths), mainFileRelative))) { + // The 'main' file is also subject to mapping through typesVersions, and we couldn't come up with a path + // explicitly through typesVersions, so if it matches a key in typesVersions now, it's not reachable. + // (The only way this can happen is if some file in a package that's not resolvable from outside the + // package got pulled into the program anyway, e.g. transitively through a file that *is* reachable. It + // happens very easily in fourslash tests though, since every test file listed gets included. See + // importNameCodeFix_typesVersions.ts for an example.) var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) { + // ^ An arbitrary removal of file extension for this comparison is almost certainly wrong return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry }; } } @@ -410157,23 +412072,46 @@ var ts; var file = _c[_i]; write("".concat(toFileName(file, relativeFileName))); (_a = reasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(function (reason) { return write(" ".concat(fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText)); }); - (_b = explainIfFileIsRedirect(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); + (_b = explainIfFileIsRedirectAndImpliedFormat(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); } } ts.explainFiles = explainFiles; - function explainIfFileIsRedirect(file, fileNameConvertor) { + function explainIfFileIsRedirectAndImpliedFormat(file, fileNameConvertor) { + var _a; var result; if (file.path !== file.resolvedPath) { - (result || (result = [])).push(ts.chainDiagnosticMessages( + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor))); } if (file.redirectInfo) { - (result || (result = [])).push(ts.chainDiagnosticMessages( + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor))); } + if (ts.isExternalOrCommonJsModule(file)) { + switch (file.impliedNodeFormat) { + case ts.ModuleKind.ESNext: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + break; + case ts.ModuleKind.CommonJS: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, file.packageJsonScope.contents.packageJsonContent.type ? + ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : + ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + else if ((_a = file.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.File_is_CommonJS_module_because_package_json_was_not_found)); + } + break; + } + } return result; } - ts.explainIfFileIsRedirect = explainIfFileIsRedirect; + ts.explainIfFileIsRedirectAndImpliedFormat = explainIfFileIsRedirectAndImpliedFormat; function getMatchedFileSpec(program, fileName) { var _a; var configFile = program.getCompilerOptions().configFile; @@ -410190,6 +412128,9 @@ var ts; var configFile = program.getCompilerOptions().configFile; if (!((_a = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _a === void 0 ? void 0 : _a.validatedIncludeSpecs)) return undefined; + // Return true if its default include spec + if (configFile.configFileSpecs.isDefaultIncludeSpec) + return true; var isJsonFile = ts.fileExtensionIs(fileName, ".json" /* Extension.Json */); var basePath = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); var useCaseSensitiveFileNames = program.useCaseSensitiveFileNames(); @@ -410255,11 +412196,13 @@ var ts; if (matchedByFiles) return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Part_of_files_list_in_tsconfig_json); var matchedByInclude = getMatchedIncludeSpec(program, fileName); - return matchedByInclude ? + return ts.isString(matchedByInclude) ? ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.Matched_by_include_pattern_0_in_1, matchedByInclude, toFileName(options.configFile, fileNameConvertor)) : - // Could be additional files specified as roots - ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Root_file_specified_for_compilation); + // Could be additional files specified as roots or matched by default include + ts.chainDiagnosticMessages(/*details*/ undefined, matchedByInclude ? + ts.Diagnostics.Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk : + ts.Diagnostics.Root_file_specified_for_compilation); case ts.FileIncludeKind.SourceFromProjectReference: case ts.FileIncludeKind.OutputFromProjectReference: var isOutput = reason.kind === ts.FileIncludeKind.OutputFromProjectReference; @@ -410378,11 +412321,19 @@ var ts; MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", + AffectingFileLocation: "File location affecting resolution", TypeRoots: "Type roots", ConfigFileOfReferencedProject: "Config file of referened project", ExtendedConfigOfReferencedProject: "Extended config file of referenced project", WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", PackageJson: "package.json file", + ClosedScriptInfo: "Closed Script info", + ConfigFileForInferredRoot: "Config file for the inferred project root", + NodeModules: "node_modules for closed script infos and package.jsons affecting module specifier cache", + MissingSourceMapFile: "Missing source map file", + NoopConfigFileForInferredRoot: "Noop Config file for the inferred project root", + MissingGeneratedFile: "Missing generated file", + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", }; function createWatchFactory(host, options) { var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; @@ -410491,6 +412442,7 @@ var ts; createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, storeFilesChangingSignatureDuringEmit: system.storeFilesChangingSignatureDuringEmit, + now: ts.maybeBind(system, system.now), }; } ts.createProgramHost = createProgramHost; @@ -410558,20 +412510,27 @@ var ts; var ts; (function (ts) { function readBuilderProgram(compilerOptions, host) { - if (ts.outFile(compilerOptions)) - return undefined; var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions); if (!buildInfoPath) return undefined; - var content = host.readFile(buildInfoPath); - if (!content) - return undefined; - var buildInfo = ts.getBuildInfo(content); + var buildInfo; + if (host.getBuildInfo) { + // host provides buildinfo, get it from there. This allows host to cache it + buildInfo = host.getBuildInfo(buildInfoPath, compilerOptions.configFilePath); + if (!buildInfo) + return undefined; + } + else { + var content = host.readFile(buildInfoPath); + if (!content) + return undefined; + buildInfo = ts.getBuildInfo(content); + } if (buildInfo.version !== ts.version) return undefined; if (!buildInfo.program) return undefined; - return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); + return ts.createBuilderProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); } ts.readBuilderProgram = readBuilderProgram; function createIncrementalCompilerHost(options, system) { @@ -410624,14 +412583,12 @@ var ts; var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc var missingFilesMap; // Map of file watchers for the missing files - var packageJsonMap; // map of watchers for package json files used in module resolution var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file var timerToUpdateProgram; // timer callback to recompile the program var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations var parsedConfigs; // Parsed commandline and watching cached for referenced projects var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation - var changesAffectResolution = false; // Flag for indicating non-config changes affect module resolution var reportFileChangeDetectedOnCreateProgram = false; // True if synchronizeProgram should report "File change detected..." when a new program is created var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files @@ -410688,6 +412645,7 @@ var ts; compilerHost.getCompilationSettings = function () { return compilerOptions; }; compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect); compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); }; + compilerHost.watchAffectingFileLocation = function (file, cb) { return watchFile(file, cb, ts.PollingInterval.High, watchOptions, ts.WatchType.AffectingFileLocation); }; compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); }; compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations; @@ -410721,6 +412679,9 @@ var ts; return host.resolveTypeReferenceDirectives.apply(host, args); }) : (function (typeDirectiveNames, containingFile, redirectedReference, _options, containingFileMode) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference, containingFileMode); }); + compilerHost.getModuleResolutionCache = host.resolveModuleNames ? + ts.maybeBind(host, host.getModuleResolutionCache) : + (function () { return resolutionCache.getModuleResolutionCache(); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); @@ -410770,10 +412731,6 @@ var ts; }); parsedConfigs = undefined; } - if (packageJsonMap) { - ts.clearMap(packageJsonMap, ts.closeFileWatcher); - packageJsonMap = undefined; - } } function getCurrentBuilderProgram() { return builderProgram; @@ -410787,12 +412744,12 @@ var ts; var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); - if (program && (changesAffectResolution || ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions))) { + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { resolutionCache.clear(); } } // All resolutions are invalid if user provided resolutions - var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution || changesAffectResolution); + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) { @@ -410808,7 +412765,6 @@ var ts; } createNewProgram(hasInvalidatedResolution); } - changesAffectResolution = false; // reset for next sync reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { host.afterProgramCreate(builderProgram); @@ -410828,16 +412784,11 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + var oldProgram = getCurrentProgram(); builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); - // map package json cache entries to their realpaths so we don't try to watch across symlinks - var packageCacheEntries = ts.map(resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache().entries(), function (_a) { - var path = _a[0], data = _a[1]; - return [compilerHost.realpath ? toPath(compilerHost.realpath(path)) : path, data]; - }); - resolutionCache.finishCachingPerDirectoryResolution(); + resolutionCache.finishCachingPerDirectoryResolution(builderProgram.getProgram(), oldProgram); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = new ts.Map()), watchMissingFilePath); - ts.updatePackageJsonWatch(packageCacheEntries, packageJsonMap || (packageJsonMap = new ts.Map()), watchPackageJsonLookupPath); if (needsUpdateInTypeRootWatch) { resolutionCache.updateTypeRootsWatch(); } @@ -410917,9 +412868,6 @@ var ts; sourceFilesCache.set(path, false); } } - if (sourceFile) { - sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings()); - } return sourceFile; } return hostSourceFile.sourceFile; @@ -411143,21 +413091,6 @@ var ts; ts.noopFileWatcher : watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); } - function watchPackageJsonLookupPath(packageJsonPath) { - // If the package.json is pulled into the compilation itself (eg, via json imports), don't add a second watcher here - return sourceFilesCache.has(packageJsonPath) ? - ts.noopFileWatcher : - watchFilePath(packageJsonPath, packageJsonPath, onPackageJsonChange, ts.PollingInterval.High, watchOptions, ts.WatchType.PackageJson); - } - function onPackageJsonChange(fileName, eventKind, path) { - updateCachedSystemWithFile(fileName, path, eventKind); - // package.json changes invalidate module resolution and can change the set of loaded files - // so if we witness a change to one, we have to do a full reload - reloadLevel = ts.ConfigFileProgramReloadLevel.Full; - changesAffectResolution = true; - // Update the program - scheduleProgramUpdate(); - } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { @@ -411315,14 +413248,17 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream"; - UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate"; - UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked"; - UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream"; - UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["OutOfDateBuildInfo"] = 7] = "OutOfDateBuildInfo"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 8] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 9] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 10] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 11] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["UpToDateWithInputFileText"] = 12] = "UpToDateWithInputFileText"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 13] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ForceBuild"] = 14] = "ForceBuild"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); function resolveConfigFileProjectName(project) { if (ts.fileExtensionIs(project, ".json" /* Extension.Json */)) { @@ -411367,9 +413303,12 @@ var ts; function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { return getOrCreateValueFromConfigFileMap(configFileMap, resolved, function () { return new ts.Map(); }); } - function newer(date1, date2) { - return date2 > date1 ? date2 : date1; + /*@internal*/ + /** Helper to use now method instead of current date for testing purposes to get consistent baselines */ + function getCurrentTime(host) { + return host.now ? host.now() : new Date(); } + ts.getCurrentTime = getCurrentTime; /*@internal*/ function isCircularBuildOrder(buildOrder) { return !!buildOrder && !!buildOrder.buildOrder; @@ -411444,6 +413383,7 @@ var ts; compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); }; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); + compilerHost.getModuleResolutionCache = ts.maybeBind(host, host.getModuleResolutionCache); var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { @@ -411459,6 +413399,7 @@ var ts; return ts.loadWithTypeDirectiveCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, containingFileMode, loader_4); }; } + compilerHost.getBuildInfo = function (fileName, configFilePath) { return getBuildInfo(state, fileName, toResolvedConfigFilePath(state, configFilePath), /*modifiedTime*/ undefined); }; var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -411475,8 +413416,9 @@ var ts; resolvedConfigFilePaths: new ts.Map(), configFileCache: new ts.Map(), projectStatus: new ts.Map(), - buildInfoChecked: new ts.Map(), extendedConfigCache: new ts.Map(), + buildInfoCache: new ts.Map(), + outputTimeStamps: new ts.Map(), builderPrograms: new ts.Map(), diagnostics: new ts.Map(), projectPendingBuild: new ts.Map(), @@ -411492,7 +413434,6 @@ var ts; allProjectBuildPending: true, needsSummary: true, watchAllProjectsPending: watch, - currentInvalidatedProject: undefined, // Watch state watch: watch, allWatchedWildcardDirectories: new ts.Map(), @@ -411500,6 +413441,7 @@ var ts; allWatchedConfigFiles: new ts.Map(), allWatchedExtendedConfigFiles: new ts.Map(), allWatchedPackageJsonFiles: new ts.Map(), + filesWatched: new ts.Map(), lastCachedPackageJsonLookups: new ts.Map(), timerToBuildInvalidatedProject: undefined, reportFileChangeDetected: false, @@ -411606,11 +413548,12 @@ var ts; // Config file cache ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete); - ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.buildInfoCache, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.outputTimeStamps, currentProjects, noopOnDelete); // Remove watches for the program no longer in the solution if (state.watch) { ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher }); @@ -411725,7 +413668,6 @@ var ts; })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {})); function doneInvalidatedProject(state, projectPath) { state.projectPendingBuild.delete(projectPath); - state.currentInvalidatedProject = undefined; return state.diagnostics.has(projectPath) ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; @@ -411901,21 +413843,21 @@ var ts; } function emit(writeFileCallback, cancellationToken, customTransformers) { var _a; - var _b, _c; + var _b, _c, _d; ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.Emit); // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly - program.backupState(); + var saved = program.saveEmitState(); var declDiagnostics; var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; var outputFiles = []; var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, /*write*/ undefined, - /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, + /*reportSummary*/ undefined, function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark, buildInfo: data === null || data === void 0 ? void 0 : data.buildInfo }); }, cancellationToken, /*emitOnlyDts*/ false, customTransformers || ((_c = (_b = state.host).getCustomTransformers) === null || _c === void 0 ? void 0 : _c.call(_b, project))).emitResult; // Don't emit .d.ts if there are decl file errors if (declDiagnostics) { - program.restoreState(); + program.restoreEmitState(saved); (_a = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"), buildResult = _a.buildResult, step = _a.step); return { emitSkipped: true, @@ -411924,38 +413866,38 @@ var ts; } // Actual Emit var host = state.host, compilerHost = state.compilerHost; - var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; - var newestDeclarationFileContentChangedTime = minimumDate; - var anyDtsChanged = false; + var resultFlags = ((_d = program.hasChangedEmitSignature) === null || _d === void 0 ? void 0 : _d.call(program)) ? BuildResultFlags.None : BuildResultFlags.DeclarationOutputUnchanged; var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var options = program.getCompilerOptions(); + var isIncremental = ts.isIncrementalCompilation(options); + var outputTimeStampMap; + var now; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; - var priorChangeTime; - if (!anyDtsChanged && ts.isDeclarationFileName(name)) { - // Check for unchanged .d.ts files - if (host.fileExists(name) && state.readFileWithCache(name) === text) { - priorChangeTime = host.getModifiedTime(name); - } - else { - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - anyDtsChanged = true; - } - } + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; + var path = toPath(state, name); emittedOutputs.set(toPath(state, name), name); + if (buildInfo) + setBuildInfo(state, buildInfo, projectPath, options, resultFlags); ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); - if (priorChangeTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + if (!isIncremental && state.watch) { + (outputTimeStampMap || (outputTimeStampMap = getOutputTimeStampMap(state, projectPath))).set(path, now || (now = getCurrentTime(state.host))); } }); - finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, - /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); + finishEmit(emitterDiagnostics, emittedOutputs, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); return emitResult; } function emitBuildInfo(writeFileCallback, cancellationToken) { ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.EmitBuildInfo); - var emitResult = program.emitBuildInfo(writeFileCallback, cancellationToken); + var emitResult = program.emitBuildInfo(function (name, text, writeByteOrderMark, onError, sourceFiles, data) { + if (data === null || data === void 0 ? void 0 : data.buildInfo) + setBuildInfo(state, data.buildInfo, projectPath, program.getCompilerOptions(), BuildResultFlags.DeclarationOutputUnchanged); + if (writeFileCallback) + writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data); + else + state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data); + }, cancellationToken); if (emitResult.diagnostics.length) { reportErrors(state, emitResult.diagnostics); state.diagnostics.set(projectPath, __spreadArray(__spreadArray([], state.diagnostics.get(projectPath), true), emitResult.diagnostics, true)); @@ -411968,7 +413910,7 @@ var ts; step = BuildStep.QueueReferencingProjects; return emitResult; } - function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) { + function finishEmit(emitterDiagnostics, emittedOutputs, oldestOutputFileName, resultFlags) { var _a; var emitDiagnostics = emitterDiagnostics.getDiagnostics(); if (emitDiagnostics.length) { @@ -411979,13 +413921,10 @@ var ts; emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); }); } // Update time stamps for rest of the outputs - var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); + updateOutputTimestampsWorker(state, config, projectPath, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); state.diagnostics.delete(projectPath); state.projectStatus.set(projectPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ? - maximumDate : - newestDeclarationFileContentChangedTime, oldestOutputFileName: oldestOutputFileName }); afterProgramDone(state, program, config); @@ -412020,13 +413959,21 @@ var ts; ts.Debug.assert(!!outputFiles.length); var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; + var existingBuildInfo = state.buildInfoCache.get(projectPath).buildInfo; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + var _b, _c; + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; emittedOutputs.set(toPath(state, name), name); + if (buildInfo) { + if (((_b = buildInfo.program) === null || _b === void 0 ? void 0 : _b.outSignature) !== ((_c = existingBuildInfo.program) === null || _c === void 0 ? void 0 : _c.outSignature)) { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + } + setBuildInfo(state, buildInfo, projectPath, config.options, resultFlags); + } ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); }); - var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, - /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged); + var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, outputFiles[0].name, resultFlags); return { emitSkipped: false, diagnostics: emitDiagnostics }; } function executeSteps(till, cancellationToken, writeFile, customTransformers) { @@ -412076,17 +414023,11 @@ var ts; !!ts.getConfigFileParsingDiagnostics(config).length || !ts.isIncrementalCompilation(config.options); } - function getNextInvalidatedProject(state, buildOrder, reportQueue) { + function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { if (!state.projectPendingBuild.size) return undefined; if (isCircularBuildOrder(buildOrder)) return undefined; - if (state.currentInvalidatedProject) { - // Only if same buildOrder the currentInvalidated project can be sent again - return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ? - state.currentInvalidatedProject : - undefined; - } var options = state.options, projectPendingBuild = state.projectPendingBuild; for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) { var project = buildOrder[projectIndex]; @@ -412119,9 +414060,9 @@ var ts; watchPackageJsonFiles(state, project, projectPath, config); } var status = getUpToDateStatus(state, config, projectPath); - verboseReportProjectStatus(state, project, status); if (!options.force) { if (status.type === ts.UpToDateStatusType.UpToDate) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); // Up to date, skip @@ -412131,12 +414072,20 @@ var ts; } continue; } - if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) { + if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes || status.type === ts.UpToDateStatusType.UpToDateWithInputFileText) { reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); - return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder); + return { + kind: InvalidatedProjectKind.UpdateOutputFileStamps, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config + }; } } if (status.type === ts.UpToDateStatusType.UpstreamBlocked) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); if (options.verbose) { @@ -412147,17 +414096,37 @@ var ts; continue; } if (status.type === ts.UpToDateStatusType.ContainerOnly) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); // Do nothing continue; } - return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ? - InvalidatedProjectKind.Build : - InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder); + return { + kind: needsBuild(state, status, config) ? + InvalidatedProjectKind.Build : + InvalidatedProjectKind.UpdateBundle, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config, + }; } return undefined; } + function createInvalidatedProjectWithInfo(state, info, buildOrder) { + verboseReportProjectStatus(state, info.project, info.status); + return info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps ? + createBuildOrUpdateInvalidedProject(info.kind, state, info.project, info.projectPath, info.projectIndex, info.config, buildOrder) : + createUpdateOutputFileStampsProject(state, info.project, info.projectPath, info.config, buildOrder); + } + function getNextInvalidatedProject(state, buildOrder, reportQueue) { + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue); + if (!info) + return info; + return createInvalidatedProjectWithInfo(state, info, buildOrder); + } function listEmittedFile(_a, proj, file) { var write = _a.write; if (write && proj.options.listEmittedFiles) { @@ -412175,7 +414144,7 @@ var ts; } function afterProgramDone(state, program, config) { if (program) { - if (program && state.write) + if (state.write) ts.listFiles(program, state.write); if (state.host.afterProgramEmitAndDiagnostics) { state.host.afterProgramEmitAndDiagnostics(program); @@ -412188,7 +414157,8 @@ var ts; state.projectCompilerOptions = state.baseCompilerOptions; } function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) { - var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions()); + // Since buildinfo has changeset and diagnostics when doing multi file emit, only --out cannot emit buildinfo if it has errors + var canEmitBuildInfo = program && !ts.outFile(program.getCompilerOptions()); reportAndStoreErrors(state, resolvedPath, diagnostics); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: "".concat(errorType, " errors") }); if (canEmitBuildInfo) @@ -412196,9 +414166,107 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } + function isFileWatcherWithModifiedTime(value) { + return !!value.watcher; + } + function getModifiedTime(state, fileName) { + var path = toPath(state, fileName); + var existing = state.filesWatched.get(path); + if (state.watch && !!existing) { + if (!isFileWatcherWithModifiedTime(existing)) + return existing; + if (existing.modifiedTime) + return existing.modifiedTime; + } + // In watch mode we store the modified times in the cache + // This is either Date | FileWatcherWithModifiedTime because we query modified times first and + // then after complete compilation of the project, watch the files so we dont want to loose these modified times. + var result = ts.getModifiedTime(state.host, fileName); + if (state.watch) { + if (existing) + existing.modifiedTime = result; + else + state.filesWatched.set(path, result); + } + return result; + } + function watchFile(state, file, callback, pollingInterval, options, watchType, project) { + var path = toPath(state, file); + var existing = state.filesWatched.get(path); + if (existing && isFileWatcherWithModifiedTime(existing)) { + existing.callbacks.push(callback); + } + else { + var watcher = state.watchFile(file, function (fileName, eventKind, modifiedTime) { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + existing.modifiedTime = modifiedTime; + existing.callbacks.forEach(function (cb) { return cb(fileName, eventKind, modifiedTime); }); + }, pollingInterval, options, watchType, project); + state.filesWatched.set(path, { callbacks: [callback], watcher: watcher, modifiedTime: existing }); + } + return { + close: function () { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + if (existing.callbacks.length === 1) { + state.filesWatched.delete(path); + ts.closeFileWatcherOf(existing); + } + else { + ts.unorderedRemoveItem(existing.callbacks, callback); + } + } + }; + } + function getOutputTimeStampMap(state, resolvedConfigFilePath) { + // Output timestamps are stored only in watch mode + if (!state.watch) + return undefined; + var result = state.outputTimeStamps.get(resolvedConfigFilePath); + if (!result) + state.outputTimeStamps.set(resolvedConfigFilePath, result = new ts.Map()); + return result; + } + function setBuildInfo(state, buildInfo, resolvedConfigPath, options, resultFlags) { + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(options); + var existing = getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath); + var modifiedTime = getCurrentTime(state.host); + if (existing) { + existing.buildInfo = buildInfo; + existing.modifiedTime = modifiedTime; + if (!(resultFlags & BuildResultFlags.DeclarationOutputUnchanged)) + existing.latestChangedDtsTime = modifiedTime; + } + else { + state.buildInfoCache.set(resolvedConfigPath, { + path: toPath(state, buildInfoPath), + buildInfo: buildInfo, + modifiedTime: modifiedTime, + latestChangedDtsTime: resultFlags & BuildResultFlags.DeclarationOutputUnchanged ? undefined : modifiedTime, + }); + } + } + function getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + return (existing === null || existing === void 0 ? void 0 : existing.path) === path ? existing : undefined; + } + function getBuildInfo(state, buildInfoPath, resolvedConfigPath, modifiedTime) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + if (existing !== undefined && existing.path === path) { + return existing.buildInfo || undefined; + } + var value = state.readFileWithCache(buildInfoPath); + var buildInfo = value ? ts.getBuildInfo(value) : undefined; + ts.Debug.assert(modifiedTime || !buildInfo); + state.buildInfoCache.set(resolvedConfigPath, { path: path, buildInfo: buildInfo || false, modifiedTime: modifiedTime || ts.missingFileModifiedTime }); + return buildInfo; + } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time - var tsconfigTime = ts.getModifiedTime(state.host, configFile); + var tsconfigTime = getModifiedTime(state, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: ts.UpToDateStatusType.OutOfDateWithSelf, @@ -412208,88 +414276,24 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { - var force = !!state.options.force; - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - var host = state.host; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: ts.UpToDateStatusType.Unbuildable, - reason: "".concat(inputFile, " does not exist") - }; - } - if (!force) { - var inputTime = ts.getModifiedTime(host, inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - } + var _a, _b; // Container if no files are specified in the project if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) { return { type: ts.UpToDateStatusType.ContainerOnly }; } - // Collect the expected outputs of this project - var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - if (!force) { - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = ts.getModifiedTime(host, output); - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (ts.isDeclarationFileName(output)) { - var outputModifiedTime = ts.getModifiedTime(host, output); - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; + // Fast check to see if reference projects are upto date and error free + var referenceStatuses; + var force = !!state.options.force; if (project.projectReferences) { state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream }); - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); + for (var _i = 0, _c = project.projectReferences; _i < _c.length; _i++) { + var ref = _c[_i]; var resolvedRef = ts.resolveProjectReferencePath(ref); var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef); - var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath); + var resolvedConfig = parseConfigFile(state, resolvedRef, resolvedRefPath); + var refStatus = getUpToDateStatus(state, resolvedConfig, resolvedRefPath); // Its a circular reference ignore the status of this project if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream || refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project @@ -412311,75 +414315,190 @@ var ts; upstreamProjectName: ref.path }; } - // Check oldest output file name only if there is no missing output file name - // (a check we will have skipped if this is a forced build) - if (!force && !missingOutputFileName) { - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + if (!force) + (referenceStatuses || (referenceStatuses = [])).push({ ref: ref, refStatus: refStatus, resolvedRefPath: resolvedRefPath, resolvedConfig: resolvedConfig }); + } + } + if (force) + return { type: ts.UpToDateStatusType.ForceBuild }; + // Check buildinfo first + var host = state.host; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); + var oldestOutputFileName; + var oldestOutputFileTime = maximumDate; + var buildInfoTime; + var buildInfoProgram; + var buildInfoVersionMap; + if (buildInfoPath) { + var buildInfoCacheEntry_1 = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath); + buildInfoTime = (buildInfoCacheEntry_1 === null || buildInfoCacheEntry_1 === void 0 ? void 0 : buildInfoCacheEntry_1.modifiedTime) || ts.getModifiedTime(host, buildInfoPath); + if (buildInfoTime === ts.missingFileModifiedTime) { + if (!buildInfoCacheEntry_1) { + state.buildInfoCache.set(resolvedPath, { + path: toPath(state, buildInfoPath), + buildInfo: false, + modifiedTime: buildInfoTime + }); + } + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: buildInfoPath + }; + } + var buildInfo = ts.Debug.checkDefined(getBuildInfo(state, buildInfoPath, resolvedPath, buildInfoTime)); + if ((buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + return { + type: ts.UpToDateStatusType.TsVersionOutputOfDate, + version: buildInfo.version + }; + } + if (buildInfo.program) { + // If there are pending changes that are not emitted, project is out of date + if (((_a = buildInfo.program.changeFileSet) === null || _a === void 0 ? void 0 : _a.length) || + (!project.options.noEmit && ((_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length))) { return { - type: ts.UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path + type: ts.UpToDateStatusType.OutOfDateBuildInfo, + buildInfoFile: buildInfoPath }; } + buildInfoProgram = buildInfo.program; } + oldestOutputFileTime = buildInfoTime; + oldestOutputFileName = buildInfoPath; } - if (missingOutputFileName !== undefined) { - return { - type: ts.UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: ts.UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; + // Check input files + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + /** True if input file has changed timestamp but text is not changed, we can then do only timestamp updates on output to make it look up-to-date later */ + var pseudoInputUpToDate = false; + // Get timestamps of input files + for (var _d = 0, _e = project.fileNames; _d < _e.length; _d++) { + var inputFile = _e[_d]; + var inputTime = getModifiedTime(state, inputFile); + if (inputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.Unbuildable, + reason: "".concat(inputFile, " does not exist") + }; + } + // If an buildInfo is older than the newest input, we can stop checking + if (buildInfoTime && buildInfoTime < inputTime) { + var version_3 = void 0; + var currentVersion = void 0; + if (buildInfoProgram) { + // Read files and see if they are same, read is anyways cached + if (!buildInfoVersionMap) + buildInfoVersionMap = ts.getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + version_3 = buildInfoVersionMap.get(toPath(state, inputFile)); + var text = version_3 ? state.readFileWithCache(inputFile) : undefined; + currentVersion = text && (host.createHash || ts.generateDjb2Hash)(text); + if (version_3 && version_3 === currentVersion) + pseudoInputUpToDate = true; + } + if (!version_3 || version_3 !== currentVersion) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: buildInfoPath, + newerInputFileName: inputFile + }; + } + } + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - else { - // Check tsconfig time - var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); - if (configStatus) - return configStatus; - // Check extended config time - var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); - if (extendedConfigStatus) - return extendedConfigStatus; - // Check package file time - var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { - var path = _a[0]; - return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); - }); - if (dependentPackageFileStatus) - return dependentPackageFileStatus; + // Now see if all outputs are newer than the newest input + // Dont check output timestamps if we have buildinfo telling us output is uptodate + if (!buildInfoPath) { + // Collect the expected outputs of this project + var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, resolvedPath); + for (var _f = 0, outputs_1 = outputs; _f < outputs_1.length; _f++) { + var output = outputs_1[_f]; + var path = toPath(state, output); + // Output is missing; can stop checking + var outputTime = outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.get(path); + if (!outputTime) { + outputTime = ts.getModifiedTime(state.host, output); + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.set(path, outputTime); + } + if (outputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: output + }; + } + // If an output is older than the newest input, we can stop checking + if (outputTime < newestInputFileTime) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: output, + newerInputFileName: newestInputFileName + }; + } + // No need to get newestDeclarationFileContentChangedTime since thats needed only for composite projects + // And composite projects are the only ones that can be referenced + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + } } - if (!force && !state.buildInfoChecked.has(resolvedPath)) { - state.buildInfoChecked.set(resolvedPath, true); - var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); - if (buildInfoPath) { - var value = state.readFileWithCache(buildInfoPath); - var buildInfo = value && ts.getBuildInfo(value); - if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + var buildInfoCacheEntry = state.buildInfoCache.get(resolvedPath); + /** Inputs are up-to-date, just need either timestamp update or bundle prepend manipulation to make it look up-to-date */ + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (referenceStatuses) { + for (var _g = 0, referenceStatuses_1 = referenceStatuses; _g < referenceStatuses_1.length; _g++) { + var _h = referenceStatuses_1[_g], ref = _h.ref, refStatus = _h.refStatus, resolvedConfig = _h.resolvedConfig, resolvedRefPath = _h.resolvedRefPath; + usesPrepend = usesPrepend || !!(ref.prepend); + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // Check if tsbuildinfo path is shared, then we need to rebuild + if (buildInfoCacheEntry && hasSameBuildInfo(state, buildInfoCacheEntry, resolvedRefPath)) { return { - type: ts.UpToDateStatusType.TsVersionOutputOfDate, - version: buildInfo.version + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: buildInfoPath, + newerProjectName: ref.path }; } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + var newestDeclarationFileContentChangedTime = getLatestChangedDtsTime(state, resolvedConfig.options, resolvedRefPath); + if (newestDeclarationFileContentChangedTime && newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } } + // Check tsconfig time + var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + // Check extended config time + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + // Check package file time + var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { + var path = _a[0]; + return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); + }); + if (dependentPackageFileStatus) + return dependentPackageFileStatus; if (usesPrepend && pseudoUpToDate) { return { type: ts.UpToDateStatusType.OutOfDateWithPrepend, @@ -412389,15 +414508,20 @@ var ts; } // Up to date return { - type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + type: pseudoUpToDate ? + ts.UpToDateStatusType.UpToDateWithUpstreamTypes : + pseudoInputUpToDate ? + ts.UpToDateStatusType.UpToDateWithInputFileText : + ts.UpToDateStatusType.UpToDate, newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, oldestOutputFileName: oldestOutputFileName }; } + function hasSameBuildInfo(state, buildInfoCacheEntry, resolvedRefPath) { + var refBuildInfo = state.buildInfoCache.get(resolvedRefPath); + return refBuildInfo.path === buildInfoCacheEntry.path; + } function getUpToDateStatus(state, project, resolvedPath) { if (project === undefined) { return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; @@ -412410,39 +414534,71 @@ var ts; state.projectStatus.set(resolvedPath, actual); return actual; } - function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { + function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, skipOutputs) { if (proj.options.noEmit) - return priorNewestUpdateTime; + return; + var now; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(proj.options); + if (buildInfoPath) { + // For incremental projects, only buildinfo needs to be upto date with timestamp check + // as we dont check output files for up-to-date ness + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(toPath(state, buildInfoPath)))) { + if (!!state.options.verbose) + reportStatus(state, verboseMessage, proj.options.configFilePath); + state.host.setModifiedTime(buildInfoPath, now = getCurrentTime(state.host)); + getBuildInfoCacheEntry(state, buildInfoPath, projectPath).modifiedTime = now; + } + state.outputTimeStamps.delete(projectPath); + return; + } var host = state.host; var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, projectPath); + var modifiedOutputs = outputTimeStampMap ? new ts.Set() : undefined; if (!skipOutputs || outputs.length !== skipOutputs.size) { var reportVerbose = !!state.options.verbose; - var now = host.now ? host.now() : new Date(); for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { var file = outputs_2[_i]; - if (skipOutputs && skipOutputs.has(toPath(state, file))) { + var path = toPath(state, file); + if (skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(path)) continue; - } if (reportVerbose) { reportVerbose = false; reportStatus(state, verboseMessage, proj.options.configFilePath); } - if (ts.isDeclarationFileName(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file)); + host.setModifiedTime(file, now || (now = getCurrentTime(state.host))); + // Store output timestamps in a map because non incremental build will need to check them to determine up-to-dateness + if (outputTimeStampMap) { + outputTimeStampMap.set(path, now); + modifiedOutputs.add(path); } - host.setModifiedTime(file, now); } } - return priorNewestUpdateTime; + // Clear out timestamps not in output list any more + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.forEach(function (_value, key) { + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(key)) && !modifiedOutputs.has(key)) + outputTimeStampMap.delete(key); + }); + } + function getLatestChangedDtsTime(state, options, resolvedConfigPath) { + if (!options.composite) + return undefined; + var entry = ts.Debug.checkDefined(state.buildInfoCache.get(resolvedConfigPath)); + if (entry.latestChangedDtsTime !== undefined) + return entry.latestChangedDtsTime || undefined; + var latestChangedDtsTime = entry.buildInfo && entry.buildInfo.program && entry.buildInfo.program.latestChangedDtsFile ? + state.host.getModifiedTime(ts.getNormalizedAbsolutePath(entry.buildInfo.program.latestChangedDtsFile, ts.getDirectoryPath(entry.path))) : + undefined; + entry.latestChangedDtsTime = latestChangedDtsTime || false; + return latestChangedDtsTime; } function updateOutputTimestamps(state, proj, resolvedPath) { if (state.options.dry) { return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath); } - var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); + updateOutputTimestampsWorker(state, proj, resolvedPath, ts.Diagnostics.Updating_output_timestamps_of_project_0); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: priorNewestUpdateTime, oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames()) }); } @@ -412488,6 +414644,7 @@ var ts; break; } // falls through + case ts.UpToDateStatusType.UpToDateWithInputFileText: case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: case ts.UpToDateStatusType.OutOfDateWithPrepend: if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { @@ -412598,9 +414755,9 @@ var ts; function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) { state.reportFileChangeDetected = true; invalidateProject(state, resolvedPath, reloadLevel); - scheduleBuildInvalidatedProject(state); + scheduleBuildInvalidatedProject(state, 250, /*changeDetected*/ true); } - function scheduleBuildInvalidatedProject(state) { + function scheduleBuildInvalidatedProject(state, time, changeDetected) { var hostWithWatch = state.hostWithWatch; if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; @@ -412608,25 +414765,38 @@ var ts; if (state.timerToBuildInvalidatedProject) { hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject); } - state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state); + state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, time, state, changeDetected); } - function buildNextInvalidatedProject(state) { + function buildNextInvalidatedProject(state, changeDetected) { state.timerToBuildInvalidatedProject = undefined; if (state.reportFileChangeDetected) { state.reportFileChangeDetected = false; state.projectErrorsReported.clear(); reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation); } + var projectsBuilt = 0; var buildOrder = getBuildOrder(state); var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false); if (invalidatedProject) { invalidatedProject.done(); - if (state.projectPendingBuild.size) { - // Schedule next project for build - if (state.watch && !state.timerToBuildInvalidatedProject) { - scheduleBuildInvalidatedProject(state); + projectsBuilt++; + while (state.projectPendingBuild.size) { + // If already scheduled, skip + if (state.timerToBuildInvalidatedProject) + return; + // Before scheduling check if the next project needs build + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, /*reportQueue*/ false); + if (!info) + break; // Nothing to build any more + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps && (changeDetected || projectsBuilt === 5)) { + // Schedule next project for build + scheduleBuildInvalidatedProject(state, 100, /*changeDetected*/ false); + return; } - return; + var project = createInvalidatedProjectWithInfo(state, info, buildOrder); + project.done(); + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps) + projectsBuilt++; } } disableCache(state); @@ -412635,12 +414805,10 @@ var ts; function watchConfigFile(state, resolved, resolvedPath, parsed) { if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return; - state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(resolved, function () { - invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); - }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); + state.allWatchedConfigFiles.set(resolvedPath, watchFile(state, resolved, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { + ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(state, extendedConfigFileName, function () { var _a; return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) { return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full); @@ -412672,7 +414840,7 @@ var ts; if (!state.watch) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), { - createNewValue: function (_path, input) { return state.watchFile(input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, + createNewValue: function (_path, input) { return watchFile(state, input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -412680,7 +414848,7 @@ var ts; if (!state.watch || !state.lastCachedPackageJsonLookups) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), new ts.Map(state.lastCachedPackageJsonLookups.get(resolvedPath)), { - createNewValue: function (path, _input) { return state.watchFile(path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, + createNewValue: function (path, _input) { return watchFile(state, path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -412730,8 +414898,6 @@ var ts; return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath); }, invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); }, - buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); }, - getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); }, close: function () { return stopWatching(state); }, }; } @@ -412812,19 +414978,18 @@ var ts; } } function reportUpToDateStatus(state, configFileName, status) { - if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) { - return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); - } switch (status.type) { case ts.UpToDateStatusType.OutOfDateWithSelf: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); case ts.UpToDateStatusType.OutOfDateWithUpstream: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.OutputMissing: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(state, configFileName), relName(state, status.missingOutputFileName)); + case ts.UpToDateStatusType.OutOfDateBuildInfo: + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted, relName(state, configFileName), relName(state, status.buildInfoFile)); case ts.UpToDateStatusType.UpToDate: if (status.newestInputFileTime !== undefined) { - return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); } // Don't report anything for "up to date because it was already built" -- too verbose break; @@ -412832,6 +414997,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(state, configFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName)); + case ts.UpToDateStatusType.UpToDateWithInputFileText: + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files, relName(state, configFileName)); case ts.UpToDateStatusType.UpstreamOutOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(state, configFileName), relName(state, status.upstreamProjectName)); case ts.UpToDateStatusType.UpstreamBlocked: @@ -412842,6 +415009,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason); case ts.UpToDateStatusType.TsVersionOutputOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(state, configFileName), status.version, ts.version); + case ts.UpToDateStatusType.ForceBuild: + return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); case ts.UpToDateStatusType.ContainerOnly: // Don't report status on "solution" projects // falls through @@ -413008,7 +415177,7 @@ var ts; * @param typeAcquisition is used to customize the typing acquisition process * @param compilerOptions are used as a source for typing inference */ - function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry, compilerOptions) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } @@ -413026,12 +415195,14 @@ var ts; addInferredTypings(typeAcquisition.include, "Explicitly included types"); var exclude = typeAcquisition.exclude || []; // Directories to search for package.json, bower.json and other typing information - var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); - possibleSearchDirs.add(projectRootPath); - possibleSearchDirs.forEach(function (searchDir) { - getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); - getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); - }); + if (!compilerOptions.types) { + var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); + possibleSearchDirs.add(projectRootPath); + possibleSearchDirs.forEach(function (searchDir) { + getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); + getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); + }); + } if (!typeAcquisition.disableFilenameBasedTypeAcquisition) { getTypingNamesFromSourceFileNames(fileNames); } @@ -414394,6 +416565,8 @@ var ts; case 256 /* SyntaxKind.FunctionDeclaration */: case 213 /* SyntaxKind.FunctionExpression */: return getAdjustedLocationForFunction(node); + case 171 /* SyntaxKind.Constructor */: + return node; } } if (ts.isNamedDeclaration(node)) { @@ -414482,7 +416655,7 @@ var ts; // // NOTE: If the node is a modifier, we don't adjust its location if it is the `default` modifier as that is handled // specially by `getSymbolAtLocation`. - if (ts.isModifier(node) && (forRename || node.kind !== 88 /* SyntaxKind.DefaultKeyword */) ? ts.contains(parent.modifiers, node) : + if (ts.isModifier(node) && (forRename || node.kind !== 88 /* SyntaxKind.DefaultKeyword */) ? ts.canHaveModifiers(parent) && ts.contains(parent.modifiers, node) : node.kind === 84 /* SyntaxKind.ClassKeyword */ ? ts.isClassDeclaration(parent) || ts.isClassExpression(node) : node.kind === 98 /* SyntaxKind.FunctionKeyword */ ? ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(node) : node.kind === 118 /* SyntaxKind.InterfaceKeyword */ ? ts.isInterfaceDeclaration(parent) : @@ -414721,12 +416894,18 @@ var ts; // flag causes us to return the first node whose end position matches the position and which produces and acceptable token // kind. Meanwhile, if includePrecedingTokenAtEndPosition is unset, we look for the first node whose start is <= the // position and whose end is greater than the position. + // There are more sophisticated end tests later, but this one is very fast + // and allows us to skip a bunch of work + var end = children[middle].getEnd(); + if (end < position) { + return -1 /* Comparison.LessThan */; + } var start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { return 1 /* Comparison.GreaterThan */; } // first element whose start position is before the input and whose end position is after or equal to the input - if (nodeContainsPosition(children[middle])) { + if (nodeContainsPosition(children[middle], start, end)) { if (children[middle - 1]) { // we want the _first_ element that contains the position, so left-recur if the prior node also contains the position if (nodeContainsPosition(children[middle - 1])) { @@ -414758,13 +416937,16 @@ var ts; case "continue-outer": continue outer; } } - function nodeContainsPosition(node) { - var start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true); + function nodeContainsPosition(node, start, end) { + end !== null && end !== void 0 ? end : (end = node.getEnd()); + if (end < position) { + return false; + } + start !== null && start !== void 0 ? start : (start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true)); if (start > position) { // If this child begins after position, then all subsequent children will as well. return false; } - var end = node.getEnd(); if (position < end || (position === end && (node.kind === 1 /* SyntaxKind.EndOfFileToken */ || includeEndPosition))) { return true; } @@ -415462,7 +417644,6 @@ var ts; ts.makeImportIfNecessary = makeImportIfNecessary; function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference, isTypeOnly) { return ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, defaultImport || namedImports ? ts.factory.createImportClause(!!isTypeOnly, defaultImport, namedImports && namedImports.length ? ts.factory.createNamedImports(namedImports) : undefined) : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier, @@ -415552,7 +417733,7 @@ var ts; node.getEnd() <= ts.textSpanEnd(span); } function findModifier(node, kind) { - return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); + return ts.canHaveModifiers(node) ? ts.find(node.modifiers, function (m) { return m.kind === kind; }) : undefined; } ts.findModifier = findModifier; function insertImports(changes, sourceFile, imports, blankLineBetween) { @@ -415631,6 +417812,41 @@ var ts; return true; } ts.isTextWhiteSpaceLike = isTextWhiteSpaceLike; + function getMappedLocation(location, sourceMapper, fileExists) { + var mapsTo = sourceMapper.tryGetSourcePosition(location); + return mapsTo && (!fileExists || fileExists(ts.normalizePath(mapsTo.fileName)) ? mapsTo : undefined); + } + ts.getMappedLocation = getMappedLocation; + function getMappedDocumentSpan(documentSpan, sourceMapper, fileExists) { + var fileName = documentSpan.fileName, textSpan = documentSpan.textSpan; + var newPosition = getMappedLocation({ fileName: fileName, pos: textSpan.start }, sourceMapper, fileExists); + if (!newPosition) + return undefined; + var newEndPosition = getMappedLocation({ fileName: fileName, pos: textSpan.start + textSpan.length }, sourceMapper, fileExists); + var newLength = newEndPosition + ? newEndPosition.pos - newPosition.pos + : textSpan.length; // This shouldn't happen + return { + fileName: newPosition.fileName, + textSpan: { + start: newPosition.pos, + length: newLength, + }, + originalFileName: documentSpan.fileName, + originalTextSpan: documentSpan.textSpan, + contextSpan: getMappedContextSpan(documentSpan, sourceMapper, fileExists), + originalContextSpan: documentSpan.contextSpan + }; + } + ts.getMappedDocumentSpan = getMappedDocumentSpan; + function getMappedContextSpan(documentSpan, sourceMapper, fileExists) { + var contextSpanStart = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start }, sourceMapper, fileExists); + var contextSpanEnd = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start + documentSpan.contextSpan.length }, sourceMapper, fileExists); + return contextSpanStart && contextSpanEnd ? + { start: contextSpanStart.pos, length: contextSpanEnd.pos - contextSpanStart.pos } : + undefined; + } + ts.getMappedContextSpan = getMappedContextSpan; // #endregion // Display-part writer helpers // #region @@ -416124,7 +418340,7 @@ var ts; for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { var change = textChanges_1[_b]; var span = change.span, newText = change.newText; - var index = indexInTextChange(newText, name); + var index = indexInTextChange(newText, ts.escapeString(name)); if (index !== -1) { lastPos = span.start + delta + index; // If the reference comes first, return immediately. @@ -417092,32 +419308,41 @@ var ts; || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } - function forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, cb) { + function forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, cb) { var _a, _b; - forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var excludePatterns = preferences.autoImportFileExcludePatterns && ts.mapDefined(preferences.autoImportFileExcludePatterns, function (spec) { + // The client is expected to send rooted path specs since we don't know + // what directory a relative path is relative to. + var pattern = ts.getPatternFromSpec(spec, "", "exclude"); + return pattern ? ts.getRegexFromPattern(pattern, useCaseSensitiveFileNames) : undefined; + }); + forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); var autoImportProvider = useAutoImportProvider && ((_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)); if (autoImportProvider) { var start = ts.timestamp(); - forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); + forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), excludePatterns, function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "forEachExternalModuleToImportFrom autoImportProvider: ".concat(ts.timestamp() - start)); } } ts.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; - function forEachExternalModule(checker, allSourceFiles, cb) { - for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { - var ambient = _a[_i]; - if (!ts.stringContains(ambient.name, "*")) { + function forEachExternalModule(checker, allSourceFiles, excludePatterns, cb) { + var _a; + var isExcluded = function (fileName) { return excludePatterns === null || excludePatterns === void 0 ? void 0 : excludePatterns.some(function (p) { return p.test(fileName); }); }; + for (var _i = 0, _b = checker.getAmbientModules(); _i < _b.length; _i++) { + var ambient = _b[_i]; + if (!ts.stringContains(ambient.name, "*") && !(excludePatterns && ((_a = ambient.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return isExcluded(d.getSourceFile().fileName); })))) { cb(ambient, /*sourceFile*/ undefined); } } - for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { - var sourceFile = allSourceFiles_1[_b]; - if (ts.isExternalOrCommonJsModule(sourceFile)) { + for (var _c = 0, allSourceFiles_1 = allSourceFiles; _c < allSourceFiles_1.length; _c++) { + var sourceFile = allSourceFiles_1[_c]; + if (ts.isExternalOrCommonJsModule(sourceFile) && !isExcluded(sourceFile.fileName)) { cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); } } } - function getExportInfoMap(importingFile, host, program, cancellationToken) { + function getExportInfoMap(importingFile, host, program, preferences, cancellationToken) { var _a, _b, _c, _d, _e; var start = ts.timestamp(); // Pulling the AutoImportProvider project will trigger its updateGraph if pending, @@ -417137,7 +419362,7 @@ var ts; var compilerOptions = program.getCompilerOptions(); var moduleCount = 0; try { - forEachExternalModuleToImportFrom(program, host, /*useAutoImportProvider*/ true, function (moduleSymbol, moduleFile, program, isFromPackageJson) { + forEachExternalModuleToImportFrom(program, host, preferences, /*useAutoImportProvider*/ true, function (moduleSymbol, moduleFile, program, isFromPackageJson) { if (++moduleCount % 100 === 0) cancellationToken === null || cancellationToken === void 0 ? void 0 : cancellationToken.throwIfCancellationRequested(); var seenExports = new ts.Map(); @@ -418478,6 +420703,26 @@ var ts; (function (Completions) { var StringCompletions; (function (StringCompletions) { + var _a; + var kindPrecedence = (_a = {}, + _a["directory" /* ScriptElementKind.directory */] = 0, + _a["script" /* ScriptElementKind.scriptElement */] = 1, + _a["external module name" /* ScriptElementKind.externalModuleName */] = 2, + _a); + function createNameAndKindSet() { + var map = new ts.Map(); + function add(value) { + var existing = map.get(value.name); + if (!existing || kindPrecedence[existing.kind] < kindPrecedence[value.kind]) { + map.set(value.name, value); + } + } + return { + add: add, + has: map.has.bind(map), + values: map.values.bind(map), + }; + } function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); @@ -418581,11 +420826,11 @@ var ts; var parent = walkUpParentheses(node.parent); switch (parent.kind) { case 196 /* SyntaxKind.LiteralType */: { - var grandParent = walkUpParentheses(parent.parent); - switch (grandParent.kind) { + var grandParent_1 = walkUpParentheses(parent.parent); + switch (grandParent_1.kind) { + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: case 178 /* SyntaxKind.TypeReference */: { - var typeReference_1 = grandParent; - var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === typeReference_1; }); + var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === grandParent_1; }); if (typeArgument) { return { kind: 2 /* StringLiteralCompletionKind.Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(typeArgument)), isNewIdentifier: false }; } @@ -418598,7 +420843,7 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - var _a = grandParent, indexType = _a.indexType, objectType = _a.objectType; + var _a = grandParent_1, indexType = _a.indexType, objectType = _a.objectType; if (!ts.rangeContainsPosition(indexType, position)) { return undefined; } @@ -418606,11 +420851,11 @@ var ts; case 200 /* SyntaxKind.ImportType */: return { kind: 0 /* StringLiteralCompletionKind.Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; case 187 /* SyntaxKind.UnionType */: { - if (!ts.isTypeReferenceNode(grandParent.parent)) { + if (!ts.isTypeReferenceNode(grandParent_1.parent)) { return undefined; } - var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(grandParent, parent); - var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(grandParent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(grandParent_1, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(grandParent_1)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); return { kind: 2 /* StringLiteralCompletionKind.Types */, types: types, isNewIdentifier: false }; } default: @@ -418759,11 +421004,12 @@ var ts; } function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences) { var literalValue = ts.normalizeSlashes(node.text); + var mode = ts.isStringLiteralLike(node) ? ts.getModeForUsageLocation(sourceFile, node) : undefined; var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, getIncludeExtensionOption()) - : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, compilerOptions, host, getIncludeExtensionOption(), typeChecker); function getIncludeExtensionOption() { var mode = ts.isStringLiteralLike(node) ? ts.getModeForUsageLocation(sourceFile, node) : undefined; return preferences.importModuleSpecifierEnding === "js" || mode === ts.ModuleKind.ESNext ? 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */ : 0 /* IncludeExtensionsOption.Exclude */; @@ -418779,7 +421025,7 @@ var ts; return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); + return ts.arrayFrom(getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath).values()); } } function isEmitResolutionKindUsingNodeModules(compilerOptions) { @@ -418815,7 +421061,7 @@ var ts; var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); - return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); }); + return ts.flatMap(baseDirectories, function (baseDirectory) { return ts.arrayFrom(getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude).values()); }); } var IncludeExtensionsOption; (function (IncludeExtensionsOption) { @@ -418826,9 +421072,9 @@ var ts; /** * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. */ - function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) { - var extensions = _a.extensions, includeExtensionsOption = _a.includeExtensionsOption; - if (result === void 0) { result = []; } + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensionOptions, host, exclude, result) { + var _a; + if (result === void 0) { result = createNameAndKindSet(); } if (fragment === undefined) { fragment = ""; } @@ -418844,92 +421090,124 @@ var ts; fragment = "." + ts.directorySeparator; } fragment = ts.ensureTrailingDirectorySeparator(fragment); - // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths var absolutePath = ts.resolvePath(scriptPath, fragment); var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); + // check for a version redirect + var packageJsonPath = ts.findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionPaths = (_a = ts.getPackageJsonTypesVersionsPaths(typesVersions)) === null || _a === void 0 ? void 0 : _a.paths; + if (versionPaths) { + var packageDirectory = ts.getDirectoryPath(packageJsonPath); + var pathInPackage = absolutePath.slice(ts.ensureTrailingDirectorySeparator(packageDirectory).length); + if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, host, versionPaths)) { + // A true result means one of the `versionPaths` was matched, which will block relative resolution + // to files and folders from here. All reachable paths given the pattern match are already added. + return result; + } + } + } + } var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (!ts.tryDirectoryExists(host, baseDirectory)) return result; // Enumerate the available files if possible - var files = ts.tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + var files = ts.tryReadDirectory(host, baseDirectory, extensionOptions.extensions, /*exclude*/ undefined, /*include*/ ["./*"]); if (files) { - /** - * Multiple file entries might map to the same truncated name once we remove extensions - * (happens iff includeExtensionsOption === includeExtensionsOption.Exclude) so we use a set-like data structure. Eg: - * - * both foo.ts and foo.tsx become foo - */ - var foundFiles = new ts.Map(); // maps file to its extension for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { var filePath = files_1[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* Comparison.EqualTo */) { continue; } - var foundFileName = void 0; - var outputExtension = ts.moduleSpecifiers.tryGetJSExtensionForFile(filePath, host.getCompilationSettings()); - if (includeExtensionsOption === 0 /* IncludeExtensionsOption.Exclude */ && !ts.fileExtensionIsOneOf(filePath, [".json" /* Extension.Json */, ".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */])) { - foundFileName = ts.removeFileExtension(ts.getBaseFileName(filePath)); - foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); - } - else if ((ts.fileExtensionIsOneOf(filePath, [".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */]) || includeExtensionsOption === 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */) && outputExtension) { - foundFileName = ts.changeExtension(ts.getBaseFileName(filePath), outputExtension); - foundFiles.set(foundFileName, outputExtension); - } - else { - foundFileName = ts.getBaseFileName(filePath); - foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); - } + var _b = getFilenameWithExtensionOption(ts.getBaseFileName(filePath), host.getCompilationSettings(), extensionOptions.includeExtensionsOption), name = _b.name, extension = _b.extension; + result.add(nameAndKind(name, "script" /* ScriptElementKind.scriptElement */, extension)); } - foundFiles.forEach(function (ext, foundFile) { - result.push(nameAndKind(foundFile, "script" /* ScriptElementKind.scriptElement */, ext)); - }); } // If possible, get folder completion as well var directories = ts.tryGetDirectories(host, baseDirectory); if (directories) { - for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { - var directory = directories_1[_b]; + for (var _c = 0, directories_1 = directories; _c < directories_1.length; _c++) { + var directory = directories_1[_c]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); if (directoryName !== "@types") { - result.push(directoryResult(directoryName)); - } - } - } - // check for a version redirect - var packageJsonPath = ts.findPackageJson(baseDirectory, host); - if (packageJsonPath) { - var packageJson = ts.readJson(packageJsonPath, host); - var typesVersions = packageJson.typesVersions; - if (typeof typesVersions === "object") { - var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); - var versionPaths = versionResult && versionResult.paths; - var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); - if (versionPaths) { - addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + result.add(directoryResult(directoryName)); } } } return result; } - function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { - for (var path in paths) { - if (!ts.hasProperty(paths, path)) + function getFilenameWithExtensionOption(name, compilerOptions, includeExtensionsOption) { + var outputExtension = ts.moduleSpecifiers.tryGetJSExtensionForFile(name, compilerOptions); + if (includeExtensionsOption === 0 /* IncludeExtensionsOption.Exclude */ && !ts.fileExtensionIsOneOf(name, [".json" /* Extension.Json */, ".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */])) { + return { name: ts.removeFileExtension(name), extension: ts.tryGetExtensionFromPath(name) }; + } + else if ((ts.fileExtensionIsOneOf(name, [".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */]) || includeExtensionsOption === 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */) && outputExtension) { + return { name: ts.changeExtension(name, outputExtension), extension: outputExtension }; + } + else { + return { name: name, extension: ts.tryGetExtensionFromPath(name) }; + } + } + /** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */ + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, host, paths) { + var getPatternsForKey = function (key) { return paths[key]; }; + var comparePaths = function (a, b) { + var patternA = ts.tryParsePattern(a); + var patternB = ts.tryParsePattern(b); + var lengthA = typeof patternA === "object" ? patternA.prefix.length : a.length; + var lengthB = typeof patternB === "object" ? patternB.prefix.length : b.length; + return ts.compareValues(lengthB, lengthA); + }; + return addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, ts.getOwnKeys(paths), getPatternsForKey, comparePaths); + } + /** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */ + function addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, keys, getPatternsForKey, comparePaths) { + var pathResults = []; + var matchedPath; + for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { + var key = keys_1[_i]; + if (key === ".") continue; - var patterns = paths[path]; + var keyWithoutLeadingDotSlash = key.replace(/^\.\//, ""); // remove leading "./" + var patterns = getPatternsForKey(key); if (patterns) { - var _loop_3 = function (name, kind, extension) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind, extension)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_3(name, kind, extension); + var pathPattern = ts.tryParsePattern(keyWithoutLeadingDotSlash); + if (!pathPattern) + continue; + var isMatch = typeof pathPattern === "object" && ts.isPatternMatch(pathPattern, fragment); + var isLongestMatch = isMatch && (matchedPath === undefined || comparePaths(key, matchedPath) === -1 /* Comparison.LessThan */); + if (isLongestMatch) { + // If this is a higher priority match than anything we've seen so far, previous results from matches are invalid, e.g. + // for `import {} from "some-package/|"` with a typesVersions: + // { + // "bar/*": ["bar/*"], // <-- 1. We add 'bar', but 'bar/*' doesn't match yet. + // "*": ["dist/*"], // <-- 2. We match here and add files from dist. 'bar' is still ok because it didn't come from a match. + // "foo/*": ["foo/*"] // <-- 3. We matched '*' earlier and added results from dist, but if 'foo/*' also matched, + // } results in dist would not be visible. 'bar' still stands because it didn't come from a match. + // This is especially important if `dist/foo` is a folder, because if we fail to clear results + // added by the '*' match, after typing `"some-package/foo/|"` we would get file results from both + // ./dist/foo and ./foo, when only the latter will actually be resolvable. + // See pathCompletionsTypesVersionsWildcard6.ts. + matchedPath = key; + pathResults = pathResults.filter(function (r) { return !r.matchedPattern; }); + } + if (typeof pathPattern === "string" || matchedPath === undefined || comparePaths(key, matchedPath) !== 1 /* Comparison.GreaterThan */) { + pathResults.push({ + matchedPattern: isMatch, + results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, host) + .map(function (_a) { + var name = _a.name, kind = _a.kind, extension = _a.extension; + return nameAndKind(name, kind, extension); + }), + }); } } } + pathResults.forEach(function (pathResult) { return pathResult.results.forEach(function (r) { return result.add(r); }); }); + return matchedPath !== undefined; } /** * Check all of the declared modules and those in node modules. Possible sources of modules: @@ -418938,22 +421216,22 @@ var ts; * Modules from node_modules (i.e. those listed in package.json) * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions */ - function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, compilerOptions, host, includeExtensionsOption, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; - var result = []; - var extensionOptions = getExtensionOptions(compilerOptions); + var result = createNameAndKindSet(); + var extensionOptions = getExtensionOptions(compilerOptions, includeExtensionsOption); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); if (paths) { - addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, host, paths); } } var fragmentDirectory = getFragmentDirectory(fragment); for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { var ambientName = _a[_i]; - result.push(nameAndKind(ambientName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); + result.add(nameAndKind(ambientName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); if (isEmitResolutionKindUsingNodeModules(compilerOptions)) { @@ -418961,15 +421239,13 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_4 = function (moduleName) { - if (!result.some(function (entry) { return entry.name === moduleName; })) { - foundGlobal = true; - result.push(nameAndKind(moduleName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); - } - }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_4(moduleName); + var moduleResult = nameAndKind(moduleName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined); + if (!result.has(moduleResult.name)) { + foundGlobal = true; + result.add(moduleResult); + } } } if (!foundGlobal) { @@ -418995,39 +421271,19 @@ var ts; } packagePath = ts.combinePaths(packagePath, subName); } - var packageFile = ts.combinePaths(ancestor, "node_modules", packagePath, "package.json"); + var packageDirectory = ts.combinePaths(ancestor, "node_modules", packagePath); + var packageFile = ts.combinePaths(packageDirectory, "package.json"); if (ts.tryFileExists(host, packageFile)) { var packageJson = ts.readJson(packageFile, host); - var exports = packageJson.exports; - if (exports) { - if (typeof exports !== "object" || exports === null) { // eslint-disable-line no-null/no-null + var exports_1 = packageJson.exports; + if (exports_1) { + if (typeof exports_1 !== "object" || exports_1 === null) { // eslint-disable-line no-null/no-null return; // null exports or entrypoint only, no sub-modules available } - var keys = ts.getOwnKeys(exports); - var fragmentSubpath_1 = components.join("/"); - var processedKeys = ts.mapDefined(keys, function (k) { - if (k === ".") - return undefined; - if (!ts.startsWith(k, "./")) - return undefined; - var subpath = k.substring(2); - if (!ts.startsWith(subpath, fragmentSubpath_1)) - return undefined; - // subpath is a valid export (barring conditions, which we don't currently check here) - if (!ts.stringContains(subpath, "*")) { - return subpath; - } - // pattern export - only return everything up to the `*`, so the user can autocomplete, then - // keep filling in the pattern (we could speculatively return a list of options by hitting disk, - // but conditions will make that somewhat awkward, as each condition may have a different set of possible - // options for the `*`. - return subpath.slice(0, subpath.indexOf("*")); - }); - ts.forEach(processedKeys, function (k) { - if (k) { - result.push(nameAndKind(k, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); - } - }); + var keys = ts.getOwnKeys(exports_1); + var fragmentSubpath = components.join("/") + (components.length && ts.hasTrailingDirectorySeparator(fragment) ? "/" : ""); + var conditions_1 = mode === ts.ModuleKind.ESNext ? ["node", "import", "types"] : ["node", "require", "types"]; + addCompletionEntriesFromPathsOrExports(result, fragmentSubpath, packageDirectory, extensionOptions, host, keys, function (key) { return ts.singleElementArray(getPatternFromFirstMatchingCondition(exports_1[key], conditions_1)); }, ts.comparePatternKeys); return; } } @@ -419037,26 +421293,44 @@ var ts; ts.forEachAncestorDirectory(scriptPath, ancestorLookup); } } - return result; + return ts.arrayFrom(result.values()); + } + function getPatternFromFirstMatchingCondition(target, conditions) { + if (typeof target === "string") { + return target; + } + if (target && typeof target === "object" && !ts.isArray(target)) { + for (var condition in target) { + if (condition === "default" || conditions.indexOf(condition) > -1 || ts.isApplicableVersionedTypesKey(conditions, condition)) { + var pattern = target[condition]; + return getPatternFromFirstMatchingCondition(pattern, conditions); + } + } + } } function getFragmentDirectory(fragment) { return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; } - function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. - return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray; + return !ts.stringContains(path, "*") ? justPathMappingName(path, "script" /* ScriptElementKind.scriptElement */) : ts.emptyArray; } var pathPrefix = path.slice(0, path.length - 1); var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix); - return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) { - return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); - }); - function justPathMappingName(name) { - return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray; + if (remainingFragment === undefined) { + var starIsFullPathComponent = path[path.length - 2] === "/"; + return starIsFullPathComponent ? justPathMappingName(pathPrefix, "directory" /* ScriptElementKind.directory */) : ts.flatMap(patterns, function (pattern) { var _a; return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, host)) === null || _a === void 0 ? void 0 : _a.map(function (_a) { + var name = _a.name, rest = __rest(_a, ["name"]); + return (__assign({ name: pathPrefix + name }, rest)); + }); }); + } + return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, host); }); + function justPathMappingName(name, kind) { + return ts.startsWith(name, fragment) ? [{ name: ts.removeTrailingDirectorySeparator(name), kind: kind, extension: undefined }] : ts.emptyArray; } } - function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { + function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, host) { if (!host.readDirectory) { return undefined; } @@ -419075,21 +421349,33 @@ var ts; var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". - var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var baseDirectory = ts.normalizePath(ts.combinePaths(packageDirectory, expandedPrefixDirectory)); var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - // If we have a suffix, then we need to read the directory all the way down. We could create a glob - // that encodes the suffix, but we would have to escape the character "?" which readDirectory - // doesn't support. For now, this is safer but slower - var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = ts.mapDefined(ts.tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) { - var extension = ts.tryGetExtensionFromPath(match); - var name = trimPrefixAndSuffix(match); - return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* ScriptElementKind.scriptElement */, extension); - }); - var directories = ts.mapDefined(ts.tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) { - var name = trimPrefixAndSuffix(dir); - return name === undefined ? undefined : directoryResult(name); + // If we have a suffix, then we read the directory all the way down to avoid returning completions for + // directories that don't contain files that would match the suffix. A previous comment here was concerned + // about the case where `normalizedSuffix` includes a `?` character, which should be interpreted literally, + // but will match any single character as part of the `include` pattern in `tryReadDirectory`. This is not + // a problem, because (in the extremely unusual circumstance where the suffix has a `?` in it) a `?` + // interpreted as "any character" can only return *too many* results as compared to the literal + // interpretation, so we can filter those superfluous results out via `trimPrefixAndSuffix` as we've always + // done. + var includeGlob = normalizedSuffix ? "**/*" + normalizedSuffix : "./*"; + var matches = ts.mapDefined(ts.tryReadDirectory(host, baseDirectory, extensionOptions.extensions, /*exclude*/ undefined, [includeGlob]), function (match) { + var trimmedWithPattern = trimPrefixAndSuffix(match); + if (trimmedWithPattern) { + if (containsSlash(trimmedWithPattern)) { + return directoryResult(ts.getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]); + } + var _a = getFilenameWithExtensionOption(trimmedWithPattern, host.getCompilationSettings(), extensionOptions.includeExtensionsOption), name = _a.name, extension = _a.extension; + return nameAndKind(name, "script" /* ScriptElementKind.scriptElement */, extension); + } }); + // If we had a suffix, we already recursively searched for all possible files that could match + // it and returned the directories leading to those files. Otherwise, assume any directory could + // have something valid to import. + var directories = normalizedSuffix + ? ts.emptyArray + : ts.mapDefined(ts.tryGetDirectories(host, baseDirectory), function (dir) { return dir === "node_modules" ? undefined : directoryResult(dir); }); return __spreadArray(__spreadArray([], matches, true), directories, true); function trimPrefixAndSuffix(path) { var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix); @@ -419132,10 +421418,10 @@ var ts; var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, 1 /* IncludeExtensionsOption.Include */), host, sourceFile.path) : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) : ts.Debug.fail(); - return addReplacementSpans(toComplete, range.pos + prefix.length, names); + return addReplacementSpans(toComplete, range.pos + prefix.length, ts.arrayFrom(names.values())); } function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) { - if (result === void 0) { result = []; } + if (result === void 0) { result = createNameAndKindSet(); } // Check for typings specified in compiler options var seen = new ts.Map(); var typeRoots = ts.tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; @@ -419160,7 +421446,7 @@ var ts; continue; if (fragmentDirectory === undefined) { if (!seen.has(packageName)) { - result.push(nameAndKind(packageName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); + result.add(nameAndKind(packageName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); seen.set(packageName, true); } } @@ -419496,7 +421782,7 @@ var ts; if (!previousResponse) return undefined; var lowerCaseTokenText = location.text.toLowerCase(); - var exportMap = ts.getExportInfoMap(file, host, program, cancellationToken); + var exportMap = ts.getExportInfoMap(file, host, program, preferences, cancellationToken); var newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, ts.codefix.createImportSpecifierResolver(file, program, host, preferences), program, location.getStart(), preferences, /*isForImportStatementCompletion*/ false, ts.isValidTypeOnlyAliasUseSite(location), function (context) { var entries = ts.mapDefined(previousResponse.entries, function (entry) { @@ -419581,37 +421867,36 @@ var ts; } } var entries = ts.createSortedArray(); - if (isUncheckedFile(sourceFile, compilerOptions)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); - getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); - } - else { - if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* KeywordCompletionFilters.None */) { - return undefined; - } - getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); + var isChecked = isCheckedFile(sourceFile, compilerOptions); + if (isChecked && !isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* KeywordCompletionFilters.None */) { + return undefined; } + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); if (keywordFilters !== 0 /* KeywordCompletionFilters.None */) { - var entryNames_1 = new ts.Set(entries.map(function (e) { return e.name; })); for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) { var keywordEntry = _a[_i]; - if (isTypeOnlyLocation && ts.isTypeKeyword(ts.stringToToken(keywordEntry.name)) || !entryNames_1.has(keywordEntry.name)) { + if (isTypeOnlyLocation && ts.isTypeKeyword(ts.stringToToken(keywordEntry.name)) || !uniqueNames.has(keywordEntry.name)) { + uniqueNames.add(keywordEntry.name); ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); } } } - var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); for (var _b = 0, _c = getContextualKeywords(contextToken, position); _b < _c.length; _b++) { var keywordEntry = _c[_b]; - if (!entryNames.has(keywordEntry.name)) { + if (!uniqueNames.has(keywordEntry.name)) { + uniqueNames.add(keywordEntry.name); ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); } } for (var _d = 0, literals_1 = literals; _d < literals_1.length; _d++) { var literal = literals_1[_d]; - ts.insertSorted(entries, createCompletionEntryForLiteral(sourceFile, preferences, literal), compareCompletionEntries, /*allowDuplicates*/ true); + var literalEntry = createCompletionEntryForLiteral(sourceFile, preferences, literal); + uniqueNames.add(literalEntry.name); + ts.insertSorted(entries, literalEntry, compareCompletionEntries, /*allowDuplicates*/ true); + } + if (!isChecked) { + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); } return { flags: completionData.flags, @@ -419623,8 +421908,8 @@ var ts; entries: entries, }; } - function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + function isCheckedFile(sourceFile, compilerOptions) { + return !ts.isSourceFileJS(sourceFile) || !!ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -419993,7 +422278,7 @@ var ts; span = ts.createTextSpanFromNode(contextToken); } if (ts.isPropertyDeclaration(contextToken.parent)) { - modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers); + modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers) & 125951 /* ModifierFlags.Modifier */; span = ts.createTextSpanFromNode(contextToken.parent); } return { modifiers: modifiers, span: span }; @@ -420053,7 +422338,7 @@ var ts; var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var quotePreference = ts.getQuotePreference(sourceFile, preferences); - var builderFlags = quotePreference === 0 /* QuotePreference.Single */ ? 268435456 /* NodeBuilderFlags.UseSingleQuotesForStringLiteralType */ : undefined; + var builderFlags = 33554432 /* NodeBuilderFlags.OmitThisParameter */ | (quotePreference === 0 /* QuotePreference.Single */ ? 268435456 /* NodeBuilderFlags.UseSingleQuotesForStringLiteralType */ : 0 /* NodeBuilderFlags.None */); switch (declaration.kind) { case 166 /* SyntaxKind.PropertySignature */: case 167 /* SyntaxKind.PropertyDeclaration */: @@ -420092,12 +422377,10 @@ var ts; } var parameters = typeNode.parameters.map(function (typedParam) { return ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, typedParam.dotDotDotToken, typedParam.name, typedParam.questionToken, /*type*/ undefined, typedParam.initializer); }); return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, @@ -420584,7 +422867,7 @@ var ts; } function getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, detailsEntryId, host, formatContext, cancellationToken) { var typeChecker = program.getTypeChecker(); - var inUncheckedFile = isUncheckedFile(sourceFile, compilerOptions); + var inCheckedFile = isCheckedFile(sourceFile, compilerOptions); var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -421000,15 +423283,7 @@ var ts; isNewIdentifierLocation = true; } var propertyAccess = node.kind === 200 /* SyntaxKind.ImportType */ ? node : node.parent; - if (inUncheckedFile) { - // In javascript files, for union types, we don't just get the members that - // the individual types have in common, we also include all the members that - // each individual type has. This is because we're going to add all identifiers - // anyways. So we might as well elevate the members that were at least part - // of the individual types to a higher status since we know what they are. - symbols.push.apply(symbols, ts.filter(getPropertiesForCompletion(type, typeChecker), function (s) { return typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s); })); - } - else { + if (inCheckedFile) { for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) { @@ -421016,6 +423291,14 @@ var ts; } } } + else { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + symbols.push.apply(symbols, ts.filter(getPropertiesForCompletion(type, typeChecker), function (s) { return typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s); })); + } if (insertAwait && preferences.includeCompletionsWithInsertText) { var promiseType = typeChecker.getPromisedTypeOfPromise(type); if (promiseType) { @@ -421207,7 +423490,7 @@ var ts; } // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 305 /* SyntaxKind.SourceFile */) { - var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); + var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false, ts.isClassLike(scopeNode.parent) ? scopeNode : undefined); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { var symbol = _a[_i]; @@ -421310,7 +423593,7 @@ var ts; previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; var moduleSpecifierCache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); - var exportInfo = ts.getExportInfoMap(sourceFile, host, program, cancellationToken); + var exportInfo = ts.getExportInfoMap(sourceFile, host, program, preferences, cancellationToken); var packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) === null || _b === void 0 ? void 0 : _b.call(host); var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, preferences, host); resolvingModuleSpecifiers("collectAutoImports", host, importSpecifierResolver || (importSpecifierResolver = ts.codefix.createImportSpecifierResolver(sourceFile, program, host, preferences)), program, position, preferences, !!importCompletionNode, ts.isValidTypeOnlyAliasUseSite(location), function (context) { @@ -422410,6 +424693,7 @@ var ts; return kind === 131 /* SyntaxKind.AsyncKeyword */ || kind === 132 /* SyntaxKind.AwaitKeyword */ || kind === 127 /* SyntaxKind.AsKeyword */ + || kind === 152 /* SyntaxKind.TypeKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { @@ -422509,6 +424793,10 @@ var ts; } break; case 79 /* SyntaxKind.Identifier */: { + var originalKeywordKind = location.originalKeywordKind; + if (originalKeywordKind && ts.isKeyword(originalKeywordKind)) { + return undefined; + } // class c { public prop = c| } if (ts.isPropertyDeclaration(location.parent) && location.parent.initializer === location) { return undefined; @@ -423296,60 +425584,64 @@ var ts; } return settingsOrHost; } - function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings)); - return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions); } - function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); + function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind, languageVersionOrOptions); } - function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings)); - return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions); } - function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, getCompilationSettings(compilationSettings), key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); + function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { + return acquireOrUpdateDocument(fileName, path, getCompilationSettings(compilationSettings), key, scriptSnapshot, version, /*acquiring*/ false, scriptKind, languageVersionOrOptions); } function getDocumentRegistryEntry(bucketEntry, scriptKind) { var entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(ts.Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided")); ts.Debug.assert(scriptKind === undefined || !entry || entry.sourceFile.scriptKind === scriptKind, "Script kind should match provided ScriptKind:".concat(scriptKind, " and sourceFile.scriptKind: ").concat(entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind, ", !entry: ").concat(!entry)); return entry; } - function acquireOrUpdateDocument(fileName, path, compilationSettingsOrHost, key, scriptSnapshot, version, acquiring, scriptKind) { + function acquireOrUpdateDocument(fileName, path, compilationSettingsOrHost, key, scriptSnapshot, version, acquiring, scriptKind, languageVersionOrOptions) { var _a, _b, _c, _d; scriptKind = ts.ensureScriptKind(fileName, scriptKind); var compilationSettings = getCompilationSettings(compilationSettingsOrHost); var host = compilationSettingsOrHost === compilationSettings ? undefined : compilationSettingsOrHost; var scriptTarget = scriptKind === 6 /* ScriptKind.JSON */ ? 100 /* ScriptTarget.JSON */ : ts.getEmitScriptTarget(compilationSettings); - var sourceFileOptions = { - languageVersion: scriptTarget, - impliedNodeFormat: host && ts.getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getModuleResolutionCache) === null || _c === void 0 ? void 0 : _c.call(_b)) === null || _d === void 0 ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings), - setExternalModuleIndicator: ts.getSetExternalModuleIndicator(compilationSettings) - }; + var sourceFileOptions = typeof languageVersionOrOptions === "object" ? + languageVersionOrOptions : + { + languageVersion: scriptTarget, + impliedNodeFormat: host && ts.getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getModuleResolutionCache) === null || _c === void 0 ? void 0 : _c.call(_b)) === null || _d === void 0 ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings), + setExternalModuleIndicator: ts.getSetExternalModuleIndicator(compilationSettings) + }; + sourceFileOptions.languageVersion = scriptTarget; var oldBucketCount = buckets.size; - var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + var keyWithMode = getDocumentRegistryBucketKeyWithMode(key, sourceFileOptions.impliedNodeFormat); + var bucket = ts.getOrUpdate(buckets, keyWithMode, function () { return new ts.Map(); }); if (ts.tracing) { if (buckets.size > oldBucketCount) { // It is interesting, but not definitively problematic if a build requires multiple document registry buckets - // perhaps they are for two projects that don't have any overlap. // Bonus: these events can help us interpret the more interesting event below. - ts.tracing.instant("session" /* tracing.Phase.Session */, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: key }); + ts.tracing.instant("session" /* tracing.Phase.Session */, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: keyWithMode }); } // It is fairly suspicious to have one path in two buckets - you'd expect dependencies to have similar configurations. // If this occurs unexpectedly, the fix is likely to synchronize the project settings. // Skip .d.ts files to reduce noise (should also cover most of node_modules). var otherBucketKey = !ts.isDeclarationFileName(path) && - ts.forEachEntry(buckets, function (bucket, bucketKey) { return bucketKey !== key && bucket.has(path) && bucketKey; }); + ts.forEachEntry(buckets, function (bucket, bucketKey) { return bucketKey !== keyWithMode && bucket.has(path) && bucketKey; }); if (otherBucketKey) { - ts.tracing.instant("session" /* tracing.Phase.Session */, "documentRegistryBucketOverlap", { path: path, key1: otherBucketKey, key2: key }); + ts.tracing.instant("session" /* tracing.Phase.Session */, "documentRegistryBucketOverlap", { path: path, key1: otherBucketKey, key2: keyWithMode }); } } var bucketEntry = bucket.get(path); var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { - var sourceFile = externalCache.getDocument(key, path); + var sourceFile = externalCache.getDocument(keyWithMode, path); if (sourceFile) { ts.Debug.assert(acquiring); entry = { @@ -423363,7 +425655,7 @@ var ts; // Have never seen this file with these settings. Create a new source file for it. var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, sourceFileOptions, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { - externalCache.setDocument(key, path, sourceFile); + externalCache.setDocument(keyWithMode, path, sourceFile); } entry = { sourceFile: sourceFile, @@ -423378,7 +425670,7 @@ var ts; if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 if (externalCache) { - externalCache.setDocument(key, path, entry.sourceFile); + externalCache.setDocument(keyWithMode, path, entry.sourceFile); } } // If we're acquiring, then this is the first time this LS is asking for this document. @@ -423407,13 +425699,13 @@ var ts; } } } - function releaseDocument(fileName, compilationSettings, scriptKind) { + function releaseDocument(fileName, compilationSettings, scriptKind, impliedNodeFormat) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key, scriptKind); + return releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat); } - function releaseDocumentWithKey(path, key, scriptKind) { - var bucket = ts.Debug.checkDefined(buckets.get(key)); + function releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat) { + var bucket = ts.Debug.checkDefined(buckets.get(getDocumentRegistryBucketKeyWithMode(key, impliedNodeFormat))); var bucketEntry = bucket.get(path); var entry = getDocumentRegistryEntry(bucketEntry, scriptKind); entry.languageServiceRefCount--; @@ -423461,7 +425753,7 @@ var ts; } var str = "{"; for (var key in value) { - if (ts.hasOwnProperty.call(value, key)) { // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier + if (ts.hasProperty(value, key)) { str += "".concat(key, ": ").concat(compilerOptionValueToString(value[key])); } } @@ -423470,6 +425762,9 @@ var ts; function getKeyForCompilationSettings(settings) { return ts.sourceFileAffectingCompilerOptions.map(function (option) { return compilerOptionValueToString(ts.getCompilerOptionValue(settings, option)); }).join("|") + (settings.pathsBasePath ? "|".concat(settings.pathsBasePath) : undefined); } + function getDocumentRegistryBucketKeyWithMode(key, mode) { + return (mode ? "".concat(key, "|").concat(mode) : key); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -423602,7 +425897,7 @@ var ts; return ts.findAncestor(node, function (node) { if (stopAtAmbientModule && isAmbientModuleDeclaration(node)) return "quit"; - return ts.some(node.modifiers, function (mod) { return mod.kind === 93 /* SyntaxKind.ExportKeyword */; }); + return ts.canHaveModifiers(node) && ts.some(node.modifiers, ts.isExportModifier); }); } function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { @@ -424285,18 +426580,18 @@ var ts; || node.kind === 106 /* SyntaxKind.SuperKeyword */) { referenceEntries = entries && __spreadArray([], entries, true); } - else { - var queue = entries && __spreadArray([], entries, true); + else if (entries) { + var queue = ts.createQueue(entries); var seenNodes = new ts.Map(); - while (queue && queue.length) { - var entry = queue.shift(); + while (!queue.isEmpty()) { + var entry = queue.dequeue(); if (!ts.addToSeen(seenNodes, ts.getNodeId(entry.node))) { continue; } referenceEntries = ts.append(referenceEntries, entry); var entries_1 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos); if (entries_1) { - queue.push.apply(queue, entries_1); + queue.enqueue.apply(queue, entries_1); } } } @@ -424552,6 +426847,7 @@ var ts; var commonjsSource = source && ts.isBinaryExpression(source) ? source.left : undefined; return !!(source && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === source || d === commonjsSource; }))); } + FindAllReferences.isDeclarationOfSymbol = isDeclarationOfSymbol; /** * True if 'decl' provides a value, as in `function f() {}`; * false if 'decl' is just a location for a future write, as in 'let x;' @@ -424758,7 +427054,7 @@ var ts; result = references; continue; } - var _loop_5 = function (entry) { + var _loop_3 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* DefinitionKind.Symbol */) { result.push(entry); return "continue"; @@ -424790,7 +427086,7 @@ var ts; }; for (var _b = 0, references_2 = references; _b < references_2.length; _b++) { var entry = references_2[_b]; - _loop_5(entry); + _loop_3(entry); } } return result; @@ -426371,8 +428667,8 @@ var ts; var declarations; if (symbol && symbol.declarations) { var indices = ts.indicesOf(symbol.declarations); - var keys_1 = ts.map(symbol.declarations, function (decl) { return ({ file: decl.getSourceFile().fileName, pos: decl.pos }); }); - indices.sort(function (a, b) { return ts.compareStringsCaseSensitive(keys_1[a].file, keys_1[b].file) || keys_1[a].pos - keys_1[b].pos; }); + var keys_2 = ts.map(symbol.declarations, function (decl) { return ({ file: decl.getSourceFile().fileName, pos: decl.pos }); }); + indices.sort(function (a, b) { return ts.compareStringsCaseSensitive(keys_2[a].file, keys_2[b].file) || keys_2[a].pos - keys_2[b].pos; }); var sortedDeclarations = ts.map(indices, function (i) { return symbol.declarations[i]; }); var lastDecl = void 0; for (var _i = 0, sortedDeclarations_1 = sortedDeclarations; _i < sortedDeclarations_1.length; _i++) { @@ -426642,14 +428938,16 @@ var ts; collect(node.body); } function collectCallSitesOfClassLikeDeclaration(node, collect) { - ts.forEach(node.decorators, collect); + ts.forEach(node.modifiers, collect); var heritage = ts.getClassExtendsHeritageElement(node); if (heritage) { collect(heritage.expression); } for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - ts.forEach(member.decorators, collect); + if (ts.canHaveModifiers(member)) { + ts.forEach(member.modifiers, collect); + } if (ts.isPropertyDeclaration(member)) { collect(member.initializer); } @@ -426818,7 +429116,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_6 = function (sourceFile) { + var _loop_4 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.fileName); var newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -426850,7 +429148,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_6(sourceFile); + _loop_4(sourceFile); } } function combineNormal(pathA, pathB) { @@ -426955,7 +429253,7 @@ var ts; } var parent = node.parent; var typeChecker = program.getTypeChecker(); - if (node.kind === 159 /* SyntaxKind.OverrideKeyword */ || (ts.isJSDocOverrideTag(node) && ts.rangeContainsPosition(node.tagName, position))) { + if (node.kind === 159 /* SyntaxKind.OverrideKeyword */ || (ts.isIdentifier(node) && ts.isJSDocOverrideTag(parent) && parent.tagName === node)) { return getDefinitionFromOverriddenMember(typeChecker, node) || ts.emptyArray; } // Labels @@ -427492,11 +429790,12 @@ var ts; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var jsdoc = _a[_i]; + var inheritDoc = ts.isJSDoc(jsdoc) && jsdoc.tags && ts.find(jsdoc.tags, function (t) { return t.kind === 327 /* SyntaxKind.JSDocTag */ && (t.tagName.escapedText === "inheritDoc" || t.tagName.escapedText === "inheritdoc"); }); // skip comments containing @typedefs since they're not associated with particular declarations // Exceptions: // - @typedefs are themselves declarations with associated comments // - @param or @return indicate that the author thinks of it as a 'local' @typedef that's part of the function documentation - if (jsdoc.comment === undefined + if (jsdoc.comment === undefined && !inheritDoc || ts.isJSDoc(jsdoc) && declaration.kind !== 345 /* SyntaxKind.JSDocTypedefTag */ && declaration.kind !== 338 /* SyntaxKind.JSDocCallbackTag */ && jsdoc.tags @@ -427504,7 +429803,10 @@ var ts; && !jsdoc.tags.some(function (t) { return t.kind === 340 /* SyntaxKind.JSDocParameterTag */ || t.kind === 341 /* SyntaxKind.JSDocReturnTag */; })) { continue; } - var newparts = getDisplayPartsFromComment(jsdoc.comment, checker); + var newparts = jsdoc.comment ? getDisplayPartsFromComment(jsdoc.comment, checker) : []; + if (inheritDoc && inheritDoc.comment) { + newparts = newparts.concat(getDisplayPartsFromComment(inheritDoc.comment, checker)); + } if (!ts.contains(parts, newparts, isIdenticalListOfDisplayParts)) { parts.push(newparts); } @@ -427738,8 +430040,12 @@ var ts; return undefined; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters, hasReturn = commentOwnerInfo.hasReturn; - var commentOwnerJSDoc = ts.hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? ts.lastOrUndefined(commentOwner.jsDoc) : undefined; - if (commentOwner.getStart(sourceFile) < position || commentOwnerJSDoc && commentOwnerJSDoc !== existingDocComment) { + var commentOwnerJsDoc = ts.hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? commentOwner.jsDoc : undefined; + var lastJsDoc = ts.lastOrUndefined(commentOwnerJsDoc); + if (commentOwner.getStart(sourceFile) < position + || lastJsDoc + && existingDocComment + && lastJsDoc !== existingDocComment) { return undefined; } var indentationStr = getIndentationStringAtPosition(sourceFile, position); @@ -427756,7 +430062,9 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var openComment = "/**"; var closeComment = " */"; - if (tags) { + // If any of the existing jsDoc has tags, ignore adding new ones. + var hasTag = (commentOwnerJsDoc || []).some(function (jsDoc) { return !!jsDoc.tags; }); + if (tags && !hasTag) { var preamble = openComment + newLine + indentationStr + " * "; var endLine = tokenStart === position ? newLine + indentationStr : ""; var result = preamble + newLine + tags + indentationStr + closeComment + endLine; @@ -427870,7 +430178,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_7 = function (sourceFile) { + var _loop_5 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -427882,7 +430190,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var sourceFile = sourceFiles_4[_i]; - _loop_7(sourceFile); + _loop_5(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -428478,7 +430786,7 @@ var ts; isPossibleConstructor(b.node) ? b.node : undefined; if (ctorFunction !== undefined) { - var ctorNode = ts.setTextRange(ts.factory.createConstructorDeclaration(/* decorators */ undefined, /* modifiers */ undefined, [], /* body */ undefined), ctorFunction); + var ctorNode = ts.setTextRange(ts.factory.createConstructorDeclaration(/* modifiers */ undefined, [], /* body */ undefined), ctorFunction); var ctor = emptyNavigationBarNode(ctorNode); ctor.indent = a.indent + 1; ctor.children = a.node === ctorFunction ? a.children : b.children; @@ -428494,7 +430802,6 @@ var ts; } } lastANode = a.node = ts.setTextRange(ts.factory.createClassDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, a.name || ts.factory.createIdentifier("__class__"), /* typeParameters */ undefined, /* heritageClauses */ undefined, []), a.node); @@ -428519,7 +430826,6 @@ var ts; if (!a.additionalNodes) a.additionalNodes = []; a.additionalNodes.push(ts.setTextRange(ts.factory.createClassDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, a.name || ts.factory.createIdentifier("__class__"), /* typeParameters */ undefined, /* heritageClauses */ undefined, []), b.node)); @@ -429028,7 +431334,7 @@ var ts; else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) { // If we’re in a declaration file, it’s safe to remove the import clause from it if (sourceFile.isDeclarationFile) { - usedImports.push(ts.factory.createImportDeclaration(importDecl.decorators, importDecl.modifiers, + usedImports.push(ts.factory.createImportDeclaration(importDecl.modifiers, /*importClause*/ undefined, moduleSpecifier, /*assertClause*/ undefined)); } @@ -429194,7 +431500,7 @@ var ts; newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(exportGroup_1, function (i) { return i.exportClause && ts.isNamedExports(i.exportClause) ? i.exportClause.elements : ts.emptyArray; })); var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); var exportDecl = exportGroup_1[0]; - coalescedExports.push(ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, exportDecl.exportClause && (ts.isNamedExports(exportDecl.exportClause) ? + coalescedExports.push(ts.factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, exportDecl.exportClause && (ts.isNamedExports(exportDecl.exportClause) ? ts.factory.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) : ts.factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)), exportDecl.moduleSpecifier, exportDecl.assertClause)); } @@ -429231,7 +431537,7 @@ var ts; } OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { - return ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), // TODO: GH#18217 + return ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, ts.factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), // TODO: GH#18217 importDeclaration.moduleSpecifier, importDeclaration.assertClause); } function sortSpecifiers(specifiers) { @@ -429947,13 +432253,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_8 = function (start) { + var _loop_6 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_8(start); + var state_3 = _loop_6(start); if (typeof state_3 === "object") return state_3.value; } @@ -430539,10 +432845,10 @@ var ts; (function (ts) { var Rename; (function (Rename) { - function getRenameInfo(program, sourceFile, position, options) { + function getRenameInfo(program, sourceFile, position, preferences) { var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); + var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, preferences); if (renameInfo) { return renameInfo; } @@ -430550,7 +432856,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, program, options) { + function getRenameInfoForNode(node, typeChecker, sourceFile, program, preferences) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (ts.isStringLiteralLike(node)) { @@ -430578,7 +432884,12 @@ var ts; return undefined; } if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { - return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; + return preferences.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; + } + // Disallow rename for elements that would rename across `*/node_modules/*` packages. + var wouldRenameNodeModules = wouldRenameInOtherNodeModules(sourceFile, symbol, typeChecker, preferences); + if (wouldRenameNodeModules) { + return getRenameInfoError(wouldRenameNodeModules); } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) @@ -430592,6 +432903,49 @@ var ts; var sourceFile = declaration.getSourceFile(); return program.isSourceFileDefaultLibrary(sourceFile) && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Extension.Dts */); } + function wouldRenameInOtherNodeModules(originalFile, symbol, checker, preferences) { + if (!preferences.providePrefixAndSuffixTextForRename && symbol.flags & 2097152 /* SymbolFlags.Alias */) { + var importSpecifier = symbol.declarations && ts.find(symbol.declarations, function (decl) { return ts.isImportSpecifier(decl); }); + if (importSpecifier && !importSpecifier.propertyName) { + symbol = checker.getAliasedSymbol(symbol); + } + } + var declarations = symbol.declarations; + if (!declarations) { + return undefined; + } + var originalPackage = getPackagePathComponents(originalFile.path); + if (originalPackage === undefined) { // original source file is not in node_modules + if (ts.some(declarations, function (declaration) { return ts.isInsideNodeModules(declaration.getSourceFile().path); })) { + return ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder; + } + else { + return undefined; + } + } + // original source file is in node_modules + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + var declPackage = getPackagePathComponents(declaration.getSourceFile().path); + if (declPackage) { + var length_2 = Math.min(originalPackage.length, declPackage.length); + for (var i = 0; i <= length_2; i++) { + if (ts.compareStringsCaseSensitive(originalPackage[i], declPackage[i]) !== 0 /* Comparison.EqualTo */) { + return ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder; + } + } + } + } + return undefined; + } + function getPackagePathComponents(filePath) { + var components = ts.getPathComponents(filePath); + var nodeModulesIdx = components.lastIndexOf("node_modules"); + if (nodeModulesIdx === -1) { + return undefined; + } + return components.slice(0, nodeModulesIdx + 2); + } function getRenameInfoForModule(node, sourceFile, moduleSymbol) { if (!ts.isExternalModuleNameRelative(node.text)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); @@ -430662,7 +433016,7 @@ var ts; var SmartSelectionRange; (function (SmartSelectionRange) { function getSmartSelectionRange(pos, sourceFile) { - var _a; + var _a, _b; var selectionRange = { textSpan: ts.createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd()) }; @@ -430714,6 +433068,17 @@ var ts; if (ts.hasJSDocNodes(node) && ((_a = node.jsDoc) === null || _a === void 0 ? void 0 : _a.length)) { pushSelectionRange(ts.first(node.jsDoc).getStart(), end); } + // (#39618 & #49807) + // When the node is a SyntaxList and its first child has a JSDoc comment, then the node's + // `start` (which usually is the result of calling `node.getStart()`) points to the first + // token after the JSDoc comment. So, we have to make sure we'd pushed the selection + // covering the JSDoc comment before diving further. + if (ts.isSyntaxList(node)) { + var firstChild = node.getChildren()[0]; + if (firstChild && ts.hasJSDocNodes(firstChild) && ((_b = firstChild.jsDoc) === null || _b === void 0 ? void 0 : _b.length) && firstChild.getStart() !== node.pos) { + start = Math.min(start, ts.first(firstChild.jsDoc).getStart()); + } + } pushSelectionRange(start, end); // String literals should have a stop both inside and outside their quotes. if (ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) { @@ -430787,6 +433152,7 @@ var ts; * other as well as of other top-level statements and declarations. */ function getSelectionChildren(node) { + var _a; // Group top-level imports if (ts.isSourceFile(node)) { return groupChildren(node.getChildAt(0).getChildren(), isImport); @@ -430802,7 +433168,7 @@ var ts; // because it allows the mapped type to become an object type with a // few keystrokes. if (ts.isMappedTypeNode(node)) { - var _a = node.getChildren(), openBraceToken = _a[0], children = _a.slice(1); + var _b = node.getChildren(), openBraceToken = _b[0], children = _b.slice(1); var closeBraceToken = ts.Debug.checkDefined(children.pop()); ts.Debug.assertEqual(openBraceToken.kind, 18 /* SyntaxKind.OpenBraceToken */); ts.Debug.assertEqual(closeBraceToken.kind, 19 /* SyntaxKind.CloseBraceToken */); @@ -430833,10 +433199,13 @@ var ts; var children = groupChildren(node.getChildren(), function (child) { return child === node.name || ts.contains(node.modifiers, child); }); - return splitChildren(children, function (_a) { + var firstJSDocChild = ((_a = children[0]) === null || _a === void 0 ? void 0 : _a.kind) === 320 /* SyntaxKind.JSDoc */ ? children[0] : undefined; + var withJSDocSeparated = firstJSDocChild ? children.slice(1) : children; + var splittedChildren = splitChildren(withJSDocSeparated, function (_a) { var kind = _a.kind; return kind === 58 /* SyntaxKind.ColonToken */; }); + return firstJSDocChild ? [firstJSDocChild, createSyntaxList(splittedChildren)] : splittedChildren; } // Group the parameter name with its `...`, then that group with its `?`, then pivot on `=`. if (ts.isParameter(node)) { @@ -431372,7 +433741,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_9 = function (n) { + var _loop_7 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: ".concat(ts.Debug.formatSyntaxKind(n.kind), ", parent: ").concat(ts.Debug.formatSyntaxKind(n.parent.kind)); }); @@ -431382,7 +433751,7 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_4 = _loop_9(n); + var state_4 = _loop_7(n); if (typeof state_4 === "object") return state_4.value; } @@ -431581,7 +433950,7 @@ var ts; if (!ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { return; } - if (ts.isTypeNode(node)) { + if (ts.isTypeNode(node) && !ts.isExpressionWithTypeArguments(node)) { return; } if (preferences.includeInlayVariableTypeHints && ts.isVariableDeclaration(node)) { @@ -431646,7 +434015,7 @@ var ts; return type.symbol && (type.symbol.flags & 1536 /* SymbolFlags.Module */); } function visitVariableLikeDeclaration(decl) { - if (!decl.initializer || ts.isBindingPattern(decl.name)) { + if (!decl.initializer || ts.isBindingPattern(decl.name) || ts.isVariableDeclaration(decl) && !isHintableDeclaration(decl)) { return; } var effectiveTypeAnnotation = ts.getEffectiveTypeAnnotationNode(decl); @@ -431659,6 +434028,10 @@ var ts; } var typeDisplayString = printTypeInSingleLine(declarationType); if (typeDisplayString) { + var isVariableNameMatchesType = preferences.includeInlayVariableTypeHintsWhenTypeMatchesName === false && ts.equateStringsCaseInsensitive(decl.name.getText(), typeDisplayString); + if (isVariableNameMatchesType) { + return; + } addTypeHints(typeDisplayString, decl.name.end); } } @@ -431770,6 +434143,9 @@ var ts; } for (var i = 0; i < node.parameters.length && i < signature.parameters.length; ++i) { var param = node.parameters[i]; + if (!isHintableDeclaration(param)) { + continue; + } var effectiveTypeAnnotation = ts.getEffectiveTypeAnnotationNode(param); if (effectiveTypeAnnotation) { continue; @@ -431811,6 +434187,13 @@ var ts; function isUndefined(name) { return name === "undefined"; } + function isHintableDeclaration(node) { + if ((ts.isParameterDeclaration(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) && node.initializer) { + var initializer = ts.skipParentheses(node.initializer); + return !(isHintableLiteral(initializer) || ts.isNewExpression(initializer) || ts.isObjectLiteralExpression(initializer) || ts.isAssertionExpression(initializer)); + } + return true; + } } InlayHints.provideInlayHints = provideInlayHints; })(InlayHints = ts.InlayHints || (ts.InlayHints = {})); @@ -432981,7 +435364,7 @@ var ts; commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_10 = function (opt) { + var _loop_8 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -433000,7 +435383,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_10(opt); + _loop_8(opt); } return options; } @@ -433950,7 +436333,7 @@ var ts; } function isEndOfDecoratorContextOnSameLine(context) { return context.TokensAreOnSameLine() && - !!context.contextNode.decorators && + ts.hasDecorators(context.contextNode) && nodeIsInDecoratorContext(context.currentTokenParent) && !nodeIsInDecoratorContext(context.nextTokenParent); } @@ -434515,6 +436898,7 @@ var ts; var options = _a.options, getRules = _a.getRules, host = _a.host; // formatting context is used by rules provider var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); + var previousRangeTriviaEnd; var previousRange; var previousParent; var previousRangeStartLine; @@ -434525,7 +436909,7 @@ var ts; if (formattingScanner.isOnToken()) { var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line; var undecoratedStartLine = startLine; - if (enclosingNode.decorators) { + if (ts.hasDecorators(enclosingNode)) { undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line; } processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); @@ -434543,10 +436927,30 @@ var ts; } } if (previousRange && formattingScanner.getStartPos() >= originalRange.end) { + // Formatting edits happen by looking at pairs of contiguous tokens (see `processPair`), + // typically inserting or deleting whitespace between them. The recursive `processNode` + // logic above bails out as soon as it encounters a token that is beyond the end of the + // range we're supposed to format (or if we reach the end of the file). But this potentially + // leaves out an edit that would occur *inside* the requested range but cannot be discovered + // without looking at one token *beyond* the end of the range: consider the line `x = { }` + // with a selection from the beginning of the line to the space inside the curly braces, + // inclusive. We would expect a format-selection would delete the space (if rules apply), + // but in order to do that, we need to process the pair ["{", "}"], but we stopped processing + // just before getting there. This block handles this trailing edit. var tokenInfo = formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token : undefined; - if (tokenInfo) { + if (tokenInfo && tokenInfo.pos === previousRangeTriviaEnd) { + // We need to check that tokenInfo and previousRange are contiguous: the `originalRange` + // may have ended in the middle of a token, which means we will have stopped formatting + // on that token, leaving `previousRange` pointing to the token before it, but already + // having moved the formatting scanner (where we just got `tokenInfo`) to the next token. + // If this happens, our supposed pair [previousRange, tokenInfo] actually straddles the + // token that intersects the end of the range we're supposed to format, so the pair will + // produce bogus edits if we try to `processPair`. Recall that the point of this logic is + // to perform a trailing edit at the end of the selection range: but there can be no valid + // edit in the middle of a token where the range ended, so if we have a non-contiguous + // pair here, we're already done and we can ignore it. var parent = ((_b = ts.findPrecedingToken(tokenInfo.end, sourceFile, enclosingNode)) === null || _b === void 0 ? void 0 : _b.parent) || previousParent; processPair(tokenInfo, sourceFile.getLineAndCharacterOfPosition(tokenInfo.pos).line, parent, previousRange, previousRangeStartLine, previousParent, parent, /*dynamicIndentation*/ undefined); @@ -434612,8 +437016,10 @@ var ts; } } function getFirstNonDecoratorTokenOfNode(node) { - if (node.modifiers && node.modifiers.length) { - return node.modifiers[0].kind; + if (ts.canHaveModifiers(node)) { + var modifier = ts.find(node.modifiers, ts.isModifier, ts.findIndex(node.modifiers, ts.isDecorator)); + if (modifier) + return modifier.kind; } switch (node.kind) { case 257 /* SyntaxKind.ClassDeclaration */: return 84 /* SyntaxKind.ClassKeyword */; @@ -434688,7 +437094,6 @@ var ts; case 280 /* SyntaxKind.JsxOpeningElement */: case 281 /* SyntaxKind.JsxClosingElement */: case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: return false; } break; @@ -434702,7 +437107,7 @@ var ts; // if token line equals to the line of containing node (this is a first token in the node) - use node indentation return nodeStartLine !== line // if this token is the first token following the list of decorators, we do not need to indent - && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + && !(ts.hasDecorators(node) && kind === getFirstNonDecoratorTokenOfNode(node)); } function getDelta(child) { // Delta value should be zero when the node explicitly prevents indentation of the child node @@ -434742,13 +437147,14 @@ var ts; consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); } function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) { + ts.Debug.assert(!ts.nodeIsSynthesized(child)); if (ts.nodeIsMissing(child)) { return inheritedIndentation; } var childStartPos = child.getStart(sourceFile); var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; var undecoratedChildStartLine = childStartLine; - if (child.decorators) { + if (ts.hasDecorators(child)) { undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; } // if child is a list item - try to get its indentation, only if parent is within the original range. @@ -434808,6 +437214,7 @@ var ts; } function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { ts.Debug.assert(ts.isNodeArray(nodes)); + ts.Debug.assert(!ts.nodeIsSynthesized(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; @@ -434858,12 +437265,10 @@ var ts; var listEndToken = getCloseTokenForOpenToken(listStartToken); if (listEndToken !== 0 /* SyntaxKind.Unknown */ && formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { var tokenInfo = formattingScanner.readTokenInfo(parent); - if (tokenInfo.token.kind === 27 /* SyntaxKind.CommaToken */ && ts.isCallLikeExpression(parent)) { - var commaTokenLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - if (startLine !== commaTokenLine) { - formattingScanner.advance(); - tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; - } + if (tokenInfo.token.kind === 27 /* SyntaxKind.CommaToken */) { + // consume the comma + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one @@ -434903,6 +437308,7 @@ var ts; } } if (currentTokenInfo.trailingTrivia) { + previousRangeTriviaEnd = ts.last(currentTokenInfo.trailingTrivia).end; processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation); } if (indentToken) { @@ -434973,6 +437379,7 @@ var ts; } } previousRange = range; + previousRangeTriviaEnd = range.end; previousParent = parent; previousRangeStartLine = rangeStart.line; return lineAction; @@ -435264,6 +437671,12 @@ var ts; case 169 /* SyntaxKind.MethodDeclaration */: case 168 /* SyntaxKind.MethodSignature */: case 214 /* SyntaxKind.ArrowFunction */: + case 174 /* SyntaxKind.CallSignature */: + case 175 /* SyntaxKind.ConstructSignature */: + case 179 /* SyntaxKind.FunctionType */: + case 180 /* SyntaxKind.ConstructorType */: + case 172 /* SyntaxKind.GetAccessor */: + case 173 /* SyntaxKind.SetAccessor */: if (node.typeParameters === list) { return 29 /* SyntaxKind.LessThanToken */; } @@ -435280,7 +437693,19 @@ var ts; return 20 /* SyntaxKind.OpenParenToken */; } break; + case 257 /* SyntaxKind.ClassDeclaration */: + case 226 /* SyntaxKind.ClassExpression */: + case 258 /* SyntaxKind.InterfaceDeclaration */: + case 259 /* SyntaxKind.TypeAliasDeclaration */: + if (node.typeParameters === list) { + return 29 /* SyntaxKind.LessThanToken */; + } + break; case 178 /* SyntaxKind.TypeReference */: + case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 181 /* SyntaxKind.TypeQuery */: + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 200 /* SyntaxKind.ImportType */: if (node.typeArguments === list) { return 29 /* SyntaxKind.LessThanToken */; } @@ -436544,7 +438969,7 @@ var ts; return { indentation: indentation, prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter, - suffix: insertTrailingComma ? "," : "" + suffix: insertTrailingComma ? "," : ts.isInterfaceDeclaration(node) && isEmpty ? ";" : "" }; }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -436748,7 +439173,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.Set(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_11 = function (sourceFile, node) { + var _loop_9 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node)); @@ -436761,7 +439186,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_11(sourceFile, node); + _loop_9(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -436849,14 +439274,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_12 = function (i) { + var _loop_10 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return "".concat(JSON.stringify(normalized[i].range), " and ").concat(JSON.stringify(normalized[i + 1].range)); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_12(i); + _loop_10(i); } var textChanges = ts.mapDefined(normalized, function (c) { var span = ts.createTextSpanFromRange(c.range); @@ -437567,7 +439992,6 @@ var ts; var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { var exportDeclaration = ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([]), /*moduleSpecifier*/ undefined); @@ -437765,7 +440189,7 @@ var ts; } var isCompleteFix = identifiers.isCompleteFix; var initializers; - var _loop_13 = function (identifier) { + var _loop_11 = function (identifier) { var symbol = checker.getSymbolAtLocation(identifier); if (!symbol) { return "continue"; @@ -437798,7 +440222,7 @@ var ts; }; for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) { var identifier = _a[_i]; - _loop_13(identifier); + _loop_11(identifier); } return initializers && { initializers: initializers, @@ -438097,8 +440521,7 @@ var ts; ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); var typeNode = ts.factory.createTypeReferenceNode(param.name, /*typeArguments*/ undefined); - var replacement = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); + var replacement = ts.factory.createParameterDeclaration(param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); changeTracker.replaceNode(sourceFile, param, replacement); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -438323,7 +440746,7 @@ var ts; var isRest = node.type.kind === 318 /* SyntaxKind.JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */) : node.dotDotDotToken; - return ts.factory.createParameterDeclaration(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); + return ts.factory.createParameterDeclaration(node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); } function transformJSDocTypeReference(node) { var name = node.typeName; @@ -438358,12 +440781,11 @@ var ts; } function transformJSDocIndexSignature(node) { var index = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 147 /* SyntaxKind.NumberKeyword */ ? "n" : "s", /*questionToken*/ undefined, ts.factory.createTypeReferenceNode(node.typeArguments[0].kind === 147 /* SyntaxKind.NumberKeyword */ ? "number" : "string", []), /*initializer*/ undefined); - var indexSignature = ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + var indexSignature = ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(/*modifiers*/ undefined, [index], node.typeArguments[1])]); ts.setEmitFlags(indexSignature, 1 /* EmitFlags.SingleLine */); return indexSignature; } @@ -438505,7 +440927,7 @@ var ts; ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentExpr) { - members.push(ts.factory.createPropertyDeclaration([], modifiers, symbol.name, /*questionToken*/ undefined, + members.push(ts.factory.createPropertyDeclaration(modifiers, symbol.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); return; } @@ -438541,7 +440963,7 @@ var ts; return; if (!ts.isPropertyAccessExpression(memberDeclaration)) return; - var prop = ts.factory.createPropertyDeclaration(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); + var prop = ts.factory.createPropertyDeclaration(modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); members.push(prop); return; @@ -438554,7 +440976,7 @@ var ts; } function createFunctionExpressionMember(members, functionExpression, name) { var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 131 /* SyntaxKind.AsyncKeyword */)); - var method = ts.factory.createMethodDeclaration(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + var method = ts.factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members.push(method); @@ -438572,7 +440994,7 @@ var ts; bodyBlock = ts.factory.createBlock([ts.factory.createReturnStatement(arrowFunctionBody)]); } var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 131 /* SyntaxKind.AsyncKeyword */)); - var method = ts.factory.createMethodDeclaration(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + var method = ts.factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members.push(method); @@ -438586,10 +441008,10 @@ var ts; } var memberElements = createClassElementsFromSymbol(node.symbol); if (initializer.body) { - memberElements.unshift(ts.factory.createConstructorDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + memberElements.unshift(ts.factory.createConstructorDeclaration(/*modifiers*/ undefined, initializer.parameters, initializer.body)); } var modifiers = getModifierKindFromSource(node.parent.parent, 93 /* SyntaxKind.ExportKeyword */); - var cls = ts.factory.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + var cls = ts.factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; @@ -438597,17 +441019,17 @@ var ts; function createClassFromFunctionDeclaration(node) { var memberElements = createClassElementsFromSymbol(ctorSymbol); if (node.body) { - memberElements.unshift(ts.factory.createConstructorDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + memberElements.unshift(ts.factory.createConstructorDeclaration(/*modifiers*/ undefined, node.parameters, node.body)); } var modifiers = getModifierKindFromSource(node, 93 /* SyntaxKind.ExportKeyword */); - var cls = ts.factory.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + var cls = ts.factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; } } function getModifierKindFromSource(source, kind) { - return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + return ts.canHaveModifiers(source) ? ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }) : undefined; } function isConstructorAssignment(x) { if (!x.name) @@ -438683,12 +441105,9 @@ var ts; if (!returnStatements.length) { return; } - var pos = functionToConvert.modifiers ? functionToConvert.modifiers.end : - functionToConvert.decorators ? ts.skipTrivia(sourceFile.text, functionToConvert.decorators.end) : - functionToConvert.getStart(sourceFile); - var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " }; - changes.insertModifierAt(sourceFile, pos, 131 /* SyntaxKind.AsyncKeyword */, options); - var _loop_14 = function (returnStatement) { + var pos = ts.skipTrivia(sourceFile.text, ts.moveRangePastModifiers(functionToConvert).pos); + changes.insertModifierAt(sourceFile, pos, 131 /* SyntaxKind.AsyncKeyword */, { suffix: " " }); + var _loop_12 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { var newNodes = transformExpression(node, node, transformer, /*hasContinuation*/ false); @@ -438710,7 +441129,7 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var returnStatement = returnStatements_1[_i]; - var state_5 = _loop_14(returnStatement); + var state_5 = _loop_12(returnStatement); if (typeof state_5 === "object") return state_5.value; } @@ -439813,12 +442232,10 @@ var ts; } // Node helpers function functionExpressionToDeclaration(name, additionalModifiers, fn, useSitesToUnqualify) { - return ts.factory.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))); + return ts.factory.createFunctionDeclaration(ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))); } function classExpressionToDeclaration(name, additionalModifiers, cls, useSitesToUnqualify) { - return ts.factory.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), replaceImportUseSites(cls.members, useSitesToUnqualify)); + return ts.factory.createClassDeclaration(ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), replaceImportUseSites(cls.members, useSitesToUnqualify)); } function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { return propertyName === "default" @@ -439833,7 +442250,6 @@ var ts; } function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { return ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, exportSpecifiers && ts.factory.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.factory.createStringLiteral(moduleSpecifier)); } @@ -439922,11 +442338,10 @@ var ts; changes.insertModifierBefore(context.sourceFile, 152 /* SyntaxKind.TypeKeyword */, exportClause); } else { - var valueExportDeclaration = ts.factory.updateExportDeclaration(exportDeclaration, exportDeclaration.decorators, exportDeclaration.modifiers, + var valueExportDeclaration = ts.factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, /*isTypeOnly*/ false, ts.factory.updateNamedExports(exportClause, ts.filter(exportClause.elements, function (e) { return !ts.contains(typeExportSpecifiers, e); })), exportDeclaration.moduleSpecifier, /*assertClause*/ undefined); var typeExportDeclaration = ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ true, ts.factory.createNamedExports(typeExportSpecifiers), exportDeclaration.moduleSpecifier, /*assertClause*/ undefined); @@ -439990,7 +442405,6 @@ var ts; if (importClause.name && importClause.namedBindings) { changes.deleteNodeRangeExcludingEnd(context.sourceFile, importClause.name, importDeclaration.importClause.namedBindings); changes.insertNodeBefore(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( /*isTypeOnly*/ true, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, @@ -440433,7 +442847,7 @@ var ts; var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); }); - ts.forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { + ts.forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(importingFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { @@ -440902,7 +443316,7 @@ var ts; originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol: moduleSymbol, moduleFileName: toFile === null || toFile === void 0 ? void 0 : toFile.fileName, exportKind: exportKind, targetFlags: ts.skipAlias(exportedSymbol, checker).flags, isFromPackageJson: isFromPackageJson }); } } - ts.forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { + ts.forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); cancellationToken.throwIfCancellationRequested(); var compilerOptions = program.getCompilerOptions(); @@ -441162,10 +443576,8 @@ var ts; if (namespaceLikeImport) { var declaration = namespaceLikeImport.importKind === 3 /* ImportKind.CommonJS */ ? ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, needsTypeOnly(namespaceLikeImport), ts.factory.createIdentifier(namespaceLikeImport.name), ts.factory.createExternalModuleReference(quotedModuleSpecifier)) : ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(needsTypeOnly(namespaceLikeImport), /*name*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier, /*assertClause*/ undefined); @@ -441245,6 +443657,113 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingConstraint"; + var errorCodes = [ + // We want errors this could be attached to: + // Diagnostics.This_type_parameter_probably_needs_an_extends_0_constraint + ts.Diagnostics.Type_0_is_not_comparable_to_type_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, + ts.Diagnostics.Property_0_is_incompatible_with_index_signature.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, + ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span, program = context.program, preferences = context.preferences, host = context.host; + var info = getInfo(program, sourceFile, span); + if (info === undefined) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingConstraint(t, program, preferences, host, sourceFile, info); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_extends_constraint, fixId, ts.Diagnostics.Add_extends_constraint_to_all_type_parameters)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var program = context.program, preferences = context.preferences, host = context.host; + var seen = new ts.Map(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(program, diag.file, ts.createTextSpan(diag.start, diag.length)); + if (info) { + if (ts.addToSeen(seen, ts.getNodeId(info.declaration))) { + return addMissingConstraint(changes, program, preferences, host, diag.file, info); + } + } + return undefined; + }); + })); + } + }); + function getInfo(program, sourceFile, span) { + var diag = ts.find(program.getSemanticDiagnostics(sourceFile), function (diag) { return diag.start === span.start && diag.length === span.length; }); + if (diag === undefined || diag.relatedInformation === undefined) + return; + var related = ts.find(diag.relatedInformation, function (related) { return related.code === ts.Diagnostics.This_type_parameter_might_need_an_extends_0_constraint.code; }); + if (related === undefined || related.file === undefined || related.start === undefined || related.length === undefined) + return; + var declaration = findAncestorMatchingSpan(related.file, ts.createTextSpan(related.start, related.length)); + if (declaration === undefined) + return; + if (ts.isIdentifier(declaration) && ts.isTypeParameterDeclaration(declaration.parent)) { + declaration = declaration.parent; + } + if (ts.isTypeParameterDeclaration(declaration)) { + // should only issue fix on type parameters written using `extends` + if (ts.isMappedTypeNode(declaration.parent)) + return; + var token = ts.getTokenAtPosition(sourceFile, span.start); + var checker = program.getTypeChecker(); + var constraint = tryGetConstraintType(checker, token) || tryGetConstraintFromDiagnosticMessage(related.messageText); + return { constraint: constraint, declaration: declaration, token: token }; + } + return undefined; + } + function addMissingConstraint(changes, program, preferences, host, sourceFile, info) { + var declaration = info.declaration, constraint = info.constraint; + var checker = program.getTypeChecker(); + if (ts.isString(constraint)) { + changes.insertText(sourceFile, declaration.name.end, " extends ".concat(constraint)); + } + else { + var scriptTarget = ts.getEmitScriptTarget(program.getCompilerOptions()); + var tracker = codefix.getNoopSymbolTrackerWithResolver({ program: program, host: host }); + var importAdder = codefix.createImportAdder(sourceFile, program, preferences, host); + var typeNode = codefix.typeToAutoImportableTypeNode(checker, importAdder, constraint, /*contextNode*/ undefined, scriptTarget, /*flags*/ undefined, tracker); + if (typeNode) { + changes.replaceNode(sourceFile, declaration, ts.factory.updateTypeParameterDeclaration(declaration, /*modifiers*/ undefined, declaration.name, typeNode, declaration.default)); + importAdder.writeFixes(changes); + } + } + } + function findAncestorMatchingSpan(sourceFile, span) { + var end = ts.textSpanEnd(span); + var token = ts.getTokenAtPosition(sourceFile, span.start); + while (token.end < end) { + token = token.parent; + } + return token; + } + function tryGetConstraintFromDiagnosticMessage(messageText) { + var _a = ts.flattenDiagnosticMessageText(messageText, "\n", 0).match(/`extends (.*)`/) || [], _ = _a[0], constraint = _a[1]; + return constraint; + } + function tryGetConstraintType(checker, node) { + if (ts.isTypeNode(node.parent)) { + return checker.getTypeArgumentConstraint(node.parent); + } + var contextualType = ts.isExpression(node) ? checker.getContextualType(node) : undefined; + return contextualType || checker.getTypeAtLocation(node); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -441367,10 +443886,11 @@ var ts; var staticModifier = ts.find(modifiers, ts.isStaticModifier); var abstractModifier = ts.find(modifiers, ts.isAbstractModifier); var accessibilityModifier = ts.find(modifiers, function (m) { return ts.isAccessibilityModifier(m.kind); }); + var lastDecorator = ts.findLast(modifiers, ts.isDecorator); var modifierPos = abstractModifier ? abstractModifier.end : staticModifier ? staticModifier.end : accessibilityModifier ? accessibilityModifier.end : - classElement.decorators ? ts.skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + lastDecorator ? ts.skipTrivia(sourceFile.text, lastDecorator.end) : classElement.getStart(sourceFile); var options = accessibilityModifier || staticModifier || abstractModifier ? { prefix: " " } : { suffix: " " }; changeTracker.insertModifierAt(sourceFile, modifierPos, 159 /* SyntaxKind.OverrideKeyword */, options); } @@ -441380,7 +443900,7 @@ var ts; changeTracker.filterJSDocTags(sourceFile, classElement, ts.not(ts.isJSDocOverrideTag)); return; } - var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 159 /* SyntaxKind.OverrideKeyword */; }); + var overrideModifier = ts.find(classElement.modifiers, ts.isOverrideModifier); ts.Debug.assertIsDefined(overrideModifier); changeTracker.deleteModifier(sourceFile, overrideModifier); } @@ -441980,7 +444500,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, declaration) { var supers = ts.isTypeLiteralNode(declaration) ? undefined : codefix.getAllSupers(declaration, checker); - var _loop_15 = function (info) { + var _loop_13 = function (info) { // If some superclass added this property, don't add it again. if (supers === null || supers === void 0 ? void 0 : supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -442007,7 +444527,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_15(info); + _loop_13(info); } }); })); @@ -442059,7 +444579,7 @@ var ts; return undefined; return { kind: 4 /* InfoKind.JsxAttributes */, token: token, attributes: attributes, parentDeclaration: token.parent }; } - if (ts.isIdentifier(token) && ts.isCallExpression(parent)) { + if (ts.isIdentifier(token) && ts.isCallExpression(parent) && parent.expression === token) { return { kind: 2 /* InfoKind.Function */, token: token, call: parent, sourceFile: sourceFile, modifierFlags: 0 /* ModifierFlags.None */, parentDeclaration: sourceFile }; } if (!ts.isPropertyAccessExpression(parent)) @@ -442136,7 +444656,6 @@ var ts; } else if (ts.isPrivateIdentifier(token)) { var property = ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, tokenName, /*questionToken*/ undefined, /*type*/ undefined, @@ -442194,7 +444713,7 @@ var ts; function addPropertyDeclaration(changeTracker, sourceFile, node, tokenName, typeNode, modifierFlags) { var modifiers = modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; var property = ts.isClassLike(node) - ? ts.factory.createPropertyDeclaration(/*decorators*/ undefined, modifiers, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined) + ? ts.factory.createPropertyDeclaration(modifiers, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined) : ts.factory.createPropertySignature(/*modifiers*/ undefined, tokenName, /*questionToken*/ undefined, typeNode); var lastProp = getNodeToInsertPropertyAfter(node); if (lastProp) { @@ -442219,13 +444738,11 @@ var ts; // Index signatures cannot have the static modifier. var stringTypeNode = ts.factory.createKeywordTypeNode(150 /* SyntaxKind.StringKeyword */); var indexingParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "x", /*questionToken*/ undefined, stringTypeNode, /*initializer*/ undefined); var indexSignature = ts.factory.createIndexSignature( - /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertMemberAtStart(sourceFile, node, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. @@ -442273,7 +444790,7 @@ var ts; return !!(type && type.flags & 402653316 /* TypeFlags.StringLike */); }); var enumMember = ts.factory.createEnumMember(token, hasStringInitializer ? ts.factory.createStringLiteral(token.text) : undefined); - changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, ts.factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.decorators, parentDeclaration.modifiers, parentDeclaration.name, ts.concatenate(parentDeclaration.members, ts.singleElementArray(enumMember))), { + changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, ts.factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.modifiers, parentDeclaration.name, ts.concatenate(parentDeclaration.members, ts.singleElementArray(enumMember))), { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude }); @@ -442282,6 +444799,7 @@ var ts; var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(256 /* SyntaxKind.FunctionDeclaration */, context, importAdder, info.call, ts.idText(info.token), info.modifierFlags, info.parentDeclaration); changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); + importAdder.writeFixes(changes); } function addJsxAttributes(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); @@ -442290,7 +444808,7 @@ var ts; var jsxAttributesNode = info.parentDeclaration.attributes; var hasSpreadAttribute = ts.some(jsxAttributesNode.properties, ts.isJsxSpreadAttribute); var attrs = ts.map(info.attributes, function (attr) { - var value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr)); + var value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr), info.parentDeclaration); var name = ts.factory.createIdentifier(attr.name); var jsxAttribute = ts.factory.createJsxAttribute(name, ts.factory.createJsxExpression(/*dotDotDotToken*/ undefined, value)); // formattingScanner requires the Identifier to have a context for scanning attributes with "-" (data-foo). @@ -442300,6 +444818,7 @@ var ts; var jsxAttributes = ts.factory.createJsxAttributes(hasSpreadAttribute ? __spreadArray(__spreadArray([], attrs, true), jsxAttributesNode.properties, true) : __spreadArray(__spreadArray([], jsxAttributesNode.properties, true), attrs, true)); var options = { prefix: jsxAttributesNode.pos === jsxAttributesNode.end ? " " : undefined }; changes.replaceNode(context.sourceFile, jsxAttributesNode, jsxAttributes, options); + importAdder.writeFixes(changes); } function addObjectLiteralProperties(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); @@ -442307,8 +444826,8 @@ var ts; var target = ts.getEmitScriptTarget(context.program.getCompilerOptions()); var checker = context.program.getTypeChecker(); var props = ts.map(info.properties, function (prop) { - var initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop)); - return ts.factory.createPropertyAssignment(ts.createPropertyNameNodeForIdentifierOrLiteral(prop.name, target, quotePreference === 0 /* QuotePreference.Single */), initializer); + var initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), info.parentDeclaration); + return ts.factory.createPropertyAssignment(createPropertyNameFromSymbol(prop, target, quotePreference, checker), initializer); }); var options = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, @@ -442316,8 +444835,9 @@ var ts; indentation: info.indentation }; changes.replaceNode(context.sourceFile, info.parentDeclaration, ts.factory.createObjectLiteralExpression(__spreadArray(__spreadArray([], info.parentDeclaration.properties, true), props, true), /*multiLine*/ true), options); + importAdder.writeFixes(changes); } - function tryGetValueFromType(context, checker, importAdder, quotePreference, type) { + function tryGetValueFromType(context, checker, importAdder, quotePreference, type, enclosingDeclaration) { if (type.flags & 3 /* TypeFlags.AnyOrUnknown */) { return createUndefined(); } @@ -442354,7 +444874,7 @@ var ts; return ts.factory.createNull(); } if (type.flags & 1048576 /* TypeFlags.Union */) { - var expression = ts.firstDefined(type.types, function (t) { return tryGetValueFromType(context, checker, importAdder, quotePreference, t); }); + var expression = ts.firstDefined(type.types, function (t) { return tryGetValueFromType(context, checker, importAdder, quotePreference, t, enclosingDeclaration); }); return expression !== null && expression !== void 0 ? expression : createUndefined(); } if (checker.isArrayLikeType(type)) { @@ -442362,7 +444882,7 @@ var ts; } if (isObjectLiteralType(type)) { var props = ts.map(checker.getPropertiesOfType(type), function (prop) { - var initializer = prop.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(prop.valueDeclaration)) : createUndefined(); + var initializer = prop.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(prop.valueDeclaration), enclosingDeclaration) : createUndefined(); return ts.factory.createPropertyAssignment(prop.name, initializer); }); return ts.factory.createObjectLiteralExpression(props, /*multiLine*/ true); @@ -442374,7 +444894,7 @@ var ts; var signature = checker.getSignaturesOfType(type, 0 /* SignatureKind.Call */); if (signature === undefined) return createUndefined(); - var func = codefix.createSignatureDeclarationFromSignature(213 /* SyntaxKind.FunctionExpression */, context, quotePreference, signature[0], codefix.createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ undefined, importAdder); + var func = codefix.createSignatureDeclarationFromSignature(213 /* SyntaxKind.FunctionExpression */, context, quotePreference, signature[0], codefix.createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ enclosingDeclaration, importAdder); return func !== null && func !== void 0 ? func : createUndefined(); } if (ts.getObjectFlags(type) & 1 /* ObjectFlags.Class */) { @@ -442427,6 +444947,15 @@ var ts; var declaration = ts.findAncestor(callExpression, function (n) { return ts.isMethodDeclaration(n) || ts.isConstructorDeclaration(n); }); return declaration && declaration.parent === node ? declaration : undefined; } + function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) { + if (ts.isTransientSymbol(symbol) && symbol.nameType && symbol.nameType.flags & 8192 /* TypeFlags.UniqueESSymbol */) { + var expression = checker.symbolToExpression(symbol.nameType.symbol, 111551 /* SymbolFlags.Value */, symbol.valueDeclaration, 1048576 /* NodeBuilderFlags.AllowUniqueESSymbolType */); + if (expression) { + return ts.factory.createComputedPropertyName(expression); + } + } + return ts.createPropertyNameNodeForIdentifierOrLiteral(symbol.name, target, quotePreference === 0 /* QuotePreference.Single */); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -443352,7 +445881,12 @@ var ts; if (mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll)) { if (parameter.modifiers && parameter.modifiers.length > 0 && (!ts.isIdentifier(parameter.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(parameter.name, checker, sourceFile))) { - parameter.modifiers.forEach(function (modifier) { return changes.deleteModifier(sourceFile, modifier); }); + for (var _i = 0, _a = parameter.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (ts.isModifier(modifier)) { + changes.deleteModifier(sourceFile, modifier); + } + } } else if (!parameter.initializer && isNotProvidedArguments(parameter, checker, sourceFiles)) { changes.delete(sourceFile, parameter); @@ -444767,7 +447301,7 @@ var ts; function getSignatureFromCalls(calls) { var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_16 = function (i) { + var _loop_14 = function (i) { var symbol = checker.createSymbol(1 /* SymbolFlags.FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg".concat(i))); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { @@ -444776,7 +447310,7 @@ var ts; parameters.push(symbol); }; for (var i = 0; i < length; i++) { - _loop_16(i); + _loop_14(i); } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* SignatureFlags.None */); @@ -444966,8 +447500,7 @@ var ts; importSymbols(importAdder, importableReference.symbols); } } - addClassElement(ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, name, optional && (preserveOptional & 2 /* PreserveOptionalFlags.Property */) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeNode, + addClassElement(ts.factory.createPropertyDeclaration(modifiers, name, optional && (preserveOptional & 2 /* PreserveOptionalFlags.Property */) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; case 172 /* SyntaxKind.GetAccessor */: @@ -444987,15 +447520,13 @@ var ts; for (var _i = 0, orderedAccessors_1 = orderedAccessors; _i < orderedAccessors_1.length; _i++) { var accessor = orderedAccessors_1[_i]; if (ts.isGetAccessorDeclaration(accessor)) { - addClassElement(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); + addClassElement(ts.factory.createGetAccessorDeclaration(modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } else { ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); var parameter = ts.getSetAccessorValueParameter(accessor); var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined; - addClassElement(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); + addClassElement(ts.factory.createSetAccessorDeclaration(modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } } break; @@ -445009,7 +447540,7 @@ var ts; // If there is more than one overload but no implementation signature // (eg: an abstract method or interface declaration), there is a 1-1 // correspondence of declarations and signatures. - var signatures = checker.getSignaturesOfType(type, 0 /* SignatureKind.Call */); + var signatures = type.isUnion() ? ts.flatMap(type.types, function (t) { return t.getCallSignatures(); }) : type.getCallSignatures(); if (!ts.some(signatures)) { break; } @@ -445090,7 +447621,7 @@ var ts; type = importableReference.typeNode; importSymbols(importAdder, importableReference.symbols); } - return ts.factory.updateParameterDeclaration(parameterDecl, parameterDecl.decorators, parameterDecl.modifiers, parameterDecl.dotDotDotToken, parameterDecl.name, parameterDecl.questionToken, type, parameterDecl.initializer); + return ts.factory.updateParameterDeclaration(parameterDecl, parameterDecl.modifiers, parameterDecl.dotDotDotToken, parameterDecl.name, parameterDecl.questionToken, type, parameterDecl.initializer); }); if (parameters !== newParameters) { parameters = ts.setTextRange(ts.factory.createNodeArray(newParameters, parameters.hasTrailingComma), parameters); @@ -445112,7 +447643,7 @@ var ts; return ts.factory.updateArrowFunction(signatureDeclaration, modifiers, typeParameters, parameters, type, signatureDeclaration.equalsGreaterThanToken, body !== null && body !== void 0 ? body : signatureDeclaration.body); } if (ts.isMethodDeclaration(signatureDeclaration)) { - return ts.factory.updateMethodDeclaration(signatureDeclaration, /* decorators */ undefined, modifiers, asteriskToken, name !== null && name !== void 0 ? name : ts.factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); + return ts.factory.updateMethodDeclaration(signatureDeclaration, modifiers, asteriskToken, name !== null && name !== void 0 ? name : ts.factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); } return undefined; } @@ -445128,40 +447659,50 @@ var ts; var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined; }); - var types = isJs ? [] : ts.map(args, function (arg) { - return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker); - }); + var instanceTypes = isJs ? [] : ts.map(args, function (arg) { return checker.getTypeAtLocation(arg); }); + var _a = getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, /*flags*/ undefined, tracker), argumentTypeNodes = _a.argumentTypeNodes, argumentTypeParameters = _a.argumentTypeParameters; var modifiers = modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; var asteriskToken = ts.isYieldExpression(parent) ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined; - var typeParameters = isJs || typeArguments === undefined - ? undefined - : ts.map(typeArguments, function (_, i) { - return ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, 84 /* CharacterCodes.T */ + typeArguments.length - 1 <= 90 /* CharacterCodes.Z */ ? String.fromCharCode(84 /* CharacterCodes.T */ + i) : "T".concat(i)); - }); - var parameters = createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, isJs); + var typeParameters = isJs ? undefined : createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments); + var parameters = createDummyParameters(args.length, names, argumentTypeNodes, /*minArgumentCount*/ undefined, isJs); var type = isJs || contextualType === undefined ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); switch (kind) { case 169 /* SyntaxKind.MethodDeclaration */: - return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers, asteriskToken, name, + return ts.factory.createMethodDeclaration(modifiers, asteriskToken, name, /*questionToken*/ undefined, typeParameters, parameters, type, createStubbedMethodBody(quotePreference)); case 168 /* SyntaxKind.MethodSignature */: return ts.factory.createMethodSignature(modifiers, name, - /*questionToken*/ undefined, typeParameters, parameters, type); + /*questionToken*/ undefined, typeParameters, parameters, type === undefined ? ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */) : type); case 256 /* SyntaxKind.FunctionDeclaration */: - return ts.factory.createFunctionDeclaration( - /*decorators*/ undefined, modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference)); + return ts.factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference)); default: ts.Debug.fail("Unexpected kind"); } } codefix.createSignatureDeclarationFromCallExpression = createSignatureDeclarationFromCallExpression; + function createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments) { + var usedNames = new ts.Set(argumentTypeParameters.map(function (pair) { return pair[0]; })); + var constraintsByName = new ts.Map(argumentTypeParameters); + if (typeArguments) { + var typeArgumentsWithNewTypes = typeArguments.filter(function (typeArgument) { return !argumentTypeParameters.some(function (pair) { var _a; return checker.getTypeAtLocation(typeArgument) === ((_a = pair[1]) === null || _a === void 0 ? void 0 : _a.argumentType); }); }); + var targetSize = usedNames.size + typeArgumentsWithNewTypes.length; + for (var i = 0; usedNames.size < targetSize; i += 1) { + usedNames.add(createTypeParameterName(i)); + } + } + return ts.map(ts.arrayFrom(usedNames.values()), function (usedName) { var _a; return ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, usedName, (_a = constraintsByName.get(usedName)) === null || _a === void 0 ? void 0 : _a.constraint); }); + } + function createTypeParameterName(index) { + return 84 /* CharacterCodes.T */ + index <= 90 /* CharacterCodes.Z */ + ? String.fromCharCode(84 /* CharacterCodes.T */ + index) + : "T".concat(index); + } function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) { var typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); if (typeNode && ts.isImportTypeNode(typeNode)) { @@ -445175,16 +447716,107 @@ var ts; return ts.getSynthesizedDeepClone(typeNode); } codefix.typeToAutoImportableTypeNode = typeToAutoImportableTypeNode; + function typeContainsTypeParameter(type) { + if (type.isUnionOrIntersection()) { + return type.types.some(typeContainsTypeParameter); + } + return type.flags & 262144 /* TypeFlags.TypeParameter */; + } + function getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, flags, tracker) { + // Types to be used as the types of the parameters in the new function + // E.g. from this source: + // added("", 0) + // The value will look like: + // [{ typeName: { text: "string" } }, { typeName: { text: "number" }] + // And in the output function will generate: + // function added(a: string, b: number) { ... } + var argumentTypeNodes = []; + // Names of type parameters provided as arguments to the call + // E.g. from this source: + // added(value); + // The value will look like: + // [ + // ["T", { argumentType: { typeName: { text: "T" } } } ], + // ["U", { argumentType: { typeName: { text: "U" } } } ], + // ] + // And in the output function will generate: + // function added() { ... } + var argumentTypeParameters = new ts.Map(); + for (var i = 0; i < instanceTypes.length; i += 1) { + var instanceType = instanceTypes[i]; + // If the instance type contains a deep reference to an existing type parameter, + // instead of copying the full union or intersection, create a new type parameter + // E.g. from this source: + // function existing(value: T | U & string) { + // added/*1*/(value); + // We don't want to output this: + // function added(value: T | U & string) { ... } + // We instead want to output: + // function added(value: T) { ... } + if (instanceType.isUnionOrIntersection() && instanceType.types.some(typeContainsTypeParameter)) { + var synthesizedTypeParameterName = createTypeParameterName(i); + argumentTypeNodes.push(ts.factory.createTypeReferenceNode(synthesizedTypeParameterName)); + argumentTypeParameters.set(synthesizedTypeParameterName, undefined); + continue; + } + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + var widenedInstanceType = checker.getBaseTypeOfLiteralType(instanceType); + var argumentTypeNode = typeToAutoImportableTypeNode(checker, importAdder, widenedInstanceType, contextNode, scriptTarget, flags, tracker); + if (!argumentTypeNode) { + continue; + } + argumentTypeNodes.push(argumentTypeNode); + var argumentTypeParameter = getFirstTypeParameterName(instanceType); + // If the instance type is a type parameter with a constraint (other than an anonymous object), + // remember that constraint for when we create the new type parameter + // E.g. from this source: + // function existing(value: T) { + // added/*1*/(value); + // We don't want to output this: + // function added(value: T) { ... } + // We instead want to output: + // function added(value: T) { ... } + var instanceTypeConstraint = instanceType.isTypeParameter() && instanceType.constraint && !isAnonymousObjectConstraintType(instanceType.constraint) + ? typeToAutoImportableTypeNode(checker, importAdder, instanceType.constraint, contextNode, scriptTarget, flags, tracker) + : undefined; + if (argumentTypeParameter) { + argumentTypeParameters.set(argumentTypeParameter, { argumentType: instanceType, constraint: instanceTypeConstraint }); + } + } + return { argumentTypeNodes: argumentTypeNodes, argumentTypeParameters: ts.arrayFrom(argumentTypeParameters.entries()) }; + } + codefix.getArgumentTypesAndTypeParameters = getArgumentTypesAndTypeParameters; + function isAnonymousObjectConstraintType(type) { + return (type.flags & 524288 /* TypeFlags.Object */) && type.objectFlags === 16 /* ObjectFlags.Anonymous */; + } + function getFirstTypeParameterName(type) { + var _a; + if (type.flags & (1048576 /* TypeFlags.Union */ | 2097152 /* TypeFlags.Intersection */)) { + for (var _i = 0, _b = type.types; _i < _b.length; _i++) { + var subType = _b[_i]; + var subTypeName = getFirstTypeParameterName(subType); + if (subTypeName) { + return subTypeName; + } + } + } + return type.flags & 262144 /* TypeFlags.TypeParameter */ + ? (_a = type.getSymbol()) === null || _a === void 0 ? void 0 : _a.getName() + : undefined; + } function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { var parameters = []; + var parameterNameCounts = new ts.Map(); for (var i = 0; i < argCount; i++) { + var parameterName = (names === null || names === void 0 ? void 0 : names[i]) || "arg".concat(i); + var parameterNameCount = parameterNameCounts.get(parameterName); + parameterNameCounts.set(parameterName, (parameterNameCount || 0) + 1); var newParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - /*name*/ names && names[i] || "arg".concat(i), + /*name*/ parameterName + (parameterNameCount || ""), /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, - /*type*/ inJs ? undefined : types && types[i] || ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */), + /*type*/ inJs ? undefined : (types === null || types === void 0 ? void 0 : types[i]) || ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -445213,7 +447845,6 @@ var ts; var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { var restParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, ts.factory.createArrayTypeNode(ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */)), /*initializer*/ undefined); @@ -445229,8 +447860,7 @@ var ts; } } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) { - return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers, + return ts.factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeParameters, parameters, returnType, body || createStubbedMethodBody(quotePreference)); } function createStubbedMethodBody(quotePreference) { @@ -445361,6 +447991,9 @@ var ts; accessorModifiers = ts.createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); fieldModifiers = ts.createModifiers(prepareModifierFlagsForField(modifierFlags)); } + if (ts.canHaveDecorators(declaration)) { + fieldModifiers = ts.concatenate(ts.getDecorators(declaration), fieldModifiers); + } } updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, fieldModifiers); var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); @@ -445425,7 +448058,7 @@ var ts; error: ts.getLocaleSpecificMessage(ts.Diagnostics.Name_is_not_valid) }; } - if ((ts.getEffectiveModifierFlags(declaration) | meaning) !== meaning) { + if (((ts.getEffectiveModifierFlags(declaration) & 125951 /* ModifierFlags.Modifier */) | meaning) !== meaning) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_property_with_modifier) }; @@ -445448,17 +448081,14 @@ var ts; } codefix.getAccessorConvertiblePropertyAtPosition = getAccessorConvertiblePropertyAtPosition; function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { - return ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, accessorName, + return ts.factory.createGetAccessorDeclaration(modifiers, accessorName, /*parameters*/ undefined, // TODO: GH#18217 type, ts.factory.createBlock([ ts.factory.createReturnStatement(createAccessorAccessExpression(fieldName, isStatic, container)) ], /*multiLine*/ true)); } function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { - return ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, accessorName, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + return ts.factory.createSetAccessorDeclaration(modifiers, accessorName, [ts.factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.factory.createIdentifier("value"), /*questionToken*/ undefined, type)], ts.factory.createBlock([ @@ -445466,7 +448096,7 @@ var ts; ], /*multiLine*/ true)); } function updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) { - var property = ts.factory.updatePropertyDeclaration(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, type, declaration.initializer); + var property = ts.factory.updatePropertyDeclaration(declaration, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, type, declaration.initializer); changeTracker.replaceNode(file, declaration, property); } function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { @@ -445481,7 +448111,7 @@ var ts; updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); } else { - changeTracker.replaceNode(file, declaration, ts.factory.updateParameterDeclaration(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + changeTracker.replaceNode(file, declaration, ts.factory.updateParameterDeclaration(declaration, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); } } function insertAccessor(changeTracker, file, accessor, declaration, container) { @@ -445555,7 +448185,6 @@ var ts; if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, namespace.name, ts.factory.createExternalModuleReference(node.moduleSpecifier)))); } @@ -445692,7 +448321,7 @@ var ts; } function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { ts.suppressLeadingAndTrailingTrivia(propertyDeclaration); - var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.factory.createToken(53 /* SyntaxKind.ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, ts.factory.createToken(53 /* SyntaxKind.ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getActionForAddMissingUndefinedType(context, info) { @@ -445722,7 +448351,7 @@ var ts; } function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { ts.suppressLeadingAndTrailingTrivia(propertyDeclaration); - var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getInitializer(checker, propertyDeclaration) { @@ -445788,8 +448417,8 @@ var ts; function doChange(changes, sourceFile, info) { var allowSyntheticDefaults = info.allowSyntheticDefaults, defaultImportName = info.defaultImportName, namedImports = info.namedImports, statement = info.statement, required = info.required; changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults - ? ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, ts.factory.createExternalModuleReference(required)) - : ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ undefined)); + ? ts.factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, ts.factory.createExternalModuleReference(required)) + : ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ undefined)); } function getInfo(sourceFile, program, pos) { var parent = ts.getTokenAtPosition(sourceFile, pos).parent; @@ -445927,7 +448556,7 @@ var ts; return token.parent; } function doChange(changes, sourceFile, importType) { - var newTypeNode = ts.factory.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + var newTypeNode = ts.factory.updateImportTypeNode(importType, importType.argument, importType.assertions, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); changes.replaceNode(sourceFile, importType, newTypeNode); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -446044,7 +448673,7 @@ var ts; return { indexSignature: indexSignature, container: container }; } function createTypeAliasFromInterface(declaration, type) { - return ts.factory.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + return ts.factory.createTypeAliasDeclaration(declaration.modifiers, declaration.name, declaration.typeParameters, type); } function doChange(changes, sourceFile, _a) { var indexSignature = _a.indexSignature, container = _a.container; @@ -446160,9 +448789,8 @@ var ts; return; } var importClause = ts.Debug.checkDefined(importDeclaration.importClause); - changes.replaceNode(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); + changes.replaceNode(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); changes.insertNodeAfter(context.sourceFile, importDeclaration, ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, /*name*/ undefined, importClause.namedBindings), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -446384,14 +449012,14 @@ var ts; if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_export_statement) }; } - var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; + var checker = program.getTypeChecker(); + var exportingModuleSymbol = getExportingModuleSymbol(exportNode, checker); var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ModifierFlags.ExportDefault */ : 0 /* ModifierFlags.None */); var wasDefault = !!(flags & 512 /* ModifierFlags.Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* ModifierFlags.Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* InternalSymbolName.Default */)) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.This_file_already_has_a_default_export) }; } - var checker = program.getTypeChecker(); var noSymbolError = function (id) { return (ts.isIdentifier(id) && checker.getSymbolAtLocation(id)) ? undefined : { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_named_export) }; @@ -446443,7 +449071,7 @@ var ts; if (ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) { var exp = exportNode.expression; var spec = makeExportSpecifier(exp.text, exp.text); - changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); + changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); } else { changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 88 /* SyntaxKind.DefaultKeyword */), "Should find a default keyword in modifier list")); @@ -446483,6 +449111,8 @@ var ts; var checker = program.getTypeChecker(); var exportSymbol = ts.Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) { + if (exportName === ref) + return; var importingSourceFile = ref.getSourceFile(); if (wasDefault) { changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); @@ -446531,7 +449161,7 @@ var ts; } case 200 /* SyntaxKind.ImportType */: var importTypeNode = parent; - changes.replaceNode(importingSourceFile, parent, ts.factory.createImportTypeNode(importTypeNode.argument, ts.factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); + changes.replaceNode(importingSourceFile, parent, ts.factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, ts.factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); break; default: ts.Debug.failBadSyntaxKind(parent); @@ -446575,6 +449205,17 @@ var ts; function makeExportSpecifier(propertyName, name) { return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, propertyName === name ? undefined : ts.factory.createIdentifier(propertyName), ts.factory.createIdentifier(name)); } + function getExportingModuleSymbol(node, checker) { + var parent = node.parent; + if (ts.isSourceFile(parent)) { + return parent.symbol; + } + var symbol = parent.parent.symbol; + if (symbol.valueDeclaration && ts.isExternalModuleAugmentation(symbol.valueDeclaration)) { + return checker.getMergedSymbol(symbol); + } + return symbol; + } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ @@ -446749,7 +449390,7 @@ var ts; // Imports that need to be kept as named imports in the refactored code, to avoid changing the semantics. // More specifically, those are named imports that appear in named exports in the original code, e.g. `a` in `import { a } from "m"; export { a }`. var neededNamedImports = new ts.Set(); - var _loop_17 = function (element) { + var _loop_15 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespaceImportName), propertyName); @@ -446766,7 +449407,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_17(element); + _loop_15(element); } changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? ts.factory.createIdentifier(namespaceImportName) @@ -446787,7 +449428,7 @@ var ts; return externalModule !== exportEquals; } function updateImport(old, defaultImportName, elements) { - return ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? ts.factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); + return ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? ts.factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); @@ -447101,7 +449742,7 @@ var ts; break; } case 169 /* SyntaxKind.MethodDeclaration */: { - updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } case 174 /* SyntaxKind.CallSignature */: { @@ -447109,7 +449750,7 @@ var ts; break; } case 171 /* SyntaxKind.Constructor */: { - updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); + updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); break; } case 175 /* SyntaxKind.ConstructSignature */: { @@ -447117,7 +449758,7 @@ var ts; break; } case 256 /* SyntaxKind.FunctionDeclaration */: { - updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } default: return ts.Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); @@ -447137,7 +449778,6 @@ var ts; } return ts.factory.createNodeArray([ ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */), "args", /*questionToken*/ undefined, ts.factory.createUnionTypeNode(ts.map(signatureDeclarations, convertSignatureParametersToTuple))) ]); @@ -447184,6 +449824,9 @@ var ts; if (!containingDecl) { return; } + if (ts.isFunctionLikeDeclaration(containingDecl) && containingDecl.body && ts.rangeContainsPosition(containingDecl.body, startPosition)) { + return; + } var checker = program.getTypeChecker(); var signatureSymbol = containingDecl.symbol; if (!signatureSymbol) { @@ -447204,7 +449847,7 @@ var ts; return; } var signatureDecls = decls; - if (ts.some(signatureDecls, function (d) { return !!d.typeParameters || ts.some(d.parameters, function (p) { return !!p.decorators || !!p.modifiers || !ts.isIdentifier(p.name); }); })) { + if (ts.some(signatureDecls, function (d) { return !!d.typeParameters || ts.some(d.parameters, function (p) { return !!p.modifiers || !ts.isIdentifier(p.name); }); })) { return; } var signatures = ts.mapDefined(signatureDecls, function (d) { return checker.getSignatureFromDeclaration(d); }); @@ -447534,11 +450177,11 @@ var ts; } } else if (ts.isVariableStatement(node) || ts.isVariableDeclarationList(node)) { - var declarations_5 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; + var declarations_6 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; var numInitializers = 0; var lastInitializer = void 0; - for (var _i = 0, declarations_4 = declarations_5; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + for (var _i = 0, declarations_5 = declarations_6; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; if (declaration.initializer) { numInitializers++; lastInitializer = declaration.initializer; @@ -447697,7 +450340,7 @@ var ts; var savedPermittedJumps = permittedJumps; switch (node.kind) { case 239 /* SyntaxKind.IfStatement */: - permittedJumps = 0 /* PermittedJumps.None */; + permittedJumps &= ~4 /* PermittedJumps.Return */; break; case 252 /* SyntaxKind.TryStatement */: // forbid all jumps inside try blocks @@ -447989,7 +450632,6 @@ var ts; typeNode = ts.codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NodeBuilderFlags.NoTruncation */); } var paramDecl = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ name, @@ -448029,22 +450671,19 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { modifiers.push(ts.factory.createModifier(131 /* SyntaxKind.AsyncKeyword */)); } - newFunction = ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, + newFunction = ts.factory.createMethodDeclaration(modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, /*questionToken*/ undefined, typeParameters, parameters, returnType, body); } else { if (callThis) { parameters.unshift(ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ "this", /*questionToken*/ undefined, checker.typeToTypeNode(checker.getTypeAtLocation(range.thisNode), scope, 1 /* NodeBuilderFlags.NoTruncation */), /*initializer*/ undefined)); } - newFunction = ts.factory.createFunctionDeclaration( - /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.factory.createToken(131 /* SyntaxKind.AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + newFunction = ts.factory.createFunctionDeclaration(range.facts & RangeFacts.IsAsyncFunction ? [ts.factory.createToken(131 /* SyntaxKind.AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; @@ -448226,8 +450865,7 @@ var ts; modifiers.push(ts.factory.createModifier(124 /* SyntaxKind.StaticKeyword */)); } modifiers.push(ts.factory.createModifier(145 /* SyntaxKind.ReadonlyKeyword */)); - var newVariable = ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, localNameText, + var newVariable = ts.factory.createPropertyDeclaration(modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); var localReference = ts.factory.createPropertyAccessExpression(rangeFacts & RangeFacts.InStaticRegion ? ts.factory.createIdentifier(scope.name.getText()) // TODO: GH#18217 @@ -448322,7 +450960,7 @@ var ts; var paramType = checker.getTypeAtLocation(p); if (paramType === checker.getAnyType()) hasAny = true; - parameters.push(ts.factory.updateParameterDeclaration(p, p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NodeBuilderFlags.NoTruncation */), p.initializer)); + parameters.push(ts.factory.updateParameterDeclaration(p, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NodeBuilderFlags.NoTruncation */), p.initializer)); } } // If a parameter was inferred as any we skip adding function parameters at all. @@ -448332,7 +450970,7 @@ var ts; return { variableType: variableType, initializer: initializer }; variableType = undefined; if (ts.isArrowFunction(initializer)) { - initializer = ts.factory.updateArrowFunction(initializer, node.modifiers, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.equalsGreaterThanToken, initializer.body); + initializer = ts.factory.updateArrowFunction(initializer, ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.equalsGreaterThanToken, initializer.body); } else { if (functionSignature && !!functionSignature.thisParameter) { @@ -448342,13 +450980,12 @@ var ts; if ((!firstParameter || (ts.isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this"))) { var thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); parameters.splice(0, 0, ts.factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "this", /* questionToken */ undefined, checker.typeToTypeNode(thisType, scope, 1 /* NodeBuilderFlags.NoTruncation */))); } } - initializer = ts.factory.updateFunctionExpression(initializer, node.modifiers, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.body); + initializer = ts.factory.updateFunctionExpression(initializer, ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.body); } return { variableType: variableType, initializer: initializer }; } @@ -448664,7 +451301,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_18 = function (i) { + var _loop_16 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -448707,7 +451344,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_18(i); + _loop_16(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -449143,7 +451780,6 @@ var ts; function doTypeAliasChange(changes, file, name, info) { var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters; var newTypeNode = ts.factory.createTypeAliasDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, name, typeParameters.map(function (id) { return ts.factory.updateTypeParameterDeclaration(id, id.modifiers, id.name, id.constraint, /* defaultType */ undefined); }), selection); changes.insertNodeBefore(file, firstStatement, ts.ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true); changes.replaceNode(file, selection, ts.factory.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.factory.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })), { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.ExcludeWhitespace }); @@ -449152,7 +451788,6 @@ var ts; var _a; var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters, typeElements = info.typeElements; var newTypeNode = ts.factory.createInterfaceDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, name, typeParameters, /* heritageClauses */ undefined, typeElements); ts.setTextRange(newTypeNode, (_a = typeElements[0]) === null || _a === void 0 ? void 0 : _a.parent); @@ -449316,7 +451951,7 @@ var ts; var usage = getUsageInfo(oldFile, toMove.all, checker); var currentDirectory = ts.getDirectoryPath(oldFile.fileName); var extension = ts.extensionFromPath(oldFile.fileName); - var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.oldFileImportsFromNewFile, usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; // If previous file was global, this is easy. changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); @@ -449410,10 +452045,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_19 = function (sourceFile) { + var _loop_17 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_20 = function (statement) { + var _loop_18 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -449435,12 +452070,12 @@ var ts; }; for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) { var statement = _c[_b]; - _loop_20(statement); + _loop_18(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_19(sourceFile); + _loop_17(sourceFile); } } function getNamespaceLikeImport(node) { @@ -449483,10 +452118,10 @@ var ts; switch (node.kind) { case 266 /* SyntaxKind.ImportDeclaration */: return ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString, + /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString, /*assertClause*/ undefined); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); + return ts.factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); case 254 /* SyntaxKind.VariableDeclaration */: return ts.factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ undefined, /*type*/ undefined, createRequireCall(newModuleString)); default: @@ -449680,8 +452315,8 @@ var ts; newModuleName = "".concat(moduleName, ".").concat(i); } } - function getNewModuleName(movedSymbols) { - return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + function getNewModuleName(importsFromNewFile, movedSymbols) { + return importsFromNewFile.forEachEntry(ts.symbolNameNoDefault) || movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; } function getUsageInfo(oldFile, toMove, checker) { var movedSymbols = new SymbolSet(); @@ -449774,7 +452409,7 @@ var ts; var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); return defaultImport || namedBindings - ? ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ undefined) + ? ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ undefined) : undefined; } case 265 /* SyntaxKind.ImportEqualsDeclaration */: @@ -449939,24 +452574,25 @@ var ts; return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); } function addEs6Export(d) { - var modifiers = ts.concatenate([ts.factory.createModifier(93 /* SyntaxKind.ExportKeyword */)], d.modifiers); + var modifiers = ts.canHaveModifiers(d) ? ts.concatenate([ts.factory.createModifier(93 /* SyntaxKind.ExportKeyword */)], ts.getModifiers(d)) : undefined; switch (d.kind) { case 256 /* SyntaxKind.FunctionDeclaration */: - return ts.factory.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + return ts.factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); case 257 /* SyntaxKind.ClassDeclaration */: - return ts.factory.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + var decorators = ts.canHaveDecorators(d) ? ts.getDecorators(d) : undefined; + return ts.factory.updateClassDeclaration(d, ts.concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); case 237 /* SyntaxKind.VariableStatement */: return ts.factory.updateVariableStatement(d, modifiers, d.declarationList); case 261 /* SyntaxKind.ModuleDeclaration */: - return ts.factory.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + return ts.factory.updateModuleDeclaration(d, modifiers, d.name, d.body); case 260 /* SyntaxKind.EnumDeclaration */: - return ts.factory.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + return ts.factory.updateEnumDeclaration(d, modifiers, d.name, d.members); case 259 /* SyntaxKind.TypeAliasDeclaration */: - return ts.factory.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + return ts.factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); case 258 /* SyntaxKind.InterfaceDeclaration */: - return ts.factory.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + return ts.factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return ts.factory.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.isTypeOnly, d.name, d.moduleReference); + return ts.factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); case 238 /* SyntaxKind.ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: @@ -450453,7 +453089,7 @@ var ts; if (!checker.isArrayType(type) && !checker.isTupleType(type)) return false; } - return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name); + return !parameterDeclaration.modifiers && ts.isIdentifier(parameterDeclaration.name); } function isValidVariableDeclaration(node) { return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113 @@ -450512,14 +453148,12 @@ var ts; objectInitializer = ts.factory.createObjectLiteralExpression(); } var objectParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, objectParameterName, /*questionToken*/ undefined, objectParameterType, objectInitializer); if (hasThisParameter(functionDeclaration.parameters)) { var thisParameter = functionDeclaration.parameters[0]; var newThisParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, thisParameter.name, /*questionToken*/ undefined, thisParameter.type); @@ -450804,7 +453438,7 @@ var ts; var templateSpans = []; var templateHead = ts.factory.createTemplateHead(headText, rawHeadText); copyCommentFromStringLiterals(headIndexes, templateHead); - var _loop_21 = function (i) { + var _loop_19 = function (i) { var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); copyOperatorComments(i, currentNode); var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], rawSubsequentText = _c[2], stringIndexes = _c[3]; @@ -450833,7 +453467,7 @@ var ts; }; var out_i_1; for (var i = begin; i < nodes.length; i++) { - _loop_21(i); + _loop_19(i); i = out_i_1; } return ts.factory.createTemplateExpression(templateHead, templateSpans); @@ -451040,7 +453674,7 @@ var ts; ts.suppressLeadingTrivia(statement); var modifiersFlags = (ts.getCombinedModifierFlags(variableDeclaration) & 1 /* ModifierFlags.Export */) | ts.getEffectiveModifierFlags(func); var modifiers = ts.factory.createModifiersFromModifierFlags(modifiersFlags); - var newNode = ts.factory.createFunctionDeclaration(func.decorators, ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + var newNode = ts.factory.createFunctionDeclaration(ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); if (variableDeclarationList.declarations.length === 1) { return ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, statement, newNode); }); } @@ -451445,20 +454079,25 @@ var ts; return this.documentationComment; }; SymbolObject.prototype.getContextualDocumentationComment = function (context, checker) { - switch (context === null || context === void 0 ? void 0 : context.kind) { - case 172 /* SyntaxKind.GetAccessor */: + if (context) { + if (ts.isGetAccessor(context)) { if (!this.contextualGetAccessorDocumentationComment) { this.contextualGetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isGetAccessor), checker); } - return this.contextualGetAccessorDocumentationComment; - case 173 /* SyntaxKind.SetAccessor */: + if (ts.length(this.contextualGetAccessorDocumentationComment)) { + return this.contextualGetAccessorDocumentationComment; + } + } + if (ts.isSetAccessor(context)) { if (!this.contextualSetAccessorDocumentationComment) { this.contextualSetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isSetAccessor), checker); } - return this.contextualSetAccessorDocumentationComment; - default: - return this.getDocumentationComment(checker); + if (ts.length(this.contextualSetAccessorDocumentationComment)) { + return this.contextualSetAccessorDocumentationComment; + } + } } + return this.getDocumentationComment(checker); }; SymbolObject.prototype.getJsDocTags = function (checker) { if (this.tags === undefined) { @@ -451467,20 +454106,25 @@ var ts; return this.tags; }; SymbolObject.prototype.getContextualJsDocTags = function (context, checker) { - switch (context === null || context === void 0 ? void 0 : context.kind) { - case 172 /* SyntaxKind.GetAccessor */: + if (context) { + if (ts.isGetAccessor(context)) { if (!this.contextualGetAccessorTags) { this.contextualGetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isGetAccessor), checker); } - return this.contextualGetAccessorTags; - case 173 /* SyntaxKind.SetAccessor */: + if (ts.length(this.contextualGetAccessorTags)) { + return this.contextualGetAccessorTags; + } + } + if (ts.isSetAccessor(context)) { if (!this.contextualSetAccessorTags) { this.contextualSetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isSetAccessor), checker); } - return this.contextualSetAccessorTags; - default: - return this.getJsDocTags(checker); + if (ts.length(this.contextualSetAccessorTags)) { + return this.contextualSetAccessorTags; + } + } } + return this.getJsDocTags(checker); }; return SymbolObject; }()); @@ -451661,7 +454305,7 @@ var ts; * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`. */ function hasJSDocInheritDocTag(node) { - return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); + return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc" || tag.tagName.text === "inheritdoc"; }); } function getJsDocTagsOfDeclarations(declarations, checker) { if (!declarations) @@ -451669,7 +454313,7 @@ var ts; var tags = ts.JsDoc.getJsDocTagsFromDeclarations(declarations, checker); if (checker && (tags.length === 0 || declarations.some(hasJSDocInheritDocTag))) { var seenSymbols_1 = new ts.Set(); - var _loop_22 = function (declaration) { + var _loop_20 = function (declaration) { var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { var _a; if (!seenSymbols_1.has(symbol)) { @@ -451684,9 +454328,9 @@ var ts; tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); } }; - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; - _loop_22(declaration); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + _loop_20(declaration); } } return tags; @@ -451697,7 +454341,7 @@ var ts; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations, checker); if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { var seenSymbols_2 = new ts.Set(); - var _loop_23 = function (declaration) { + var _loop_21 = function (declaration) { var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { if (!seenSymbols_2.has(symbol)) { seenSymbols_2.add(symbol); @@ -451711,22 +454355,23 @@ var ts; if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); }; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; - _loop_23(declaration); + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + _loop_21(declaration); } } return doc; } function findBaseOfDeclaration(checker, declaration, cb) { var _a; - if (ts.hasStaticModifier(declaration)) - return; var classOrInterfaceDeclaration = ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.kind) === 171 /* SyntaxKind.Constructor */ ? declaration.parent.parent : declaration.parent; if (!classOrInterfaceDeclaration) return; + var isStaticMember = ts.hasStaticModifier(declaration); return ts.firstDefined(ts.getAllSuperTypeNodes(classOrInterfaceDeclaration), function (superTypeNode) { - var symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name); + var baseType = checker.getTypeAtLocation(superTypeNode); + var type = isStaticMember && baseType.symbol ? checker.getTypeOfSymbol(baseType.symbol) : baseType; + var symbol = checker.getPropertyOfType(type, declaration.symbol.name); return symbol ? cb(symbol) : undefined; }); } @@ -451969,70 +454614,6 @@ var ts; return ts.codefix.getSupportedErrorCodes(); } ts.getSupportedCodeFixes = getSupportedCodeFixes; - // Cache host information about script Should be refreshed - // at each language service public entry point, since we don't know when - // the set of scripts handled by the host changes. - var HostCache = /** @class */ (function () { - function HostCache(host, getCanonicalFileName) { - this.host = host; - // script id => script index - this.currentDirectory = host.getCurrentDirectory(); - this.fileNameToEntry = new ts.Map(); - // Initialize the list with the root file names - var rootFileNames = host.getScriptFileNames(); - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* tracing.Phase.Session */, "initializeHostCache", { count: rootFileNames.length }); - for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { - var fileName = rootFileNames_1[_i]; - this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); - } - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); - } - HostCache.prototype.createEntry = function (fileName, path) { - var entry; - var scriptSnapshot = this.host.getScriptSnapshot(fileName); - if (scriptSnapshot) { - entry = { - hostFileName: fileName, - version: this.host.getScriptVersion(fileName), - scriptSnapshot: scriptSnapshot, - scriptKind: ts.getScriptKind(fileName, this.host) - }; - } - else { - entry = fileName; - } - this.fileNameToEntry.set(path, entry); - return entry; - }; - HostCache.prototype.getEntryByPath = function (path) { - return this.fileNameToEntry.get(path); - }; - HostCache.prototype.getHostFileInformation = function (path) { - var entry = this.fileNameToEntry.get(path); - return !ts.isString(entry) ? entry : undefined; - }; - HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - var info = this.getEntryByPath(path) || this.createEntry(fileName, path); - return ts.isString(info) ? undefined : info; // TODO: GH#18217 - }; - HostCache.prototype.getRootFileNames = function () { - var names = []; - this.fileNameToEntry.forEach(function (entry) { - if (ts.isString(entry)) { - names.push(entry); - } - else { - names.push(entry.hostFileName); - } - }); - return names; - }; - HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getHostFileInformation(path); - return (file && file.scriptSnapshot); // TODO: GH#18217 - }; - return HostCache; - }()); var SyntaxTreeCache = /** @class */ (function () { function SyntaxTreeCache(host) { this.host = host; @@ -452294,32 +454875,16 @@ var ts; program = undefined; // TODO: GH#18217 lastTypesRootVersion = typeRootsVersion; } + // This array is retained by the program and will be used to determine if the program is up to date, + // so we need to make a copy in case the host mutates the underlying array - otherwise it would look + // like every program always has the host's current list of root files. + var rootFileNames = host.getScriptFileNames().slice(); // Get a fresh cache of the host information - var hostCache = new HostCache(host, getCanonicalFileName); - var rootFileNames = hostCache.getRootFileNames(); var newSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; var hasChangedAutomaticTypeDirectiveNames = ts.maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); var projectReferences = (_b = host.getProjectReferences) === null || _b === void 0 ? void 0 : _b.call(host); var parsedCommandLines; - var parseConfigHost = { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - fileExists: fileExists, - readFile: readFile, - readDirectory: readDirectory, - trace: ts.maybeBind(host, host.trace), - getCurrentDirectory: function () { return currentDirectory; }, - onUnRecoverableConfigFileDiagnostic: ts.noop, - }; - // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { - return; - } - // IMPORTANT - It is critical from this moment onward that we do not check - // cancellation tokens. We are about to mutate source files from a previous program - // instance. If we cancel midway through, we may end up in an inconsistent state where - // the program points to old source files that have been invalidated because of - // incremental parsing. // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -452331,8 +454896,8 @@ var ts; getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, - fileExists: fileExists, - readFile: readFile, + fileExists: function (fileName) { return host.fileExists(fileName); }, + readFile: function (fileName) { return host.readFile && host.readFile(fileName); }, getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache), realpath: ts.maybeBind(host, host.realpath), directoryExists: function (directoryName) { @@ -452341,19 +454906,56 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, - readDirectory: readDirectory, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, onReleaseParsedCommandLine: onReleaseParsedCommandLine, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, - trace: parseConfigHost.trace, + trace: ts.maybeBind(host, host.trace), resolveModuleNames: ts.maybeBind(host, host.resolveModuleNames), getModuleResolutionCache: ts.maybeBind(host, host.getModuleResolutionCache), resolveTypeReferenceDirectives: ts.maybeBind(host, host.resolveTypeReferenceDirectives), useSourceOfProjectReferenceRedirect: ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect), getParsedCommandLine: getParsedCommandLine, }; + var originalGetSourceFile = compilerHost.getSourceFile; + var getSourceFileWithCache = ts.changeCompilerHostLikeToUseCache(compilerHost, function (fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); }, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArray([compilerHost], args, false)); + }).getSourceFileWithCache; + compilerHost.getSourceFile = getSourceFileWithCache; (_c = host.setCompilerHost) === null || _c === void 0 ? void 0 : _c.call(host, compilerHost); + var parseConfigHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, + readFile: function (fileName) { return compilerHost.readFile(fileName); }, + readDirectory: function () { + var _a; + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return (_a = compilerHost).readDirectory.apply(_a, args); + }, + trace: compilerHost.trace, + getCurrentDirectory: compilerHost.getCurrentDirectory, + onUnRecoverableConfigFileDiagnostic: ts.noop, + }; + // If the program is already up-to-date, we can reuse it + if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, function (fileName) { return compilerHost.fileExists(fileName); }, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + return; + } + // IMPORTANT - It is critical from this moment onward that we do not check + // cancellation tokens. We are about to mutate source files from a previous program + // instance. If we cancel midway through, we may end up in an inconsistent state where + // the program points to old source files that have been invalidated because of + // incremental parsing. var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); var options = { rootNames: rootFileNames, @@ -452363,9 +454965,9 @@ var ts; projectReferences: projectReferences }; program = ts.createProgram(options); - // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. - // It needs to be cleared to allow all collected snapshots to be released - hostCache = undefined; + // 'getOrCreateSourceFile' depends on caching but should be used past this point. + // After this point, the cache needs to be cleared to allow all collected snapshots to be released + compilerHost = undefined; parsedCommandLines = undefined; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during @@ -452405,44 +455007,26 @@ var ts; onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); } } - function fileExists(fileName) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - return entry ? - !ts.isString(entry) : - (!!host.fileExists && host.fileExists(fileName)); - } - function readFile(fileName) { - // stub missing host functionality - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - if (entry) { - return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); - } - return host.readFile && host.readFile(fileName); - } - function readDirectory(path, extensions, exclude, include, depth) { - ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(path, extensions, exclude, include, depth); - } // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); } - function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { - return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); + function getOrCreateSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersionOrOptions, onError, shouldCreateNewSourceFile); } - function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { - ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); + function getOrCreateSourceFileByPath(fileName, path, languageVersionOrOptions, _onError, shouldCreateNewSourceFile) { + ts.Debug.assert(compilerHost, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined // to the program to allow reporting of errors for missing files. - var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path); - if (!hostFileInformation) { + var scriptSnapshot = host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { return undefined; } + var scriptKind = ts.getScriptKind(fileName, host); + var scriptVersion = host.getScriptVersion(fileName); // Check if the language version has changed since we last created a program; if they are the same, // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile // can not be reused. we have to dump all syntax trees and create new ones. @@ -452474,18 +455058,18 @@ var ts; // We do not support the scenario where a host can modify a registered // file's script kind, i.e. in one project some file is treated as ".ts" // and in another as ".js" - if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { - return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); } else { // Release old source file and fall through to aquire new file with new script kind - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); } } // We didn't already have the file. Fall through and acquire it from the registry. } // Could not find this file in the old program, create a new SourceFile for it. - return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); } } // TODO: GH#18217 frequently asserted as defined @@ -452501,6 +455085,61 @@ var ts; var _a; return (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host); } + function updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans) { + var checker = program.getTypeChecker(); + var symbol = getSymbolForProgram(); + if (!symbol) + return false; + for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { + var referencedSymbol = referencedSymbols_1[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + var refNode = getNodeForSpan(ref); + ts.Debug.assertIsDefined(refNode); + if (knownSymbolSpans.has(ref) || ts.FindAllReferences.isDeclarationOfSymbol(refNode, symbol)) { + knownSymbolSpans.add(ref); + ref.isDefinition = true; + var mappedSpan = ts.getMappedDocumentSpan(ref, sourceMapper, ts.maybeBind(host, host.fileExists)); + if (mappedSpan) { + knownSymbolSpans.add(mappedSpan); + } + } + else { + ref.isDefinition = false; + } + } + } + return true; + function getSymbolForProgram() { + for (var _i = 0, referencedSymbols_2 = referencedSymbols; _i < referencedSymbols_2.length; _i++) { + var referencedSymbol = referencedSymbols_2[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + if (knownSymbolSpans.has(ref)) { + var refNode = getNodeForSpan(ref); + ts.Debug.assertIsDefined(refNode); + return checker.getSymbolAtLocation(refNode); + } + var mappedSpan = ts.getMappedDocumentSpan(ref, sourceMapper, ts.maybeBind(host, host.fileExists)); + if (mappedSpan && knownSymbolSpans.has(mappedSpan)) { + var refNode = getNodeForSpan(mappedSpan); + if (refNode) { + return checker.getSymbolAtLocation(refNode); + } + } + } + } + return undefined; + } + function getNodeForSpan(docSpan) { + var sourceFile = program.getSourceFile(docSpan.fileName); + if (!sourceFile) + return undefined; + var rawNode = ts.getTouchingPropertyName(sourceFile, docSpan.textSpan.start); + var adjustedNode = ts.FindAllReferences.Core.getAdjustedNode(rawNode, { use: 1 /* FindAllReferences.FindReferencesUse.References */ }); + return adjustedNode; + } + } function cleanupSemanticCache() { program = undefined; // TODO: GH#18217 } @@ -452509,7 +455148,7 @@ var ts; // Use paths to ensure we are using correct key and paths as document registry could be created with different current directory than host var key_1 = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); ts.forEach(program.getSourceFiles(), function (f) { - return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind, f.impliedNodeFormat); }); program = undefined; // TODO: GH#18217 } @@ -453297,9 +455936,9 @@ var ts; return ts.stringContains(path, "/node_modules/"); } } - function getRenameInfo(fileName, position, options) { + function getRenameInfo(fileName, position, preferences) { synchronizeHostData(); - return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, preferences || {}); } function getRefactorContext(file, positionOrRange, preferences, formatOptions, triggerReason, kind) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; @@ -453426,7 +456065,9 @@ var ts; getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getProgram: getProgram, + getCurrentProgram: function () { return program; }, getAutoImportProvider: getAutoImportProvider, + updateIsDefinitionOfReferencedSymbols: updateIsDefinitionOfReferencedSymbols, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, toLineColumnOffset: toLineColumnOffset, @@ -453578,7 +456219,7 @@ var ts; function getDefaultLibFilePath(options) { // Check __dirname is defined and that we are on a node.js system. if (typeof __dirname !== "undefined") { - return __nccwpck_require__.ab + "typescript1/lib" + ts.directorySeparator + '' + ts.getDefaultLibFileName(options); + return ts.combinePaths(__dirname, ts.getDefaultLibFileName(options)); } throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. "); } @@ -453620,8 +456261,9 @@ var ts; // Get the span in the node based on its syntax return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { - var start = startNode.decorators ? - ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + var lastDecorator = ts.canHaveDecorators(startNode) ? ts.findLast(startNode.modifiers, ts.isDecorator) : undefined; + var start = lastDecorator ? + ts.skipTrivia(sourceFile.text, lastDecorator.end) : startNode.getStart(sourceFile); return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } @@ -453634,8 +456276,20 @@ var ts; } return spanInNode(otherwiseOnNode); } - function spanInNodeArray(nodeArray) { - return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + function spanInNodeArray(nodeArray, node, match) { + if (nodeArray) { + var index = nodeArray.indexOf(node); + if (index >= 0) { + var start = index; + var end = index + 1; + while (start > 0 && match(nodeArray[start - 1])) + start--; + while (end < nodeArray.length && match(nodeArray[end])) + end++; + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray[start].pos), nodeArray[end - 1].end); + } + } + return textSpan(node); } function spanInPreviousNode(node) { return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); @@ -453748,7 +456402,7 @@ var ts; // span in statement return spanInNode(node.statement); case 165 /* SyntaxKind.Decorator */: - return spanInNodeArray(parent.decorators); + return spanInNodeArray(parent.modifiers, node, ts.isDecorator); case 201 /* SyntaxKind.ObjectBindingPattern */: case 202 /* SyntaxKind.ArrayBindingPattern */: return spanInBindingPattern(node); @@ -453911,7 +456565,7 @@ var ts; } // Breakpoint is possible in variableDeclaration only if there is initialization // or its declaration from 'for of' - if (variableDeclaration.initializer || + if ((ts.hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer) || ts.hasSyntacticModifier(variableDeclaration, 1 /* ModifierFlags.Export */) || parent.parent.kind === 244 /* SyntaxKind.ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); @@ -454651,9 +457305,9 @@ var ts; var _this = this; return this.forwardJSONCall("getImplementationAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); }; - LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, options) { + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, preferences) { var _this = this; - return this.forwardJSONCall("getRenameInfo('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getRenameInfo(fileName, position, options); }); + return this.forwardJSONCall("getRenameInfo('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getRenameInfo(fileName, position, preferences); }); }; LanguageServiceShimObject.prototype.getSmartSelectionRange = function (fileName, position) { var _this = this; @@ -454878,7 +457532,8 @@ var ts; } return { resolvedFileName: resolvedFileName, - failedLookupLocations: result.failedLookupLocations + failedLookupLocations: result.failedLookupLocations, + affectingLocations: result.affectingLocations, }; }); }; @@ -454957,7 +457612,7 @@ var ts; if (_this.safeList === undefined) { _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); } - return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry); + return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry, ts.emptyOptions); }); }; return CoreServicesShimObject; @@ -455079,23 +457734,80 @@ if (typeof process === "undefined" || process.browser) { if ( true && module.exports) { module.exports = ts; } +// The following are deprecations for the public API. Deprecated exports are removed from the compiler itself +// and compatible implementations are added here, along with an appropriate deprecation warning using +// the `@deprecated` JSDoc tag as well as the `Debug.deprecate` API. +// +// Deprecations fall into one of three categories: +// +// - "soft" - Soft deprecations are indicated with the `@deprecated` JSDoc Tag. +// - "warn" - Warning deprecations are indicated with the `@deprecated` JSDoc Tag and a diagnostic message (assuming a compatible host). +// - "error" - Error deprecations are either indicated with the `@deprecated` JSDoc tag and will throw a `TypeError` when invoked, or removed from the API entirely. +// +// Once we have determined enough time has passed after a deprecation has been marked as `"warn"` or `"error"`, it will be removed from the public API. +/* @internal */ +var ts; +(function (ts) { + function createOverload(name, overloads, binder, deprecations) { + Object.defineProperty(call, "name", __assign(__assign({}, Object.getOwnPropertyDescriptor(call, "name")), { value: name })); + if (deprecations) { + for (var _i = 0, _a = Object.keys(deprecations); _i < _a.length; _i++) { + var key = _a[_i]; + var index = +key; + if (!isNaN(index) && ts.hasProperty(overloads, "".concat(index))) { + overloads[index] = ts.Debug.deprecate(overloads[index], __assign(__assign({}, deprecations[index]), { name: name })); + } + } + } + var bind = createBinder(overloads, binder); + return call; + function call() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var index = bind(args); + var fn = index !== undefined ? overloads[index] : undefined; + if (typeof fn === "function") { + return fn.apply(void 0, args); + } + throw new TypeError("Invalid arguments"); + } + } + ts.createOverload = createOverload; + function createBinder(overloads, binder) { + return function (args) { + for (var i = 0; ts.hasProperty(overloads, "".concat(i)) && ts.hasProperty(binder, "".concat(i)); i++) { + var fn = binder[i]; + if (fn(args)) { + return i; + } + } + }; + } + // NOTE: We only use this "builder" because we don't infer correctly when calling `createOverload` directly in < TS 4.7, + // but lib is currently at TS 4.4. We can switch to directly calling `createOverload` when we update LKG in main. + function buildOverload(name) { + return { + overload: function (overloads) { return ({ + bind: function (binder) { return ({ + finish: function () { return createOverload(name, overloads, binder); }, + deprecate: function (deprecations) { return ({ + finish: function () { return createOverload(name, overloads, binder, deprecations); } + }); } + }); } + }); } + }; + } + ts.buildOverload = buildOverload; +})(ts || (ts = {})); +// DEPRECATION: Node factory top-level exports +// DEPRECATION PLAN: +// - soft: 4.0 +// - warn: 4.1 +// - error: 5.0 var ts; (function (ts) { - // The following are deprecations for the public API. Deprecated exports are removed from the compiler itself - // and compatible implementations are added here, along with an appropriate deprecation warning using - // the `@deprecated` JSDoc tag as well as the `Debug.deprecate` API. - // - // Deprecations fall into one of three categories: - // - // * "soft" - Soft deprecations are indicated with the `@deprecated` JSDoc Tag. - // * "warn" - Warning deprecations are indicated with the `@deprecated` JSDoc Tag and a diagnostic message (assuming a compatible host) - // * "error" - Error deprecations are indicated with the `@deprecated` JSDoc tag and will throw a `TypeError` when invoked. - // DEPRECATION: Node factory top-level exports - // DEPRECATION PLAN: - // - soft: 4.0 - // - warn: 4.1 - // - error: TBD - // #region Node factory top-level exports // NOTE: These exports are deprecated in favor of using a `NodeFactory` instance and exist here purely for backwards compatibility reasons. var factoryDeprecation = { since: "4.0", warnAfter: "4.1", message: "Use the appropriate method on 'ts.factory' or the 'factory' supplied by your transformation context instead." }; /** @deprecated Use `factory.createNodeArray` or the factory supplied by your transformation context instead. */ @@ -455965,13 +458677,14 @@ var ts; ts.setParent(clone, node.parent); return clone; }, { since: "4.0", warnAfter: "4.1", message: "Use an appropriate `factory.update...` method instead, use `setCommentRange` or `setSourceMapRange`, and avoid setting `parent`." }); - // #endregion Node Factory top-level exports - // DEPRECATION: Renamed node tests - // DEPRECATION PLAN: - // - soft: 4.0 - // - warn: 4.1 - // - error: TBD - // #region Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Renamed node tests +// DEPRECATION PLAN: +// - soft: 4.0 +// - warn: 4.1 +// - error: TBD +var ts; +(function (ts) { /** @deprecated Use `isTypeAssertionExpression` instead. */ ts.isTypeAssertion = ts.Debug.deprecate(function isTypeAssertion(node) { return node.kind === 211 /* SyntaxKind.TypeAssertionExpression */; @@ -455980,13 +458693,14 @@ var ts; warnAfter: "4.1", message: "Use `isTypeAssertionExpression` instead." }); - // #endregion - // DEPRECATION: Renamed node tests - // DEPRECATION PLAN: - // - soft: 4.2 - // - warn: 4.3 - // - error: TBD - // #region Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Renamed node tests +// DEPRECATION PLAN: +// - soft: 4.2 +// - warn: 4.3 +// - error: 5.0 +var ts; +(function (ts) { /** * @deprecated Use `isMemberName` instead. */ @@ -455997,7 +458711,1422 @@ var ts; warnAfter: "4.3", message: "Use `isMemberName` instead." }); - // #endregion Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Overloads for createConstructorTypeNode/updateConstructorTypeNode that do not accept 'modifiers' +// DEPRECATION PLAN: +// - soft: 4.2 +// - warn: 4.3 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createConstructorTypeNode = factory.createConstructorTypeNode, updateConstructorTypeNode = factory.updateConstructorTypeNode; + factory.createConstructorTypeNode = ts.buildOverload("createConstructorTypeNode") + .overload({ + 0: function (modifiers, typeParameters, parameters, type) { + return createConstructorTypeNode(modifiers, typeParameters, parameters, type); + }, + 1: function (typeParameters, parameters, type) { + return createConstructorTypeNode(/*modifiers*/ undefined, typeParameters, parameters, type); + }, + }) + .bind({ + 0: function (args) { return args.length === 4; }, + 1: function (args) { return args.length === 3; }, + }) + .deprecate({ + 1: { since: "4.2", warnAfter: "4.3", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + factory.updateConstructorTypeNode = ts.buildOverload("updateConstructorTypeNode") + .overload({ + 0: function (node, modifiers, typeParameters, parameters, type) { + return updateConstructorTypeNode(node, modifiers, typeParameters, parameters, type); + }, + 1: function (node, typeParameters, parameters, type) { + return updateConstructorTypeNode(node, node.modifiers, typeParameters, parameters, type); + } + }) + .bind({ + 0: function (args) { return args.length === 5; }, + 1: function (args) { return args.length === 4; }, + }) + .deprecate({ + 1: { since: "4.2", warnAfter: "4.3", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Overloads to createImportTypeNode/updateImportTypeNode that do not accept `assertions` +// DEPRECATION PLAN: +// - soft: 4.6 +// - warn: 4.7 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createImportTypeNode = factory.createImportTypeNode, updateImportTypeNode = factory.updateImportTypeNode; + factory.createImportTypeNode = ts.buildOverload("createImportTypeNode") + .overload({ + 0: function (argument, assertions, qualifier, typeArguments, isTypeOf) { + return createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf); + }, + 1: function (argument, qualifier, typeArguments, isTypeOf) { + return createImportTypeNode(argument, /*assertions*/ undefined, qualifier, typeArguments, isTypeOf); + }, + }) + .bind({ + 0: function (_a) { + var assertions = _a[1], qualifier = _a[2], typeArguments = _a[3], isTypeOf = _a[4]; + return (assertions === undefined || ts.isImportTypeAssertionContainer(assertions)) && + (qualifier === undefined || !ts.isArray(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + 1: function (_a) { + var qualifier = _a[1], typeArguments = _a[2], isTypeOf = _a[3], other = _a[4]; + return (other === undefined) && + (qualifier === undefined || ts.isEntityName(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + }) + .deprecate({ + 1: { since: "4.6", warnAfter: "4.7", message: "Use the overload that accepts 'assertions'" } + }) + .finish(); + factory.updateImportTypeNode = ts.buildOverload("updateImportTypeNode") + .overload({ + 0: function (node, argument, assertions, qualifier, typeArguments, isTypeOf) { + return updateImportTypeNode(node, argument, assertions, qualifier, typeArguments, isTypeOf); + }, + 1: function (node, argument, qualifier, typeArguments, isTypeOf) { + return updateImportTypeNode(node, argument, node.assertions, qualifier, typeArguments, isTypeOf); + }, + }) + .bind({ + 0: function (_a) { + var assertions = _a[2], qualifier = _a[3], typeArguments = _a[4], isTypeOf = _a[5]; + return (assertions === undefined || ts.isImportTypeAssertionContainer(assertions)) && + (qualifier === undefined || !ts.isArray(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + 1: function (_a) { + var qualifier = _a[2], typeArguments = _a[3], isTypeOf = _a[4], other = _a[5]; + return (other === undefined) && + (qualifier === undefined || ts.isEntityName(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + }). + deprecate({ + 1: { since: "4.6", warnAfter: "4.7", message: "Use the overload that accepts 'assertions'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Overloads to createTypeParameter/updateTypeParameter that does not accept `modifiers` +// DEPRECATION PLAN: +// - soft: 4.7 +// - warn: 4.8 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createTypeParameterDeclaration = factory.createTypeParameterDeclaration, updateTypeParameterDeclaration = factory.updateTypeParameterDeclaration; + factory.createTypeParameterDeclaration = ts.buildOverload("createTypeParameterDeclaration") + .overload({ + 0: function (modifiers, name, constraint, defaultType) { + return createTypeParameterDeclaration(modifiers, name, constraint, defaultType); + }, + 1: function (name, constraint, defaultType) { + return createTypeParameterDeclaration(/*modifiers*/ undefined, name, constraint, defaultType); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0]; + return (modifiers === undefined || ts.isArray(modifiers)); + }, + 1: function (_a) { + var name = _a[0]; + return (name !== undefined && !ts.isArray(name)); + }, + }) + .deprecate({ + 1: { since: "4.7", warnAfter: "4.8", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + factory.updateTypeParameterDeclaration = ts.buildOverload("updateTypeParameterDeclaration") + .overload({ + 0: function (node, modifiers, name, constraint, defaultType) { + return updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType); + }, + 1: function (node, name, constraint, defaultType) { + return updateTypeParameterDeclaration(node, node.modifiers, name, constraint, defaultType); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1]; + return (modifiers === undefined || ts.isArray(modifiers)); + }, + 1: function (_a) { + var name = _a[1]; + return (name !== undefined && !ts.isArray(name)); + }, + }) + .deprecate({ + 1: { since: "4.7", warnAfter: "4.8", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Deprecate passing `decorators` separate from `modifiers` +// DEPRECATION PLAN: +// - soft: 4.8 +// - warn: 4.9 +// - error: 5.0 +var ts; +(function (ts) { + var MUST_MERGE = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators have been combined with modifiers. Callers should switch to an overload that does not accept a 'decorators' parameter." }; + var DISALLOW_DECORATORS = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators are no longer supported for this function. Callers should switch to an overload that does not accept a 'decorators' parameter." }; + var DISALLOW_DECORATORS_AND_MODIFIERS = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators and modifiers are no longer supported for this function. Callers should switch to an overload that does not accept the 'decorators' and 'modifiers' parameters." }; + function patchNodeFactory(factory) { + var createParameterDeclaration = factory.createParameterDeclaration, updateParameterDeclaration = factory.updateParameterDeclaration, createPropertyDeclaration = factory.createPropertyDeclaration, updatePropertyDeclaration = factory.updatePropertyDeclaration, createMethodDeclaration = factory.createMethodDeclaration, updateMethodDeclaration = factory.updateMethodDeclaration, createConstructorDeclaration = factory.createConstructorDeclaration, updateConstructorDeclaration = factory.updateConstructorDeclaration, createGetAccessorDeclaration = factory.createGetAccessorDeclaration, updateGetAccessorDeclaration = factory.updateGetAccessorDeclaration, createSetAccessorDeclaration = factory.createSetAccessorDeclaration, updateSetAccessorDeclaration = factory.updateSetAccessorDeclaration, createIndexSignature = factory.createIndexSignature, updateIndexSignature = factory.updateIndexSignature, createClassStaticBlockDeclaration = factory.createClassStaticBlockDeclaration, updateClassStaticBlockDeclaration = factory.updateClassStaticBlockDeclaration, createClassExpression = factory.createClassExpression, updateClassExpression = factory.updateClassExpression, createFunctionDeclaration = factory.createFunctionDeclaration, updateFunctionDeclaration = factory.updateFunctionDeclaration, createClassDeclaration = factory.createClassDeclaration, updateClassDeclaration = factory.updateClassDeclaration, createInterfaceDeclaration = factory.createInterfaceDeclaration, updateInterfaceDeclaration = factory.updateInterfaceDeclaration, createTypeAliasDeclaration = factory.createTypeAliasDeclaration, updateTypeAliasDeclaration = factory.updateTypeAliasDeclaration, createEnumDeclaration = factory.createEnumDeclaration, updateEnumDeclaration = factory.updateEnumDeclaration, createModuleDeclaration = factory.createModuleDeclaration, updateModuleDeclaration = factory.updateModuleDeclaration, createImportEqualsDeclaration = factory.createImportEqualsDeclaration, updateImportEqualsDeclaration = factory.updateImportEqualsDeclaration, createImportDeclaration = factory.createImportDeclaration, updateImportDeclaration = factory.updateImportDeclaration, createExportAssignment = factory.createExportAssignment, updateExportAssignment = factory.updateExportAssignment, createExportDeclaration = factory.createExportDeclaration, updateExportDeclaration = factory.updateExportDeclaration; + factory.createParameterDeclaration = ts.buildOverload("createParameterDeclaration") + .overload({ + 0: function (modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer); + }, + 1: function (decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return createParameterDeclaration(ts.concatenate(decorators, modifiers), dotDotDotToken, name, questionToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var dotDotDotToken = _a[1], name = _a[2], questionToken = _a[3], type = _a[4], initializer = _a[5], other = _a[6]; + return (other === undefined) && + (dotDotDotToken === undefined || !ts.isArray(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[1], dotDotDotToken = _a[2], name = _a[3], questionToken = _a[4], type = _a[5], initializer = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (dotDotDotToken === undefined || typeof dotDotDotToken === "object" && ts.isDotDotDotToken(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateParameterDeclaration = ts.buildOverload("updateParameterDeclaration") + .overload({ + 0: function (node, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer); + }, + 1: function (node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return updateParameterDeclaration(node, ts.concatenate(decorators, modifiers), dotDotDotToken, name, questionToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var dotDotDotToken = _a[2], name = _a[3], questionToken = _a[4], type = _a[5], initializer = _a[6], other = _a[7]; + return (other === undefined) && + (dotDotDotToken === undefined || !ts.isArray(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[2], dotDotDotToken = _a[3], name = _a[4], questionToken = _a[5], type = _a[6], initializer = _a[7]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (dotDotDotToken === undefined || typeof dotDotDotToken === "object" && ts.isDotDotDotToken(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createPropertyDeclaration = ts.buildOverload("createPropertyDeclaration") + .overload({ + 0: function (modifiers, name, questionOrExclamationToken, type, initializer) { + return createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer); + }, + 1: function (decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return createPropertyDeclaration(ts.concatenate(decorators, modifiers), name, questionOrExclamationToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], questionOrExclamationToken = _a[2], type = _a[3], initializer = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (questionOrExclamationToken === undefined || typeof questionOrExclamationToken === "object" && ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], questionOrExclamationToken = _a[3], type = _a[4], initializer = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionOrExclamationToken === undefined || ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updatePropertyDeclaration = ts.buildOverload("updatePropertyDeclaration") + .overload({ + 0: function (node, modifiers, name, questionOrExclamationToken, type, initializer) { + return updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer); + }, + 1: function (node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return updatePropertyDeclaration(node, ts.concatenate(decorators, modifiers), name, questionOrExclamationToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], questionOrExclamationToken = _a[3], type = _a[4], initializer = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (questionOrExclamationToken === undefined || typeof questionOrExclamationToken === "object" && ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], questionOrExclamationToken = _a[4], type = _a[5], initializer = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionOrExclamationToken === undefined || ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createMethodDeclaration = ts.buildOverload("createMethodDeclaration") + .overload({ + 0: function (modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + 1: function (decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return createMethodDeclaration(ts.concatenate(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[1], name = _a[2], questionToken = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7], other = _a[8]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || !ts.some(parameters, ts.isTypeParameterDeclaration)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], asteriskToken = _a[2], name = _a[3], questionToken = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken === "object" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || !ts.isArray(questionToken)) && + (typeParameters === undefined || !ts.some(typeParameters, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateMethodDeclaration = ts.buildOverload("updateMethodDeclaration") + .overload({ + 0: function (node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + 1: function (node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return updateMethodDeclaration(node, ts.concatenate(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[2], name = _a[3], questionToken = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8], other = _a[9]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || !ts.some(parameters, ts.isTypeParameterDeclaration)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], asteriskToken = _a[3], name = _a[4], questionToken = _a[5], typeParameters = _a[6], parameters = _a[7], type = _a[8], body = _a[9]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken === "object" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || !ts.isArray(questionToken)) && + (typeParameters === undefined || !ts.some(typeParameters, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createConstructorDeclaration = ts.buildOverload("createConstructorDeclaration") + .overload({ + 0: function (modifiers, parameters, body) { + return createConstructorDeclaration(modifiers, parameters, body); + }, + 1: function (_decorators, modifiers, parameters, body) { + return createConstructorDeclaration(modifiers, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], parameters = _a[1], body = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || !ts.some(modifiers, ts.isDecorator)) && + (parameters === undefined || !ts.some(parameters, ts.isModifier)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], parameters = _a[2], body = _a[3]; + return (decorators === undefined || !ts.some(decorators, ts.isModifier)) && + (modifiers === undefined || !ts.some(modifiers, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateConstructorDeclaration = ts.buildOverload("updateConstructorDeclaration") + .overload({ + 0: function (node, modifiers, parameters, body) { + return updateConstructorDeclaration(node, modifiers, parameters, body); + }, + 1: function (node, _decorators, modifiers, parameters, body) { + return updateConstructorDeclaration(node, modifiers, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], parameters = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || !ts.some(modifiers, ts.isDecorator)) && + (parameters === undefined || !ts.some(parameters, ts.isModifier)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], parameters = _a[3], body = _a[4]; + return (decorators === undefined || !ts.some(decorators, ts.isModifier)) && + (modifiers === undefined || !ts.some(modifiers, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createGetAccessorDeclaration = ts.buildOverload("createGetAccessorDeclaration") + .overload({ + 0: function (modifiers, name, parameters, type, body) { + return createGetAccessorDeclaration(modifiers, name, parameters, type, body); + }, + 1: function (decorators, modifiers, name, parameters, type, body) { + return createGetAccessorDeclaration(ts.concatenate(decorators, modifiers), name, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], parameters = _a[2], type = _a[3], body = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], parameters = _a[3], type = _a[4], body = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateGetAccessorDeclaration = ts.buildOverload("updateGetAccessorDeclaration") + .overload({ + 0: function (node, modifiers, name, parameters, type, body) { + return updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body); + }, + 1: function (node, decorators, modifiers, name, parameters, type, body) { + return updateGetAccessorDeclaration(node, ts.concatenate(decorators, modifiers), name, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], parameters = _a[3], type = _a[4], body = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], parameters = _a[4], type = _a[5], body = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createSetAccessorDeclaration = ts.buildOverload("createSetAccessorDeclaration") + .overload({ + 0: function (modifiers, name, parameters, body) { + return createSetAccessorDeclaration(modifiers, name, parameters, body); + }, + 1: function (decorators, modifiers, name, parameters, body) { + return createSetAccessorDeclaration(ts.concatenate(decorators, modifiers), name, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], parameters = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], parameters = _a[3], body = _a[4]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateSetAccessorDeclaration = ts.buildOverload("updateSetAccessorDeclaration") + .overload({ + 0: function (node, modifiers, name, parameters, body) { + return updateSetAccessorDeclaration(node, modifiers, name, parameters, body); + }, + 1: function (node, decorators, modifiers, name, parameters, body) { + return updateSetAccessorDeclaration(node, ts.concatenate(decorators, modifiers), name, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], parameters = _a[3], body = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], parameters = _a[4], body = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createIndexSignature = ts.buildOverload("createIndexSignature") + .overload({ + 0: function (modifiers, parameters, type) { + return createIndexSignature(modifiers, parameters, type); + }, + 1: function (_decorators, modifiers, parameters, type) { + return createIndexSignature(modifiers, parameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], parameters = _a[1], type = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], parameters = _a[2], type = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateIndexSignature = ts.buildOverload("updateIndexSignature") + .overload({ + 0: function (node, modifiers, parameters, type) { + return updateIndexSignature(node, modifiers, parameters, type); + }, + 1: function (node, _decorators, modifiers, parameters, type) { + return updateIndexSignature(node, modifiers, parameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], parameters = _a[2], type = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], parameters = _a[3], type = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createClassStaticBlockDeclaration = ts.buildOverload("createClassStaticBlockDeclaration") + .overload({ + 0: function (body) { + return createClassStaticBlockDeclaration(body); + }, + 1: function (_decorators, _modifiers, body) { + return createClassStaticBlockDeclaration(body); + }, + }) + .bind({ + 0: function (_a) { + var body = _a[0], other1 = _a[1], other2 = _a[2]; + return (other1 === undefined) && + (other2 === undefined) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], body = _a[2]; + return (decorators === undefined || ts.isArray(decorators)) && + (modifiers === undefined || ts.isArray(decorators)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS_AND_MODIFIERS + }) + .finish(); + factory.updateClassStaticBlockDeclaration = ts.buildOverload("updateClassStaticBlockDeclaration") + .overload({ + 0: function (node, body) { + return updateClassStaticBlockDeclaration(node, body); + }, + 1: function (node, _decorators, _modifiers, body) { + return updateClassStaticBlockDeclaration(node, body); + }, + }) + .bind({ + 0: function (_a) { + var body = _a[1], other1 = _a[2], other2 = _a[3]; + return (other1 === undefined) && + (other2 === undefined) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], body = _a[3]; + return (decorators === undefined || ts.isArray(decorators)) && + (modifiers === undefined || ts.isArray(decorators)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS_AND_MODIFIERS + }) + .finish(); + factory.createClassExpression = ts.buildOverload("createClassExpression") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createClassExpression(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createClassExpression(ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateClassExpression = ts.buildOverload("updateClassExpression") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassExpression(node, ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createFunctionDeclaration = ts.buildOverload("createFunctionDeclaration") + .overload({ + 0: function (modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + 1: function (_decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[1], name = _a[2], typeParameters = _a[3], parameters = _a[4], type = _a[5], body = _a[6], other = _a[7]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isIdentifier(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], asteriskToken = _a[2], name = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken !== "string" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateFunctionDeclaration = ts.buildOverload("updateFunctionDeclaration") + .overload({ + 0: function (node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + 1: function (node, _decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[2], name = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7], other = _a[8]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || ts.isIdentifier(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], asteriskToken = _a[3], name = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken !== "string" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createClassDeclaration = ts.buildOverload("createClassDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createClassDeclaration(ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function () { return true; }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateClassDeclaration = ts.buildOverload("updateClassDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassDeclaration(node, ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createInterfaceDeclaration = ts.buildOverload("createInterfaceDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (_decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateInterfaceDeclaration = ts.buildOverload("updateInterfaceDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, _decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createTypeAliasDeclaration = ts.buildOverload("createTypeAliasDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, type) { + return createTypeAliasDeclaration(modifiers, name, typeParameters, type); + }, + 1: function (_decorators, modifiers, name, typeParameters, type) { + return createTypeAliasDeclaration(modifiers, name, typeParameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], typeParameters = _a[2], type = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], typeParameters = _a[3], type = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateTypeAliasDeclaration = ts.buildOverload("updateTypeAliasDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, type) { + return updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type); + }, + 1: function (node, _decorators, modifiers, name, typeParameters, type) { + return updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], type = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], typeParameters = _a[4], type = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createEnumDeclaration = ts.buildOverload("createEnumDeclaration") + .overload({ + 0: function (modifiers, name, members) { + return createEnumDeclaration(modifiers, name, members); + }, + 1: function (_decorators, modifiers, name, members) { + return createEnumDeclaration(modifiers, name, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], members = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], members = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateEnumDeclaration = ts.buildOverload("updateEnumDeclaration") + .overload({ + 0: function (node, modifiers, name, members) { + return updateEnumDeclaration(node, modifiers, name, members); + }, + 1: function (node, _decorators, modifiers, name, members) { + return updateEnumDeclaration(node, modifiers, name, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], members = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], members = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createModuleDeclaration = ts.buildOverload("createModuleDeclaration") + .overload({ + 0: function (modifiers, name, body, flags) { + return createModuleDeclaration(modifiers, name, body, flags); + }, + 1: function (_decorators, modifiers, name, body, flags) { + return createModuleDeclaration(modifiers, name, body, flags); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], body = _a[2], flags = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name !== undefined && !ts.isArray(name)) && + (body === undefined || ts.isModuleBody(body)) && + (flags === undefined || typeof flags === "number"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], body = _a[3], flags = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name !== undefined && ts.isModuleName(name)) && + (body === undefined || typeof body === "object") && + (flags === undefined || typeof flags === "number"); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateModuleDeclaration = ts.buildOverload("updateModuleDeclaration") + .overload({ + 0: function (node, modifiers, name, body) { + return updateModuleDeclaration(node, modifiers, name, body); + }, + 1: function (node, _decorators, modifiers, name, body) { + return updateModuleDeclaration(node, modifiers, name, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (body === undefined || ts.isModuleBody(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], body = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name !== undefined && ts.isModuleName(name)) && + (body === undefined || ts.isModuleBody(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createImportEqualsDeclaration = ts.buildOverload("createImportEqualsDeclaration") + .overload({ + 0: function (modifiers, isTypeOnly, name, moduleReference) { + return createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference); + }, + 1: function (_decorators, modifiers, isTypeOnly, name, moduleReference) { + return createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isTypeOnly = _a[1], name = _a[2], moduleReference = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name !== "boolean") && + (typeof moduleReference !== "string"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isTypeOnly = _a[2], name = _a[3], moduleReference = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name === "string" || ts.isIdentifier(name)) && + (moduleReference !== undefined && ts.isModuleReference(moduleReference)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateImportEqualsDeclaration = ts.buildOverload("updateImportEqualsDeclaration") + .overload({ + 0: function (node, modifiers, isTypeOnly, name, moduleReference) { + return updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference); + }, + 1: function (node, _decorators, modifiers, isTypeOnly, name, moduleReference) { + return updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], isTypeOnly = _a[2], name = _a[3], moduleReference = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name !== "boolean") && + (typeof moduleReference !== "string"); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], isTypeOnly = _a[3], name = _a[4], moduleReference = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name === "string" || ts.isIdentifier(name)) && + (moduleReference !== undefined && ts.isModuleReference(moduleReference)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createImportDeclaration = ts.buildOverload("createImportDeclaration") + .overload({ + 0: function (modifiers, importClause, moduleSpecifier, assertClause) { + return createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + }, + 1: function (_decorators, modifiers, importClause, moduleSpecifier, assertClause) { + return createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], importClause = _a[1], moduleSpecifier = _a[2], assertClause = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (importClause === undefined || !ts.isArray(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], importClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (importClause === undefined || ts.isImportClause(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateImportDeclaration = ts.buildOverload("updateImportDeclaration") + .overload({ + 0: function (node, modifiers, importClause, moduleSpecifier, assertClause) { + return updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause); + }, + 1: function (node, _decorators, modifiers, importClause, moduleSpecifier, assertClause) { + return updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], importClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (importClause === undefined || !ts.isArray(importClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], importClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (importClause === undefined || ts.isImportClause(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createExportAssignment = ts.buildOverload("createExportAssignment") + .overload({ + 0: function (modifiers, isExportEquals, expression) { + return createExportAssignment(modifiers, isExportEquals, expression); + }, + 1: function (_decorators, modifiers, isExportEquals, expression) { + return createExportAssignment(modifiers, isExportEquals, expression); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isExportEquals = _a[1], expression = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isExportEquals === undefined || typeof isExportEquals === "boolean") && + (typeof expression === "object"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isExportEquals = _a[2], expression = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isExportEquals === undefined || typeof isExportEquals === "boolean") && + (expression !== undefined && ts.isExpression(expression)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateExportAssignment = ts.buildOverload("updateExportAssignment") + .overload({ + 0: function (node, modifiers, expression) { + return updateExportAssignment(node, modifiers, expression); + }, + 1: function (node, _decorators, modifiers, expression) { + return updateExportAssignment(node, modifiers, expression); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], expression = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (expression !== undefined && !ts.isArray(expression)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], expression = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (expression !== undefined && ts.isExpression(expression)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createExportDeclaration = ts.buildOverload("createExportDeclaration") + .overload({ + 0: function (modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + 1: function (_decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isTypeOnly = _a[1], exportClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (typeof isTypeOnly === "boolean") && + (typeof exportClause !== "boolean") && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isTypeOnly = _a[2], exportClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (typeof isTypeOnly === "boolean") && + (exportClause === undefined || ts.isNamedExportBindings(exportClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateExportDeclaration = ts.buildOverload("updateExportDeclaration") + .overload({ + 0: function (node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + 1: function (node, _decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], isTypeOnly = _a[2], exportClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5], other = _a[6]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (typeof isTypeOnly === "boolean") && + (typeof exportClause !== "boolean") && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], isTypeOnly = _a[3], exportClause = _a[4], moduleSpecifier = _a[5], assertClause = _a[6]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (typeof isTypeOnly === "boolean") && + (exportClause === undefined || ts.isNamedExportBindings(exportClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + if (typeof console !== "undefined") { + ts.Debug.loggingHost = { + log: function (level, s) { + switch (level) { + case ts.LogLevel.Error: return console.error(s); + case ts.LogLevel.Warning: return console.warn(s); + case ts.LogLevel.Info: return console.log(s); + case ts.LogLevel.Verbose: return console.log(s); + } + } + }; + } })(ts || (ts = {})); diff --git a/package-lock.json b/package-lock.json index 25ba1ca7..a606652f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10596,9 +10596,9 @@ } }, "typescript": { - "version": "4.7.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz", - "integrity": "sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==", + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.8.4.tgz", + "integrity": "sha512-QCh+85mCy+h0IGff8r5XWzOVSbBO+KfeYrMQh7NJ58QujwcE22u+NUSmUxqF+un70P9GXKxa2HCNiTTMJknyjQ==", "dev": true }, "union-value": { diff --git a/package.json b/package.json index f9b0f791..a8b1d35a 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,6 @@ "js-yaml": "^4.1.0", "prettier": "^2.7.1", "ts-jest": "^26.5.6", - "typescript": "^4.7.4" + "typescript": "^4.8.4" } }