@@ -15,31 +15,6 @@
"use strict";
-var __extends = (this && this.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
-})();
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
@@ -82,13 +57,35 @@
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
+var __extends = (this && this.__extends) || (function () {
+ var extendStatics = function (d, b) {
+ extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+ return extendStatics(d, b);
+ };
+ return function (d, b) {
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ };
+})();
+var __rest = (this && this.__rest) || function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
+ t[p[i]] = s[p[i]];
+ return t;
+};
var ts;
(function (ts) {
// WARNING: The script `configureNightly.ts` uses a regexp to parse out these values.
// If changing the text in this section, be sure to test `configureNightly` too.
- ts.versionMajorMinor = "3.3";
+ ts.versionMajorMinor = "3.4";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".4000";
+ ts.version = ts.versionMajorMinor + ".1";
})(ts || (ts = {}));
(function (ts) {
/* @internal */
@@ -144,19 +141,25 @@
// Keep the class inside a function so it doesn't get compiled if it's not used.
function shimMap() {
var MapIterator = /** @class */ (function () {
- function MapIterator(data, selector) {
- this.index = 0;
- this.data = data;
+ function MapIterator(currentEntry, selector) {
+ this.currentEntry = currentEntry;
this.selector = selector;
- this.keys = Object.keys(data);
}
MapIterator.prototype.next = function () {
- var index = this.index;
- if (index < this.keys.length) {
- this.index++;
- return { value: this.selector(this.data, this.keys[index]), done: false };
+ // Navigate to the next entry.
+ while (this.currentEntry) {
+ var skipNext = !!this.currentEntry.skipNext;
+ this.currentEntry = this.currentEntry.nextEntry;
+ if (!skipNext) {
+ break;
+ }
}
+ if (this.currentEntry) {
+ return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false };
+ }
+ else {
return { value: undefined, done: true };
+ }
};
return MapIterator;
}());
@@ -164,15 +167,36 @@
function class_1() {
this.data = createDictionaryObject();
this.size = 0;
+ // Create a first (stub) map entry that will not contain a key
+ // and value but serves as starting point for iterators.
+ this.firstEntry = {};
+ // When the map is empty, the last entry is the same as the
+ // first one.
+ this.lastEntry = this.firstEntry;
}
class_1.prototype.get = function (key) {
- return this.data[key];
+ var entry = this.data[key];
+ return entry && entry.value;
};
class_1.prototype.set = function (key, value) {
if (!this.has(key)) {
this.size++;
+ // Create a new entry that will be appended at the
+ // end of the linked list.
+ var newEntry = {
+ key: key,
+ value: value
+ };
+ this.data[key] = newEntry;
+ // Adjust the references.
+ var previousLastEntry = this.lastEntry;
+ previousLastEntry.nextEntry = newEntry;
+ newEntry.previousEntry = previousLastEntry;
+ this.lastEntry = newEntry;
+ }
+ else {
+ this.data[key].value = value;
}
- this.data[key] = value;
return this;
};
class_1.prototype.has = function (key) {
@@ -182,7 +206,28 @@
class_1.prototype.delete = function (key) {
if (this.has(key)) {
this.size--;
+ var entry = this.data[key];
delete this.data[key];
+ // Adjust the linked list references of the neighbor entries.
+ var previousEntry = entry.previousEntry;
+ previousEntry.nextEntry = entry.nextEntry;
+ if (entry.nextEntry) {
+ entry.nextEntry.previousEntry = previousEntry;
+ }
+ // When the deleted entry was the last one, we need to
+ // adust the lastEntry reference.
+ if (this.lastEntry === entry) {
+ this.lastEntry = previousEntry;
+ }
+ // Adjust the forward reference of the deleted entry
+ // in case an iterator still references it. This allows us
+ // to throw away the entry, but when an active iterator
+ // (which points to the current entry) continues, it will
+ // navigate to the entry that originally came before the
+ // current one and skip it.
+ entry.previousEntry = undefined;
+ entry.nextEntry = previousEntry;
+ entry.skipNext = true;
return true;
}
return false;
@@ -190,24 +235,46 @@
class_1.prototype.clear = function () {
this.data = createDictionaryObject();
this.size = 0;
+ // Reset the linked list. Note that we must adjust the forward
+ // references of the deleted entries to ensure iterators stuck
+ // in the middle of the list don't continue with deleted entries,
+ // but can continue with new entries added after the clear()
+ // operation.
+ var firstEntry = this.firstEntry;
+ var currentEntry = firstEntry.nextEntry;
+ while (currentEntry) {
+ var nextEntry = currentEntry.nextEntry;
+ currentEntry.previousEntry = undefined;
+ currentEntry.nextEntry = firstEntry;
+ currentEntry.skipNext = true;
+ currentEntry = nextEntry;
+ }
+ firstEntry.nextEntry = undefined;
+ this.lastEntry = firstEntry;
};
class_1.prototype.keys = function () {
- return new MapIterator(this.data, function (_data, key) { return key; });
+ return new MapIterator(this.firstEntry, function (key) { return key; });
};
class_1.prototype.values = function () {
- return new MapIterator(this.data, function (data, key) { return data[key]; });
+ return new MapIterator(this.firstEntry, function (_key, value) { return value; });
};
class_1.prototype.entries = function () {
- return new MapIterator(this.data, function (data, key) { return [key, data[key]]; });
+ return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; });
};
class_1.prototype.forEach = function (action) {
- for (var key in this.data) {
- action(this.data[key], key);
+ var iterator = this.entries();
+ while (true) {
+ var _a = iterator.next(), entry = _a.value, done = _a.done;
+ if (done) {
+ break;
+ }
+ action(entry[1], entry[0]);
}
};
return class_1;
}());
}
+ ts.shimMap = shimMap;
function length(array) {
return array ? array.length : 0;
}
@@ -755,7 +822,7 @@
}
/**
* Deduplicates an unsorted array.
- * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
+ * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
* @param comparer An optional `Comparer` used to sort entries before comparison, though the
* result will remain in the original order in `array`.
*/
@@ -971,6 +1038,21 @@
} };
}
ts.arrayIterator = arrayIterator;
+ function arrayReverseIterator(array) {
+ var i = array.length;
+ return {
+ next: function () {
+ if (i === 0) {
+ return { value: undefined, done: true };
+ }
+ else {
+ i--;
+ return { value: array[i], done: false };
+ }
+ }
+ };
+ }
+ ts.arrayReverseIterator = arrayReverseIterator;
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
@@ -1181,9 +1263,11 @@
}
for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
var arg = args_1[_a];
+ if (arg === undefined)
+ continue;
for (var p in arg) {
if (hasProperty(arg, p)) {
- t[p] = arg[p]; // TODO: GH#23368
+ t[p] = arg[p];
}
}
}
@@ -1359,6 +1443,9 @@
/** Do nothing and return true */
function returnTrue() { return true; }
ts.returnTrue = returnTrue;
+ /** Do nothing and return undefined */
+ function returnUndefined() { return undefined; }
+ ts.returnUndefined = returnUndefined;
/** Returns its argument. */
function identity(x) { return x; }
ts.identity = identity;
@@ -1505,7 +1592,7 @@
Debug.assertEachDefined = assertEachDefined;
function assertNever(member, message, stackCrawlMark) {
if (message === void 0) { message = "Illegal value:"; }
- var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
+ var detail = typeof member === "object" && "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
return fail(message + " " + detail, stackCrawlMark || assertNever);
}
Debug.assertNever = assertNever;
@@ -2808,47 +2895,53 @@
SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment";
// Enum
SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember";
+ // Unparsed
+ SyntaxKind[SyntaxKind["UnparsedPrologue"] = 279] = "UnparsedPrologue";
+ SyntaxKind[SyntaxKind["UnparsedPrepend"] = 280] = "UnparsedPrepend";
+ SyntaxKind[SyntaxKind["UnparsedText"] = 281] = "UnparsedText";
+ SyntaxKind[SyntaxKind["UnparsedInternalText"] = 282] = "UnparsedInternalText";
+ SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 283] = "UnparsedSyntheticReference";
// Top-level nodes
- SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle";
- SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource";
- SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles";
+ SyntaxKind[SyntaxKind["SourceFile"] = 284] = "SourceFile";
+ SyntaxKind[SyntaxKind["Bundle"] = 285] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 286] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 287] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 288] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 289] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature";
- SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag";
- SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 290] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 291] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 292] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 293] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 294] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 295] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 296] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 297] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 298] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 299] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 300] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 301] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 302] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocEnumTag"] = 303] = "JSDocEnumTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 304] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 305] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocThisTag"] = 306] = "JSDocThisTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 307] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 308] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 309] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 310] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 311] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 312] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 313] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 314] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 315] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 316] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 312] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 317] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment";
@@ -2875,10 +2968,10 @@
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 288] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 310] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 299] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 310] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -2985,21 +3078,27 @@
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
})(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
- /* @internal */
var TokenFlags;
(function (TokenFlags) {
TokenFlags[TokenFlags["None"] = 0] = "None";
+ /* @internal */
TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
+ /* @internal */
TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
+ /* @internal */
TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
+ /* @internal */
TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
+ /* @internal */
TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
+ /* @internal */
TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
+ /* @internal */
TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
})(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
var FlowFlags;
@@ -3359,12 +3458,6 @@
TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
/* @internal */
- TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType";
- /* @internal */
- TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral";
- /* @internal */
- TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType";
- /* @internal */
TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
/* @internal */
TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
@@ -3396,28 +3489,29 @@
TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
+ /* @internal */
+ TypeFlags[TypeFlags["ObjectFlagsType"] = 3768320] = "ObjectFlagsType";
// 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never
TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
/* @internal */
TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
+ // The following flags are aggregated during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening";
- /* @internal */
- TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags";
+ TypeFlags[TypeFlags["IncludesMask"] = 1835007] = "IncludesMask";
// The following flags are used for different purposes during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType";
+ TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
/* @internal */
- TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard";
+ TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType";
/* @internal */
- TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject";
+ TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard";
/* @internal */
- TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags";
+ TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject";
// The following flag is used for different purposes by maybeTypeOfKind
/* @internal */
- TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType";
+ TypeFlags[TypeFlags["GenericMappedType"] = 131072] = "GenericMappedType";
})(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
var ObjectFlags;
(function (ObjectFlags) {
@@ -3437,7 +3531,19 @@
ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
+ /* @internal */
+ ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion";
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType";
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsObjectLiteral"] = 262144] = "ContainsObjectLiteral";
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsAnyFunctionType"] = 524288] = "ContainsAnyFunctionType";
ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
+ /* @internal */
+ ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening";
+ /* @internal */
+ ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags";
})(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
/* @internal */
var Variance;
@@ -3482,6 +3588,7 @@
InferenceFlags[InferenceFlags["None"] = 0] = "None";
InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
+ InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
})(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
/**
* Ternary values are defined such that
@@ -3589,9 +3696,10 @@
ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
- ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext";
+ ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
+ ScriptTarget[ScriptTarget["ESNext"] = 7] = "ESNext";
ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
- ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest";
+ ScriptTarget[ScriptTarget["Latest"] = 7] = "Latest";
})(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
var LanguageVariant;
(function (LanguageVariant) {
@@ -3740,6 +3848,7 @@
Extension["Js"] = ".js";
Extension["Jsx"] = ".jsx";
Extension["Json"] = ".json";
+ Extension["TsBuildInfo"] = ".tsbuildinfo";
})(Extension = ts.Extension || (ts.Extension = {}));
/* @internal */
var TransformFlags;
@@ -3747,71 +3856,69 @@
TransformFlags[TransformFlags["None"] = 0] = "None";
// Facts
// - Flags used to indicate that a node or subtree contains syntax that requires transformation.
- TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript";
- TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript";
- TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx";
- TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext";
- TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017";
- TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016";
- TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015";
+ TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
+ TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
+ TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
+ TransformFlags[TransformFlags["ContainsES2019"] = 8] = "ContainsES2019";
+ TransformFlags[TransformFlags["ContainsES2018"] = 16] = "ContainsES2018";
+ TransformFlags[TransformFlags["ContainsES2017"] = 32] = "ContainsES2017";
+ TransformFlags[TransformFlags["ContainsES2016"] = 64] = "ContainsES2016";
TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015";
- TransformFlags[TransformFlags["Generator"] = 256] = "Generator";
- TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
- TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment";
- TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment";
+ TransformFlags[TransformFlags["ContainsGenerator"] = 256] = "ContainsGenerator";
+ TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 512] = "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["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis";
- TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName";
- TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments";
- TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread";
- TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread";
- TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName";
- TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding";
- TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern";
- TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield";
- TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion";
- TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport";
- TransformFlags[TransformFlags["Super"] = 33554432] = "Super";
- TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper";
+ TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 1024] = "ContainsTypeScriptClassSyntax";
+ TransformFlags[TransformFlags["ContainsLexicalThis"] = 2048] = "ContainsLexicalThis";
+ TransformFlags[TransformFlags["ContainsRestOrSpread"] = 4096] = "ContainsRestOrSpread";
+ TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 8192] = "ContainsObjectRestOrSpread";
+ TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 16384] = "ContainsComputedPropertyName";
+ TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 32768] = "ContainsBlockScopedBinding";
+ TransformFlags[TransformFlags["ContainsBindingPattern"] = 65536] = "ContainsBindingPattern";
+ TransformFlags[TransformFlags["ContainsYield"] = 131072] = "ContainsYield";
+ TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 262144] = "ContainsHoistedDeclarationOrCompletion";
+ TransformFlags[TransformFlags["ContainsDynamicImport"] = 524288] = "ContainsDynamicImport";
// 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";
// Assertions
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
- TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript";
- TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx";
- TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext";
- TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017";
- TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016";
- TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015";
- TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator";
- TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment";
+ TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
+ TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
+ TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
+ TransformFlags[TransformFlags["AssertES2019"] = 8] = "AssertES2019";
+ TransformFlags[TransformFlags["AssertES2018"] = 16] = "AssertES2018";
+ TransformFlags[TransformFlags["AssertES2017"] = 32] = "AssertES2017";
+ TransformFlags[TransformFlags["AssertES2016"] = 64] = "AssertES2016";
+ TransformFlags[TransformFlags["AssertES2015"] = 128] = "AssertES2015";
+ TransformFlags[TransformFlags["AssertGenerator"] = 256] = "AssertGenerator";
+ TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 512] = "AssertDestructuringAssignment";
// Scope Exclusions
// - Bitmasks that exclude flags from propagating out of a specific context
// into the subtree flags of their container.
- TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes";
- TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes";
- TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes";
- TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes";
- TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes";
- TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes";
- TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes";
- TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes";
- TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes";
- TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes";
- TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes";
- TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes";
- TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes";
- TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes";
- TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes";
- TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes";
+ TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
+ TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
+ TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
+ TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 537371648] = "ArrowFunctionExcludes";
+ TransformFlags[TransformFlags["FunctionExcludes"] = 537373696] = "FunctionExcludes";
+ TransformFlags[TransformFlags["ConstructorExcludes"] = 537372672] = "ConstructorExcludes";
+ TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 537372672] = "MethodOrAccessorExcludes";
+ TransformFlags[TransformFlags["PropertyExcludes"] = 536872960] = "PropertyExcludes";
+ TransformFlags[TransformFlags["ClassExcludes"] = 536888320] = "ClassExcludes";
+ TransformFlags[TransformFlags["ModuleExcludes"] = 537168896] = "ModuleExcludes";
+ TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
+ TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536896512] = "ObjectLiteralExcludes";
+ TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536875008] = "ArrayLiteralOrCallOrNewExcludes";
+ TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 536944640] = "VariableDeclarationListExcludes";
+ TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
+ TransformFlags[TransformFlags["CatchClauseExcludes"] = 536879104] = "CatchClauseExcludes";
+ TransformFlags[TransformFlags["BindingPatternExcludes"] = 536875008] = "BindingPatternExcludes";
+ // Propagating flags
+ // - Bitmasks for flags that should propagate from a child
+ TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 2048] = "PropertyNamePropagatingFlags";
// Masks
// - Additional bitmasks
- TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask";
})(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
var EmitFlags;
(function (EmitFlags) {
@@ -3893,6 +4000,20 @@
EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
})(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
+ /*@internal*/
+ var BundleFileSectionKind;
+ (function (BundleFileSectionKind) {
+ BundleFileSectionKind["Prologue"] = "prologue";
+ BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
+ BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
+ BundleFileSectionKind["Reference"] = "reference";
+ BundleFileSectionKind["Type"] = "type";
+ BundleFileSectionKind["Lib"] = "lib";
+ BundleFileSectionKind["Prepend"] = "prepend";
+ BundleFileSectionKind["Text"] = "text";
+ BundleFileSectionKind["Internal"] = "internal";
+ // comments?
+ })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
var ListFormat;
(function (ListFormat) {
ListFormat[ListFormat["None"] = 0] = "None";
@@ -4039,8 +4160,11 @@
*/
/* @internal */
function generateDjb2Hash(data) {
- var chars = data.split("").map(function (str) { return str.charCodeAt(0); });
- return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381);
+ var acc = 5381;
+ for (var i = 0; i < data.length; i++) {
+ acc = ((acc << 5) + acc) + data.charCodeAt(i);
+ }
+ return acc.toString();
}
ts.generateDjb2Hash = generateDjb2Hash;
/**
@@ -4300,6 +4424,8 @@
: FileWatcherEventKind.Changed;
}
ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ /*@internal*/
+ ts.ignoredPaths = ["/node_modules/.", "/.git"];
/**
* Watch the directory recursively using host provided method to watch child directories
* that means if this is recursive watcher, watch the children directories as well
@@ -4324,6 +4450,8 @@
else {
directoryWatcher = {
watcher: host.watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName))
+ return;
// Call the actual callback
callbackCache.forEach(function (callbacks, rootDirName) {
if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
@@ -4373,7 +4501,7 @@
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
- return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
+ return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
}) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
return newChildWatches || ts.emptyArray;
/**
@@ -4390,6 +4518,16 @@
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
+ function isIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ }
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (host.useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ }
}
ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
function getNodeMajorVersion() {
@@ -4458,8 +4596,18 @@
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!nodeSystem.directoryExists(directoryName)) {
+ // Wrapped in a try-catch to prevent crashing if we are in a race
+ // with another copy of ourselves to create the same directory
+ try {
_fs.mkdirSync(directoryName);
}
+ catch (e) {
+ if (e.code !== "EEXIST") {
+ // Failed for some other reason (access denied?); still throw
+ throw e;
+ }
+ }
+ }
},
getExecutingFilePath: function () {
return __filename;
@@ -4475,7 +4623,7 @@
getModifiedTime: getModifiedTime,
setModifiedTime: setModifiedTime,
deleteFile: deleteFile,
- createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
+ createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
createSHA256Hash: _crypto ? createSHA256Hash : undefined,
getMemoryUsage: function () {
if (global.gc) {
@@ -4863,7 +5011,7 @@
}
}
function readDirectory(path, extensions, excludes, includes, depth) {
- return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries);
+ return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
}
function fileSystemEntryExists(path, entryKind) {
try {
@@ -4919,11 +5067,6 @@
return;
}
}
- function createMD5HashUsingNativeCrypto(data) {
- var hash = _crypto.createHash("md5");
- hash.update(data);
- return hash.digest("hex");
- }
function createSHA256Hash(data) {
var hash = _crypto.createHash("sha256");
hash.update(data);
@@ -5184,7 +5327,6 @@
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."),
Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."),
- Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."),
Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in 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."),
@@ -5275,6 +5417,8 @@
An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."),
A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."),
A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."),
+ readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, ts.DiagnosticCategory.Error, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."),
+ A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal_1355", "A 'const' assertion can only be applied to a string, number, boolean, array, or object literal."),
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."),
@@ -5369,7 +5513,7 @@
Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."),
Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
- Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."),
+ This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, ts.DiagnosticCategory.Error, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."),
Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."),
Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."),
Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."),
@@ -5542,15 +5686,20 @@
No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."),
Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"),
Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @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_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @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_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."),
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
+ Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."),
+ Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_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_types_Slashnode_and_th_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @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_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_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @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_types_Slashjest_or_npm_i_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_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."),
The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."),
JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."),
@@ -5657,6 +5806,12 @@
This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."),
This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."),
_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."),
+ Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided: diag(2748, ts.DiagnosticCategory.Error, "Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided_2748", "Cannot access ambient const enums when the '--isolatedModules' flag is provided."),
+ _0_refers_to_a_value_but_is_being_used_as_a_type_here: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_2749", "'{0}' refers to a value, but is being used as a type here."),
+ The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
+ Circularity_originates_in_type_at_this_location: diag(2751, ts.DiagnosticCategory.Error, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."),
+ The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
+ Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
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}'."),
@@ -5740,6 +5895,7 @@
Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
@@ -5788,7 +5944,7 @@
Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."),
Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
- Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."),
+ Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'."),
Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."),
Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
@@ -6007,6 +6163,16 @@
Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."),
Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."),
Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
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."),
@@ -6043,7 +6209,7 @@
Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."),
Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."),
If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"),
- The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."),
+ The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."),
Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."),
Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
@@ -6223,6 +6389,7 @@
Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
};
})(ts || (ts = {}));
var ts;
@@ -6710,16 +6877,20 @@
return pos;
}
var shebangTriviaRegex = /^#!.*/;
+ /*@internal*/
function isShebangTrivia(text, pos) {
// Shebangs check must only be done at the start of the file
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
+ ts.isShebangTrivia = isShebangTrivia;
+ /*@internal*/
function scanShebangTrivia(text, pos) {
var shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
+ ts.scanShebangTrivia = scanShebangTrivia;
/**
* Invokes a callback for each comment range following the provided position.
*
@@ -6746,8 +6917,15 @@
var pendingKind;
var pendingHasTrailingNewLine;
var hasPendingCommentRange = false;
- var collecting = trailing || pos === 0;
+ var collecting = trailing;
var accumulator = initial;
+ if (pos === 0) {
+ collecting = true;
+ var shebang = getShebang(text);
+ if (shebang) {
+ pos = shebang.length;
+ }
+ }
scan: while (pos >= 0 && pos < text.length) {
var ch = text.charCodeAt(pos);
switch (ch) {
@@ -7982,6 +8160,7 @@
}
pos++;
}
+ tokenValue = text.substring(startPos, pos);
return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
}
// Scans a JSX identifier; these differ from normal identifiers in that
@@ -8063,8 +8242,8 @@
pos++;
return token = 14 /* NoSubstitutionTemplateLiteral */;
}
- if (isIdentifierStart(ch, 6 /* Latest */)) {
- while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) {
+ if (isIdentifierStart(ch, 7 /* Latest */)) {
+ while (isIdentifierPart(text.charCodeAt(pos), 7 /* Latest */) && pos < end) {
pos++;
}
tokenValue = text.substring(tokenPos, pos);
@@ -8422,7 +8601,7 @@
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 279 /* SourceFile */) {
+ while (node && node.kind !== 284 /* SourceFile */) {
node = node.parent;
}
return node;
@@ -8509,10 +8688,7 @@
return !nodeIsMissing(node);
}
ts.nodeIsPresent = nodeIsPresent;
- /**
- * Prepends statements to an array while taking care of prologue directives.
- */
- function addStatementsAfterPrologue(to, from) {
+ function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
if (from === undefined || from.length === 0)
return to;
var statementIndex = 0;
@@ -8525,7 +8701,44 @@
to.splice.apply(to, [statementIndex, 0].concat(from));
return to;
}
- ts.addStatementsAfterPrologue = addStatementsAfterPrologue;
+ function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
+ if (statement === undefined)
+ return to;
+ var statementIndex = 0;
+ // skip all prologue directives to insert at the correct position
+ for (; statementIndex < to.length; ++statementIndex) {
+ if (!isPrologueDirective(to[statementIndex])) {
+ break;
+ }
+ }
+ to.splice(statementIndex, 0, statement);
+ return to;
+ }
+ function isAnyPrologueDirective(node) {
+ return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
+ }
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementsAfterStandardPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isPrologueDirective);
+ }
+ ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
+ function insertStatementsAfterCustomPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
+ }
+ ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementAfterStandardPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isPrologueDirective);
+ }
+ ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
+ function insertStatementAfterCustomPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
+ }
+ ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
/**
* Determine if the given comment is a triple-slash
*
@@ -8568,7 +8781,7 @@
// the syntax list itself considers them as normal trivia. Therefore if we simply skip
// trivia for the list, we may have skipped the JSDocComment as well. So we should process its
// first child to determine the actual position of its first token.
- if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 311 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8587,7 +8800,7 @@
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
function isJSDocTypeExpressionOrChild(node) {
- return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ return node.kind === 288 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
}
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
@@ -8714,7 +8927,7 @@
return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 279 /* SourceFile */ ||
+ return node.kind === 284 /* SourceFile */ ||
node.kind === 244 /* ModuleDeclaration */ ||
ts.isFunctionLike(node);
}
@@ -8732,7 +8945,7 @@
// - defined in the top level scope and source file is an external module
// - defined inside ambient module declaration located in the top level scope and source file not an external module
switch (node.parent.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 245 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
@@ -8750,7 +8963,7 @@
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 274 /* CatchClause */:
case 244 /* ModuleDeclaration */:
@@ -8775,9 +8988,9 @@
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
- case 293 /* JSDocSignature */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 298 /* JSDocSignature */:
return true;
default:
ts.assertType(node);
@@ -8793,12 +9006,12 @@
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
@@ -8943,7 +9156,7 @@
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
if (pos_1 === sourceFile.text.length) {
// file is empty - return span for the beginning of the file
@@ -9118,7 +9331,7 @@
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 150 /* TypeParameter */:
return node === parent.constraint;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return node === parent.constraint;
case 154 /* PropertyDeclaration */:
case 153 /* PropertySignature */:
@@ -9378,7 +9591,7 @@
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 279 /* SourceFile */);
+ ts.Debug.assert(node.kind !== 284 /* SourceFile */);
while (true) {
node = node.parent;
if (!node) {
@@ -9432,7 +9645,7 @@
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 243 /* EnumDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return node;
}
}
@@ -9515,6 +9728,11 @@
}
}
ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
+ function isSuperOrSuperProperty(node) {
+ return node.kind === 98 /* SuperKeyword */
+ || isSuperProperty(node);
+ }
+ ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
/**
* Determines whether a node is a property or element access expression for `super`.
*/
@@ -10140,7 +10358,7 @@
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 309 /* JSDocTypedefTag */ || node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -10284,7 +10502,7 @@
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 === 290 /* JSDocVariadicType */;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 295 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10522,14 +10740,15 @@
}
ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
function getEffectiveBaseTypeNode(node) {
- if (isInJSFile(node)) {
+ var baseType = getClassExtendsHeritageElement(node);
+ if (baseType && isInJSFile(node)) {
// Prefer an @augments tag because it may have type parameters.
var tag = ts.getJSDocAugmentsTag(node);
if (tag) {
return tag.class;
}
}
- return getClassExtendsHeritageElement(node);
+ return baseType;
}
ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
function getClassExtendsHeritageElement(node) {
@@ -10768,7 +10987,7 @@
|| kind === 158 /* GetAccessor */
|| kind === 159 /* SetAccessor */
|| kind === 244 /* ModuleDeclaration */
- || kind === 279 /* SourceFile */;
+ || kind === 284 /* SourceFile */;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -10845,7 +11064,7 @@
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return 0;
case 208 /* SpreadElement */:
return 1;
@@ -11163,6 +11382,9 @@
lineStart = true;
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
reset();
return {
write: write,
@@ -11191,7 +11413,8 @@
writeStringLiteral: write,
writeSymbol: function (s, _) { return write(s); },
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
};
}
ts.createTextWriter = createTextWriter;
@@ -11320,23 +11543,27 @@
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); };
+ var getResolvedProjectReferenceToRedirect = function (fileName) { return host.getResolvedProjectReferenceToRedirect(fileName); };
if (options.outFile || options.out) {
var moduleKind = ts.getEmitModuleKind(options);
var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
// Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
return ts.filter(host.getSourceFiles(), function (sourceFile) {
- return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary);
+ return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect);
});
}
else {
var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
- return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); });
+ return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
}
}
ts.getSourceFilesToEmit = getSourceFilesToEmit;
/** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
- function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) {
- return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile);
+ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect) {
+ return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
+ !sourceFile.isDeclarationFile &&
+ !isSourceFileFromExternalLibrary(sourceFile) &&
+ !(isJsonSourceFile(sourceFile) && getResolvedProjectReferenceToRedirect(sourceFile.fileName));
}
ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
function getSourceFilePathInNewDir(fileName, host, newDirPath) {
@@ -11482,7 +11709,7 @@
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
/** template tags are only available when a typedef isn't already using them */
function isNonTypeAliasTemplate(tag) {
- return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
}
/**
* Gets the effective type annotation of the value parameter of a set accessor. If the node
@@ -12387,7 +12614,7 @@
}
ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
function getObjectFlags(type) {
- return type.flags & 524288 /* Object */ ? type.objectFlags : 0;
+ return type.flags & 3768320 /* ObjectFlagsType */ ? type.objectFlags : 0;
}
ts.getObjectFlags = getObjectFlags;
function typeHasCallOrConstructSignatures(type, checker) {
@@ -12454,25 +12681,37 @@
|| kind === 96 /* NullKeyword */
|| kind === 132 /* NeverKeyword */
|| kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
+ || kind === 289 /* JSDocAllType */
+ || kind === 290 /* JSDocUnknownType */
+ || kind === 291 /* JSDocNullableType */
+ || kind === 292 /* JSDocNonNullableType */
+ || kind === 293 /* JSDocOptionalType */
+ || kind === 294 /* JSDocFunctionType */
+ || kind === 295 /* JSDocVariadicType */;
}
ts.isTypeNodeKind = isTypeNodeKind;
function isAccessExpression(node) {
return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */;
}
ts.isAccessExpression = isAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text" /* Text */:
+ case "internal" /* Internal */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
switch (options.target) {
- case 6 /* ESNext */:
+ case 7 /* ESNext */:
return "lib.esnext.full.d.ts";
+ case 6 /* ES2019 */:
+ return "lib.es2019.full.d.ts";
case 5 /* ES2018 */:
return "lib.es2018.full.d.ts";
case 4 /* ES2017 */:
@@ -12926,8 +13165,8 @@
switch (declaration.kind) {
case 72 /* Identifier */:
return declaration;
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */: {
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 148 /* QualifiedName */) {
return name.right;
@@ -12951,7 +13190,7 @@
return undefined;
}
}
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 254 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -13155,7 +13394,7 @@
return ts.emptyArray;
}
if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */);
+ ts.Debug.assert(node.parent.kind === 296 /* JSDocComment */);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
if (node.typeParameters) {
@@ -13417,12 +13656,17 @@
return node.kind === 194 /* TypeAssertionExpression */;
}
ts.isTypeAssertion = isTypeAssertion;
+ function isConstTypeReference(node) {
+ return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
+ node.typeName.escapedText === "const" && !node.typeArguments;
+ }
+ ts.isConstTypeReference = isConstTypeReference;
function isParenthesizedExpression(node) {
return node.kind === 195 /* ParenthesizedExpression */;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 308 /* PartiallyEmittedExpression */) {
+ while (node.kind === 313 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13769,108 +14013,128 @@
ts.isEnumMember = isEnumMember;
// Top-level nodes
function isSourceFile(node) {
- return node.kind === 279 /* SourceFile */;
+ return node.kind === 284 /* SourceFile */;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 280 /* Bundle */;
+ return node.kind === 285 /* Bundle */;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 281 /* UnparsedSource */;
+ return node.kind === 286 /* UnparsedSource */;
}
ts.isUnparsedSource = isUnparsedSource;
+ function isUnparsedPrepend(node) {
+ return node.kind === 280 /* UnparsedPrepend */;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 279 /* UnparsedPrologue */ ||
+ node.kind === 283 /* UnparsedSyntheticReference */;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 283 /* JSDocTypeExpression */;
+ return node.kind === 288 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 284 /* JSDocAllType */;
+ return node.kind === 289 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 285 /* JSDocUnknownType */;
+ return node.kind === 290 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 286 /* JSDocNullableType */;
+ return node.kind === 291 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 287 /* JSDocNonNullableType */;
+ return node.kind === 292 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 288 /* JSDocOptionalType */;
+ return node.kind === 293 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 289 /* JSDocFunctionType */;
+ return node.kind === 294 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 290 /* JSDocVariadicType */;
+ return node.kind === 295 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 291 /* JSDocComment */;
+ return node.kind === 296 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 295 /* JSDocAugmentsTag */;
+ return node.kind === 300 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 296 /* JSDocClassTag */;
+ return node.kind === 301 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocEnumTag(node) {
- return node.kind === 298 /* JSDocEnumTag */;
+ return node.kind === 303 /* JSDocEnumTag */;
}
ts.isJSDocEnumTag = isJSDocEnumTag;
function isJSDocThisTag(node) {
- return node.kind === 301 /* JSDocThisTag */;
+ return node.kind === 306 /* JSDocThisTag */;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 300 /* JSDocReturnTag */;
+ return node.kind === 305 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 302 /* JSDocTypeTag */;
+ return node.kind === 307 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 303 /* JSDocTemplateTag */;
+ return node.kind === 308 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 304 /* JSDocTypedefTag */;
+ return node.kind === 309 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */;
+ return node.kind === 310 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 310 /* JSDocPropertyTag */ || node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 292 /* JSDocTypeLiteral */;
+ return node.kind === 297 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 293 /* JSDocSignature */;
+ return node.kind === 298 /* JSDocSignature */;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
@@ -13881,7 +14145,7 @@
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 306 /* SyntaxList */;
+ return n.kind === 311 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -14033,11 +14297,11 @@
switch (kind) {
case 155 /* MethodSignature */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 166 /* ConstructorType */:
return true;
default:
@@ -14328,8 +14592,8 @@
case 208 /* SpreadElement */:
case 212 /* AsExpression */:
case 210 /* OmittedExpression */:
- case 309 /* CommaListExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 314 /* CommaListExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -14343,12 +14607,12 @@
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 308 /* PartiallyEmittedExpression */;
+ return node.kind === 313 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 307 /* NotEmittedStatement */;
+ return node.kind === 312 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14459,9 +14723,9 @@
|| kind === 242 /* TypeAliasDeclaration */
|| kind === 150 /* TypeParameter */
|| kind === 237 /* VariableDeclaration */
- || kind === 304 /* JSDocTypedefTag */
- || kind === 297 /* JSDocCallbackTag */
- || kind === 305 /* JSDocPropertyTag */;
+ || kind === 309 /* JSDocTypedefTag */
+ || kind === 302 /* JSDocCallbackTag */
+ || kind === 310 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 239 /* FunctionDeclaration */
@@ -14496,14 +14760,14 @@
|| kind === 219 /* VariableStatement */
|| kind === 224 /* WhileStatement */
|| kind === 231 /* WithStatement */
- || kind === 307 /* NotEmittedStatement */
- || kind === 311 /* EndOfDeclarationMarker */
- || kind === 310 /* MergeDeclarationMarker */;
+ || kind === 312 /* NotEmittedStatement */
+ || kind === 316 /* EndOfDeclarationMarker */
+ || kind === 315 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 150 /* TypeParameter */) {
- return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node);
+ return (node.parent && node.parent.kind !== 308 /* JSDocTemplateTag */) || ts.isInJSFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14598,18 +14862,18 @@
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */;
+ return node.kind >= 288 /* FirstJSDocNode */ && node.kind <= 310 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 296 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
// TODO: determine what this does before making it public.
/* @internal */
function isJSDocTag(node) {
- return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */;
+ return node.kind >= 299 /* FirstJSDocTagNode */ && node.kind <= 310 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -14926,6 +15190,10 @@
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
@@ -15613,7 +15881,7 @@
}
ts.getRegexFromPattern = getRegexFromPattern;
/** @param path directory of the tsconfig.json */
- function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) {
+ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
path = ts.normalizePath(path);
currentDirectory = ts.normalizePath(currentDirectory);
var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
@@ -15623,12 +15891,18 @@
// Associate an array of results with each include regex. This keeps results in order of the "include" order.
// If there are no "includes", then just put everything in results[0].
var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
+ var visited = ts.createMap();
+ var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
var basePath = _a[_i];
visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
}
return ts.flatten(results);
function visitDirectory(path, absolutePath, depth) {
+ var canonicalPath = toCanonical(realpath(absolutePath));
+ if (visited.has(canonicalPath))
+ return;
+ visited.set(canonicalPath, true);
var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
var _loop_1 = function (current) {
var name = combinePaths(path, current);
@@ -16011,6 +16285,19 @@
return arr.slice(index);
}
ts.sliceAfter = sliceAfter;
+ function addRelatedInfo(diagnostic) {
+ var _a;
+ var relatedInformation = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ relatedInformation[_i - 1] = arguments[_i];
+ }
+ if (!diagnostic.relatedInformation) {
+ diagnostic.relatedInformation = [];
+ }
+ (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
+ return diagnostic;
+ }
+ ts.addRelatedInfo = addRelatedInfo;
function minAndMax(arr, getValue) {
Debug.assert(arr.length !== 0);
var min = getValue(arr[0]);
@@ -16210,7 +16497,7 @@
var SourceFileConstructor;
// tslint:enable variable-name
function createNode(kind, pos, end) {
- if (kind === 279 /* SourceFile */) {
+ if (kind === 284 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 72 /* Identifier */) {
@@ -16461,7 +16748,7 @@
case 218 /* Block */:
case 245 /* ModuleBlock */:
return visitNodes(cbNode, cbNodes, node.statements);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
case 219 /* VariableStatement */:
@@ -16610,7 +16897,7 @@
return visitNode(cbNode, node.expression);
case 258 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 260 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -16639,60 +16926,60 @@
return visitNode(cbNode, node.tagName);
case 171 /* OptionalType */:
case 172 /* RestType */:
- case 283 /* JSDocTypeExpression */:
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 288 /* JSDocOptionalType */:
- case 290 /* JSDocVariadicType */:
+ case 288 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 293 /* JSDocOptionalType */:
+ case 295 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return visitNode(cbNode, node.tagName) ||
(node.isNameFirst
? visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression)
: visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name));
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.constraint) ||
visitNodes(cbNode, cbNodes, node.typeParameters);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return visitNode(cbNode, node.tagName) ||
(node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ node.typeExpression.kind === 288 /* JSDocTypeExpression */
? visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName)
: visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression));
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.typeExpression);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 294 /* JSDocTag */:
- case 296 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
return visitNode(cbNode, node.tagName);
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -16772,7 +17059,7 @@
(function (Parser) {
// Share a single scanner across all calls to parse a source file. This helps speed things
// up by avoiding the cost of creating/compiling scanners over and over again.
- var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
+ var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true);
var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */;
// capture constructors in 'initializeState' to avoid null checks
// tslint:disable variable-name
@@ -17066,7 +17353,7 @@
function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
// code from createNode is inlined here so createNode won't have to deal with special case of creating source files
// this is quite rare comparing to other nodes and createNode should be as fast as possible
- var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ var sourceFile = new SourceFileConstructor(284 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -18266,9 +18553,9 @@
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(284 /* JSDocAllType */);
+ var result = createNode(289 /* JSDocAllType */);
if (postFixEquals) {
- return createPostfixType(288 /* JSDocOptionalType */, result);
+ return createPostfixType(293 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -18276,7 +18563,7 @@
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(287 /* JSDocNonNullableType */);
+ var result = createNode(292 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -18300,18 +18587,18 @@
token() === 30 /* GreaterThanToken */ ||
token() === 59 /* EqualsToken */ ||
token() === 50 /* BarToken */) {
- var result = createNode(285 /* JSDocUnknownType */, pos);
+ var result = createNode(290 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(286 /* JSDocNullableType */, pos);
+ var result = createNode(291 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(289 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(294 /* JSDocFunctionType */);
nextToken();
fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -18335,12 +18622,12 @@
var type = parseTypeOrTypePredicate();
scanner.setInJSDocType(false);
if (dotdotdot) {
- var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(295 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 59 /* EqualsToken */) {
- return createPostfixType(288 /* JSDocOptionalType */, type);
+ return createPostfixType(293 /* JSDocOptionalType */, type);
}
return type;
}
@@ -18712,7 +18999,7 @@
return finishNode(node);
}
var type = parseType();
- if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) {
+ if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 291 /* JSDocNullableType */ && type.pos === type.type.pos) {
type.kind = 171 /* OptionalType */;
}
return type;
@@ -18850,6 +19137,7 @@
case 135 /* NumberKeyword */:
case 146 /* BigIntKeyword */:
case 123 /* BooleanKeyword */:
+ case 133 /* ReadonlyKeyword */:
case 139 /* SymbolKeyword */:
case 142 /* UniqueKeyword */:
case 106 /* VoidKeyword */:
@@ -18898,14 +19186,14 @@
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 52 /* ExclamationToken */:
- type = createPostfixType(287 /* JSDocNonNullableType */, type);
+ type = createPostfixType(292 /* JSDocNonNullableType */, type);
break;
case 56 /* QuestionToken */:
// If not in JSDoc and next token is start of a type we have a conditional type
if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
- type = createPostfixType(286 /* JSDocNullableType */, type);
+ type = createPostfixType(291 /* JSDocNullableType */, type);
break;
case 22 /* OpenBracketToken */:
parseExpected(22 /* OpenBracketToken */);
@@ -18955,6 +19243,7 @@
switch (operator) {
case 129 /* KeyOfKeyword */:
case 142 /* UniqueKeyword */:
+ case 133 /* ReadonlyKeyword */:
return parseTypeOperator(operator);
case 127 /* InferKeyword */:
return parseInferType();
@@ -20014,7 +20303,8 @@
}
function parseJsxText() {
var node = createNode(11 /* JsxText */);
- node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
+ node.text = scanner.getTokenValue();
+ node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
currentToken = scanner.scanJsxToken();
return finishNode(node);
}
@@ -21829,8 +22119,8 @@
var JSDocParser;
(function (JSDocParser) {
function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
- sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
+ initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ sourceFile = createSourceFile("file.js", 7 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
scanner.setText(content, start, length);
currentToken = scanner.scan();
var jsDocTypeExpression = parseJSDocTypeExpression();
@@ -21841,7 +22131,7 @@
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(283 /* JSDocTypeExpression */);
+ var result = createNode(288 /* JSDocTypeExpression */);
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -21852,7 +22142,7 @@
}
JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
function parseIsolatedJSDocComment(content, start, length) {
- initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion
var jsDoc = parseJSDocCommentWorker(start, length);
var diagnostics = parseDiagnostics;
@@ -22004,7 +22294,7 @@
}
}
function createJSDocComment() {
- var result = createNode(291 /* JSDocComment */, start);
+ var result = createNode(296 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -22171,7 +22461,7 @@
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(start, tagName) {
- var result = createNode(294 /* JSDocTag */, start);
+ var result = createNode(299 /* JSDocTag */, start);
result.tagName = tagName;
return finishNode(result);
}
@@ -22230,8 +22520,8 @@
typeExpression = tryParseTypeExpression();
}
var result = target === 1 /* Property */ ?
- createNode(305 /* JSDocPropertyTag */, start) :
- createNode(299 /* JSDocParameterTag */, start);
+ createNode(310 /* JSDocPropertyTag */, start) :
+ createNode(304 /* JSDocParameterTag */, start);
var comment = parseTagComments(indent + scanner.getStartPos() - start);
var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
@@ -22248,18 +22538,18 @@
}
function parseNestedTypeLiteral(typeExpression, name, target, indent) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(288 /* JSDocTypeExpression */, scanner.getTokenPos());
var child = void 0;
var jsdocTypeLiteral = void 0;
var start_2 = scanner.getStartPos();
var children = void 0;
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
- if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) {
+ if (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 169 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -22270,25 +22560,25 @@
}
}
function parseReturnTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 305 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(300 /* JSDocReturnTag */, start);
+ var result = createNode(305 /* JSDocReturnTag */, start);
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 307 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(302 /* JSDocTypeTag */, start);
+ var result = createNode(307 /* JSDocTypeTag */, start);
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(start, tagName) {
- var result = createNode(295 /* JSDocAugmentsTag */, start);
+ var result = createNode(300 /* JSDocAugmentsTag */, start);
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
@@ -22315,19 +22605,19 @@
return node;
}
function parseClassTag(start, tagName) {
- var tag = createNode(296 /* JSDocClassTag */, start);
+ var tag = createNode(301 /* JSDocClassTag */, start);
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(start, tagName) {
- var tag = createNode(301 /* JSDocThisTag */, start);
+ var tag = createNode(306 /* JSDocThisTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
return finishNode(tag);
}
function parseEnumTag(start, tagName) {
- var tag = createNode(298 /* JSDocEnumTag */, start);
+ var tag = createNode(303 /* JSDocEnumTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
@@ -22336,7 +22626,7 @@
function parseTypedefTag(start, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
- var typedefTag = createNode(304 /* JSDocTypedefTag */, start);
+ var typedefTag = createNode(309 /* JSDocTypedefTag */, start);
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
@@ -22350,9 +22640,9 @@
var childTypeTag = void 0;
while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start);
}
- if (child.kind === 302 /* JSDocTypeTag */) {
+ if (child.kind === 307 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -22398,14 +22688,14 @@
return typeNameOrNamespaceName;
}
function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(297 /* JSDocCallbackTag */, start);
+ var callbackTag = createNode(302 /* JSDocCallbackTag */, start);
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
var child;
- var jsdocSignature = createNode(293 /* JSDocSignature */, start);
+ var jsdocSignature = createNode(298 /* JSDocSignature */, start);
jsdocSignature.parameters = [];
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
@@ -22413,7 +22703,7 @@
var returnTag = tryParse(function () {
if (parseOptionalJsdoc(58 /* AtToken */)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 300 /* JSDocReturnTag */) {
+ if (tag && tag.kind === 305 /* JSDocReturnTag */) {
return tag;
}
}
@@ -22458,7 +22748,7 @@
case 58 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) &&
+ if (child && (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) &&
target !== 4 /* CallbackParameter */ &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
@@ -22528,7 +22818,7 @@
skipWhitespace();
typeParameters.push(typeParameter);
} while (parseOptionalJsdoc(27 /* CommaToken */));
- var result = createNode(303 /* JSDocTemplateTag */, start);
+ var result = createNode(308 /* JSDocTemplateTag */, start);
result.tagName = tagName;
result.constraint = constraint;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -23306,6 +23596,7 @@
["es2016", "lib.es2016.d.ts"],
["es2017", "lib.es2017.d.ts"],
["es2018", "lib.es2018.d.ts"],
+ ["es2019", "lib.es2019.d.ts"],
["esnext", "lib.esnext.d.ts"],
// Host only
["dom", "lib.dom.d.ts"],
@@ -23329,12 +23620,16 @@
["es2017.string", "lib.es2017.string.d.ts"],
["es2017.intl", "lib.es2017.intl.d.ts"],
["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
+ ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
["es2018.intl", "lib.es2018.intl.d.ts"],
["es2018.promise", "lib.es2018.promise.d.ts"],
["es2018.regexp", "lib.es2018.regexp.d.ts"],
- ["esnext.array", "lib.esnext.array.d.ts"],
- ["esnext.symbol", "lib.esnext.symbol.d.ts"],
- ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"],
+ ["es2019.array", "lib.es2019.array.d.ts"],
+ ["es2019.string", "lib.es2019.string.d.ts"],
+ ["es2019.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.array", "lib.es2019.array.d.ts"],
+ ["esnext.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
["esnext.intl", "lib.esnext.intl.d.ts"],
["esnext.bigint", "lib.esnext.bigint.d.ts"]
];
@@ -23480,14 +23775,15 @@
es2016: 3 /* ES2016 */,
es2017: 4 /* ES2017 */,
es2018: 5 /* ES2018 */,
- esnext: 6 /* ESNext */,
+ es2019: 6 /* ES2019 */,
+ esnext: 7 /* ESNext */,
}),
affectsSourceFile: true,
affectsModuleResolution: true,
paramType: ts.Diagnostics.VERSION,
showInSimplifiedHelpView: true,
category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT,
+ description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT,
},
{
name: "module",
@@ -23609,6 +23905,22 @@
description: ts.Diagnostics.Enable_project_compilation,
},
{
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
+ {
name: "removeComments",
type: "boolean",
showInSimplifiedHelpView: true,
@@ -25034,7 +25346,7 @@
}
function directoryOfCombinedPath(fileName, basePath) {
// Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
- // until consistient casing errors are reported
+ // until consistent casing errors are reported
return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
}
/**
@@ -27326,7 +27638,7 @@
return "__constructor" /* Constructor */;
case 165 /* FunctionType */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return "__call" /* Call */;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
@@ -27335,7 +27647,7 @@
return "__index" /* Index */;
case 255 /* ExportDeclaration */:
return "__export" /* ExportStar */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// json file should behave as
// module.exports = ...
return "export=" /* ExportEquals */;
@@ -27346,12 +27658,12 @@
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 151 /* 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 === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
+ ts.Debug.assert(node.parent.kind === 294 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
var functionType = node.parent;
var index = functionType.parameters.indexOf(node);
return "arg" + index;
@@ -27435,13 +27747,15 @@
message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
messageNeedsName_1 = false;
}
- if (symbol.declarations && symbol.declarations.length) {
+ var multipleDefaultExports_1 = false;
+ if (ts.length(symbol.declarations)) {
// If the current node is a default export of some sort, then check if
// there are any other default exports that we need to error on.
// We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
if (isDefaultExport) {
message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
messageNeedsName_1 = false;
+ multipleDefaultExports_1 = true;
}
else {
// This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
@@ -27452,14 +27766,22 @@
(node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) {
message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
messageNeedsName_1 = false;
+ multipleDefaultExports_1 = true;
}
}
}
- var addError = function (decl) {
- file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined));
- };
- ts.forEach(symbol.declarations, addError);
- addError(node);
+ var declarationName_1 = ts.getNameOfDeclaration(node) || node;
+ var relatedInformation_1 = [];
+ ts.forEach(symbol.declarations, function (declaration, index) {
+ var decl = ts.getNameOfDeclaration(declaration) || declaration;
+ var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo(diag, createDiagnosticForNode(declarationName_1, index === 0 ? ts.Diagnostics.Another_export_default_is_here : ts.Diagnostics.and_here)) : diag);
+ if (multipleDefaultExports_1) {
+ relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
+ }
+ });
+ var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInformation_1)) : diag);
symbol = createSymbol(0 /* None */, name);
}
}
@@ -27575,7 +27897,7 @@
}
}
// We create a return control flow graph for IIFEs and constructors. For constructors
- // we use the return control flow graph in strict property intialization checks.
+ // we use the return control flow graph in strict property initialization checks.
currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined;
currentBreakTarget = undefined;
currentContinueTarget = undefined;
@@ -27590,7 +27912,7 @@
if (hasExplicitReturn)
node.flags |= 256 /* HasExplicitReturn */;
}
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
@@ -27734,12 +28056,12 @@
case 191 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
bindJSDocTypeAlias(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
- case 279 /* SourceFile */: {
+ case 284 /* SourceFile */: {
bindEachFunctionsFirst(node.statements);
bind(node.endOfFileToken);
break;
@@ -28426,7 +28748,7 @@
case 243 /* EnumDeclaration */:
case 188 /* ObjectLiteralExpression */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 268 /* JsxAttributes */:
return 1 /* IsContainer */;
case 241 /* InterfaceDeclaration */:
@@ -28435,7 +28757,7 @@
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
return 1 /* IsContainer */ | 32 /* HasLocals */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
case 156 /* MethodDeclaration */:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -28448,8 +28770,8 @@
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
- case 289 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
case 165 /* FunctionType */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
@@ -28503,7 +28825,7 @@
// handlers to take care of declaring these child members.
case 244 /* ModuleDeclaration */:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
case 209 /* ClassExpression */:
case 240 /* ClassDeclaration */:
@@ -28511,7 +28833,7 @@
case 243 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 188 /* ObjectLiteralExpression */:
case 241 /* InterfaceDeclaration */:
case 268 /* JsxAttributes */:
@@ -28525,7 +28847,7 @@
case 166 /* ConstructorType */:
case 160 /* CallSignature */:
case 161 /* ConstructSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 162 /* IndexSignature */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
@@ -28535,9 +28857,9 @@
case 239 /* FunctionDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
- case 289 /* JSDocFunctionType */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 294 /* JSDocFunctionType */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
// All the children of these container types are never visible through another
@@ -28560,8 +28882,8 @@
: declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 279 /* SourceFile */ ? node : node.body;
- if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
+ var body = node.kind === 284 /* SourceFile */ ? node : node.body;
+ if (body && (body.kind === 284 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) {
@@ -28695,7 +29017,7 @@
case 244 /* ModuleDeclaration */:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalOrCommonJsModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
@@ -28833,7 +29155,7 @@
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2 /* ES2015 */) {
// Report error if function is not top level function declaration
- if (blockScopeContainer.kind !== 279 /* SourceFile */ &&
+ if (blockScopeContainer.kind !== 284 /* SourceFile */ &&
blockScopeContainer.kind !== 244 /* ModuleDeclaration */ &&
!ts.isFunctionLike(blockScopeContainer)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
@@ -29108,12 +29430,12 @@
case 159 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
case 166 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 181 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 188 /* ObjectLiteralExpression */:
@@ -29172,7 +29494,7 @@
return bindExportDeclaration(node);
case 254 /* ExportAssignment */:
return bindExportAssignment(node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
case 218 /* Block */:
@@ -29182,22 +29504,22 @@
// falls through
case 245 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 299 /* JSDocParameterTag */:
- if (node.parent.kind === 293 /* JSDocSignature */) {
+ case 304 /* JSDocParameterTag */:
+ if (node.parent.kind === 298 /* JSDocSignature */) {
return bindParameter(node);
}
- if (node.parent.kind !== 292 /* JSDocTypeLiteral */) {
+ if (node.parent.kind !== 297 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 305 /* JSDocPropertyTag */:
+ case 310 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
@@ -29369,9 +29691,14 @@
var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true);
break;
- case 279 /* SourceFile */:
- // this.foo assignment in a source file
- // Do not bind. It would be nice to support this someday though.
+ case 284 /* SourceFile */:
+ // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
+ if (thisContainer.commonJsModuleIndicator) {
+ declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220414 /* FunctionScopedVariableExcludes */);
+ }
break;
default:
ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer));
@@ -29381,7 +29708,7 @@
if (node.expression.kind === 100 /* ThisKeyword */) {
bindThisPropertyAssignment(node);
}
- else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) {
+ else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284 /* SourceFile */) {
if (ts.isPrototypeAccess(node.expression)) {
bindPrototypePropertyAssignment(node, node.parent);
}
@@ -29418,7 +29745,7 @@
}
function bindObjectDefinePropertyAssignment(node) {
var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 279 /* SourceFile */;
+ var isToplevel = node.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false);
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
}
@@ -29485,8 +29812,8 @@
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */
- : propertyAccess.parent.parent.kind === 279 /* SourceFile */;
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284 /* SourceFile */
+ : propertyAccess.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
@@ -29624,7 +29951,7 @@
}
}
function bindParameter(node) {
- if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) {
+ if (node.kind === 304 /* JSDocParameterTag */ && container.kind !== 298 /* JSDocSignature */) {
return;
}
if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
@@ -29882,44 +30209,37 @@
ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
function computeCallExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
+ var callee = ts.skipOuterExpressions(node.expression);
var expression = node.expression;
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */
- || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) {
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
// If the this node contains a SpreadExpression, or is a super call, then it is an ES6
// node.
- transformFlags |= 192 /* AssertES2015 */;
- // super property or element accesses could be inside lambdas, etc, and need a captured `this`,
- // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor)
- if (expression.transformFlags & 67108864 /* ContainsSuper */) {
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 128 /* AssertES2015 */;
+ if (ts.isSuperProperty(callee)) {
+ transformFlags |= 2048 /* ContainsLexicalThis */;
}
}
if (expression.kind === 92 /* ImportKeyword */) {
- transformFlags |= 16777216 /* ContainsDynamicImport */;
- // A dynamic 'import()' call that contains a lexical 'this' will
- // require a captured 'this' when emitting down-level.
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- transformFlags |= 16384 /* ContainsCapturedLexicalThis */;
- }
+ transformFlags |= 524288 /* ContainsDynamicImport */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
}
function computeNewExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
// If the this node contains a SpreadElementExpression then it is an ES6
// node.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
}
function computeBinaryExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -29927,20 +30247,20 @@
var leftKind = node.left.kind;
if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) {
// Destructuring object assignments with are ES2015 syntax
- // and possibly ESNext if they contain rest
- transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
+ // and possibly ES2018 if they contain rest
+ transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
}
else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) {
// Destructuring assignments are ES2015 syntax.
- transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
+ transformFlags |= 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
}
else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */
|| operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) {
// Exponentiation is ES2016 syntax.
- transformFlags |= 32 /* AssertES2016 */;
+ transformFlags |= 64 /* AssertES2016 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeParameter(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -29951,147 +30271,131 @@
// syntax.
if (node.questionToken
|| node.type
- || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
+ || (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
|| ts.isThisIdentifier(name)) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// If a parameter has an accessibility modifier, then it is TypeScript syntax.
if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
- transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
}
- // parameters with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // parameters with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a parameter has an initializer, a binding pattern or a dotDotDot token, then
// it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
- if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
- transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */;
+ if (subtreeFlags & 65536 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* ParameterExcludes */;
+ return transformFlags & ~536870912 /* ParameterExcludes */;
}
function computeParenthesizedExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
var expression = node.expression;
var expressionKind = expression.kind;
- var expressionTransformFlags = expression.transformFlags;
// If the node is synthesized, it means the emitter put the parentheses there,
// not the user. If we didn't want them, the emitter would not have put them
// there.
if (expressionKind === 212 /* AsExpression */
|| expressionKind === 194 /* TypeAssertionExpression */) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- // If the expression of a ParenthesizedExpression is a destructuring assignment,
- // then the ParenthesizedExpression is a destructuring assignment.
- if (expressionTransformFlags & 1024 /* DestructuringAssignment */) {
- transformFlags |= 1024 /* DestructuringAssignment */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536872257 /* OuterExpressionExcludes */;
+ return transformFlags & ~536870912 /* OuterExpressionExcludes */;
}
function computeClassDeclaration(node, subtreeFlags) {
var transformFlags;
if (ts.hasModifier(node, 2 /* Ambient */)) {
// An ambient declaration is TypeScript syntax.
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
// A ClassDeclaration is ES6 syntax.
- transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// A class with a parameter property assignment, property initializer, computed property name, or decorator is
// TypeScript syntax.
// An exported declaration may be TypeScript syntax, but is handled by the visitor
// for a namespace declaration.
- if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */)
+ if ((subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */)
|| node.typeParameters) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~638121281 /* ClassExcludes */;
+ return transformFlags & ~536888320 /* ClassExcludes */;
}
function computeClassExpression(node, subtreeFlags) {
// A ClassExpression is ES6 syntax.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// A class with a parameter property assignment, property initializer, or decorator is
// TypeScript syntax.
- if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */
+ if (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */
|| node.typeParameters) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~638121281 /* ClassExcludes */;
+ return transformFlags & ~536888320 /* ClassExcludes */;
}
function computeHeritageClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
switch (node.token) {
case 86 /* ExtendsKeyword */:
// An `extends` HeritageClause is ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 109 /* ImplementsKeyword */:
// An `implements` HeritageClause is TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
break;
default:
ts.Debug.fail("Unexpected token for heritage clause");
break;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeCatchClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (!node.variableDeclaration) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 8 /* AssertES2019 */;
}
else if (ts.isBindingPattern(node.variableDeclaration.name)) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637797697 /* CatchClauseExcludes */;
+ return transformFlags & ~536879104 /* CatchClauseExcludes */;
}
function computeExpressionWithTypeArguments(node, subtreeFlags) {
// An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
// extends clause of a class.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// If an ExpressionWithTypeArguments contains type arguments, then it
// is TypeScript syntax.
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeConstructor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// TypeScript-specific modifiers and overloads are TypeScript syntax
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* ConstructorExcludes */;
+ return transformFlags & ~537372672 /* ConstructorExcludes */;
}
function computeMethod(node, subtreeFlags) {
// A MethodDeclaration is ES6 syntax.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
// overloads are TypeScript syntax.
if (node.decorators
@@ -30100,21 +30404,21 @@
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// An async method declaration is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* MethodOrAccessorExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
}
function computeAccessor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -30125,25 +30429,25 @@
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* MethodOrAccessorExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
}
function computePropertyDeclaration(node, subtreeFlags) {
// A PropertyDeclaration is TypeScript syntax.
- var transformFlags = subtreeFlags | 3 /* AssertTypeScript */;
+ var transformFlags = subtreeFlags | 1 /* AssertTypeScript */;
// If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor
// so that it handle the transformation.
if (node.initializer || ts.isComputedPropertyName(node.name)) {
- transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1024 /* ContainsTypeScriptClassSyntax */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~536872960 /* PropertyExcludes */);
}
function computeFunctionDeclaration(node, subtreeFlags) {
var transformFlags;
@@ -30152,42 +30456,36 @@
if (!body || (modifierFlags & 2 /* Ambient */)) {
// An ambient declaration is TypeScript syntax.
// A FunctionDeclaration without a body is an overload and is TypeScript syntax.
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
- transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */;
+ transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (modifierFlags & 2270 /* TypeScriptModifier */
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async function declaration is ES2017 syntax.
if (modifierFlags & 256 /* Async */) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If a FunctionDeclaration's subtree has marked the container as needing to capture the
- // lexical this, or the function contains parameters with initializers, then this node is
- // ES6 syntax.
- if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) {
- transformFlags |= 192 /* AssertES2015 */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a FunctionDeclaration is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
- // Currently we do not support transforming any other generator fucntions
+ // Currently we do not support transforming any other generator functions
// down level.
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653620545 /* FunctionExcludes */;
+ return transformFlags & ~537373696 /* FunctionExcludes */;
}
function computeFunctionExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -30196,181 +30494,161 @@
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async function expression is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
- // function expressions with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If a FunctionExpression's subtree has marked the container as needing to capture the
- // lexical this, or the function contains parameters with initializers, then this node is
- // ES6 syntax.
- if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) {
- transformFlags |= 192 /* AssertES2015 */;
+ // function expressions with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a FunctionExpression is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653620545 /* FunctionExcludes */;
+ return transformFlags & ~537373696 /* FunctionExcludes */;
}
function computeArrowFunction(node, subtreeFlags) {
// An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async arrow function is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= 16 /* AssertES2017 */;
+ transformFlags |= 32 /* AssertES2017 */;
}
- // arrow functions with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If an ArrowFunction contains a lexical this, its container must capture the lexical this.
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- transformFlags |= 16384 /* ContainsCapturedLexicalThis */;
+ // arrow functions with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653604161 /* ArrowFunctionExcludes */;
+ return transformFlags & ~537371648 /* ArrowFunctionExcludes */;
}
function computePropertyAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// If a PropertyAccessExpression starts with a super keyword, then it is
// ES6 syntax, and requires a lexical `this` binding.
- if (transformFlags & 33554432 /* Super */) {
- transformFlags ^= 33554432 /* Super */;
+ if (node.expression.kind === 98 /* SuperKeyword */) {
// super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ESNext.
- transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */;
+ // same for super inside of an async generator, which is ES2018.
+ transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~570426689 /* PropertyAccessExcludes */;
+ return transformFlags & ~536870912 /* PropertyAccessExcludes */;
}
function computeElementAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- var expression = node.expression;
- var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing
// If an ElementAccessExpression starts with a super keyword, then it is
// ES6 syntax, and requires a lexical `this` binding.
- if (expressionFlags & 33554432 /* Super */) {
- transformFlags &= ~33554432 /* Super */;
+ if (node.expression.kind === 98 /* SuperKeyword */) {
// super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ESNext.
- transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */;
+ // same for super inside of an async generator, which is ES2018.
+ transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~570426689 /* PropertyAccessExcludes */;
+ return transformFlags & ~536870912 /* PropertyAccessExcludes */;
}
function computeVariableDeclaration(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- // A VariableDeclaration containing ObjectRest is ESNext syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
+ // A VariableDeclaration containing ObjectRest is ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// Type annotations are TypeScript syntax.
if (node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeVariableStatement(node, subtreeFlags) {
var transformFlags;
var declarationListTransformFlags = node.declarationList.transformFlags;
// An ambient declaration is TypeScript syntax.
if (ts.hasModifier(node, 2 /* Ambient */)) {
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
transformFlags = subtreeFlags;
- if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) {
- transformFlags |= 192 /* AssertES2015 */;
+ if (declarationListTransformFlags & 65536 /* ContainsBindingPattern */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeLabeledStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */
+ if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */
&& ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeImportEquals(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// An ImportEqualsDeclaration with a namespace reference is TypeScript.
if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeExpressionStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- // If the expression of an expression statement is a destructuring assignment,
- // then we treat the statement as ES6 so that we can indicate that we do not
- // need to hold on to the right-hand side.
- if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) {
- transformFlags |= 192 /* AssertES2015 */;
- }
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeModuleDeclaration(node, subtreeFlags) {
- var transformFlags = 3 /* AssertTypeScript */;
+ var transformFlags = 1 /* AssertTypeScript */;
var modifierFlags = ts.getModifierFlags(node);
if ((modifierFlags & 2 /* Ambient */) === 0) {
transformFlags |= subtreeFlags;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~647001409 /* ModuleExcludes */;
+ return transformFlags & ~537168896 /* ModuleExcludes */;
}
function computeVariableDeclarationList(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */;
- if (subtreeFlags & 2097152 /* ContainsBindingPattern */) {
- transformFlags |= 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
+ if (subtreeFlags & 65536 /* ContainsBindingPattern */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
// If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
if (node.flags & 3 /* BlockScoped */) {
- transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */;
+ transformFlags |= 128 /* AssertES2015 */ | 32768 /* ContainsBlockScopedBinding */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~639894849 /* VariableDeclarationListExcludes */;
+ return transformFlags & ~536944640 /* VariableDeclarationListExcludes */;
}
function computeOther(node, kind, subtreeFlags) {
// Mark transformations needed for each node
var transformFlags = subtreeFlags;
- var excludeFlags = 637535553 /* NodeExcludes */;
+ var excludeFlags = 536870912 /* NodeExcludes */;
switch (kind) {
case 121 /* AsyncKeyword */:
case 201 /* AwaitExpression */:
- // async/await is ES2017 syntax, but may be ESNext syntax (for async generators)
- transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */;
+ // async/await is ES2017 syntax, but may be ES2018 syntax (for async generators)
+ transformFlags |= 16 /* AssertES2018 */ | 32 /* AssertES2017 */;
break;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
- excludeFlags = 536872257 /* OuterExpressionExcludes */;
+ transformFlags |= 1 /* AssertTypeScript */;
+ excludeFlags = 536870912 /* OuterExpressionExcludes */;
break;
case 115 /* PublicKeyword */:
case 113 /* PrivateKeyword */:
@@ -30383,7 +30661,7 @@
case 213 /* NonNullExpression */:
case 133 /* ReadonlyKeyword */:
// These nodes are TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
break;
case 260 /* JsxElement */:
case 261 /* JsxSelfClosingElement */:
@@ -30398,7 +30676,7 @@
case 269 /* JsxSpreadAttribute */:
case 270 /* JsxExpression */:
// These nodes are Jsx syntax.
- transformFlags |= 4 /* AssertJsx */;
+ transformFlags |= 2 /* AssertJsx */;
break;
case 14 /* NoSubstitutionTemplateLiteral */:
case 15 /* TemplateHead */:
@@ -30410,32 +30688,32 @@
case 116 /* StaticKeyword */:
case 214 /* MetaProperty */:
// These nodes are ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 10 /* StringLiteral */:
if (node.hasExtendedUnicodeEscape) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
case 8 /* NumericLiteral */:
if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
case 9 /* BigIntLiteral */:
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 4 /* AssertESNext */;
break;
case 227 /* ForOfStatement */:
// This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
if (node.awaitModifier) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 16 /* AssertES2018 */;
}
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 207 /* YieldExpression */:
// This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
// generator).
- transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */;
+ transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 131072 /* ContainsYield */;
break;
case 120 /* AnyKeyword */:
case 135 /* NumberKeyword */:
@@ -30476,115 +30754,93 @@
case 182 /* LiteralType */:
case 247 /* NamespaceExportDeclaration */:
// Types and signatures are TypeScript syntax, and exclude all other facts.
- transformFlags = 3 /* AssertTypeScript */;
- excludeFlags = -3 /* TypeExcludes */;
+ transformFlags = 1 /* AssertTypeScript */;
+ excludeFlags = -2 /* TypeExcludes */;
break;
case 149 /* ComputedPropertyName */:
// Even though computed property names are ES6, we don't treat them as such.
// This is so that they can flow through PropertyName transforms unaffected.
// Instead, we mark the container as ES6, so that it can properly handle the transform.
- transformFlags |= 524288 /* ContainsComputedPropertyName */;
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- // A computed method name like `[this.getName()](x: string) { ... }` needs to
- // distinguish itself from the normal case of a method body containing `this`:
- // `this` inside a method doesn't need to be rewritten (the method provides `this`),
- // whereas `this` inside a computed name *might* need to be rewritten if the class/object
- // is inside an arrow function:
- // `_this = this; () => class K { [_this.getName()]() { ... } }`
- // To make this distinction, use ContainsLexicalThisInComputedPropertyName
- // instead of ContainsLexicalThis for computed property names
- transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */;
- }
+ transformFlags |= 16384 /* ContainsComputedPropertyName */;
break;
case 208 /* SpreadElement */:
- transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */;
+ transformFlags |= 128 /* AssertES2015 */ | 4096 /* ContainsRestOrSpread */;
break;
case 277 /* SpreadAssignment */:
- transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */;
+ transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
break;
case 98 /* SuperKeyword */:
// This node is ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */;
- excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super`
+ transformFlags |= 128 /* AssertES2015 */;
+ excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
break;
case 100 /* ThisKeyword */:
// Mark this node and its ancestors as containing a lexical `this` keyword.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 2048 /* ContainsLexicalThis */;
break;
case 184 /* ObjectBindingPattern */:
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
}
- excludeFlags = 637666625 /* BindingPatternExcludes */;
+ excludeFlags = 536875008 /* BindingPatternExcludes */;
break;
case 185 /* ArrayBindingPattern */:
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- excludeFlags = 637666625 /* BindingPatternExcludes */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
+ excludeFlags = 536875008 /* BindingPatternExcludes */;
break;
case 186 /* BindingElement */:
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
if (node.dotDotDotToken) {
- transformFlags |= 131072 /* ContainsRestOrSpread */;
+ transformFlags |= 4096 /* ContainsRestOrSpread */;
}
break;
case 152 /* Decorator */:
// This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
break;
case 188 /* ObjectLiteralExpression */:
- excludeFlags = 638358849 /* ObjectLiteralExcludes */;
- if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) {
+ excludeFlags = 536896512 /* ObjectLiteralExcludes */;
+ if (subtreeFlags & 16384 /* ContainsComputedPropertyName */) {
// If an ObjectLiteralExpression contains a ComputedPropertyName, then it
// is an ES6 node.
- transformFlags |= 192 /* AssertES2015 */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 128 /* AssertES2015 */;
}
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
// If an ObjectLiteralExpression contains a spread element, then it
- // is an ES next node.
- transformFlags |= 8 /* AssertESNext */;
+ // is an ES2018 node.
+ transformFlags |= 16 /* AssertES2018 */;
}
break;
case 187 /* ArrayLiteralExpression */:
- case 192 /* NewExpression */:
- excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */;
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
- // If the this node contains a SpreadExpression, then it is an ES6
- // node.
- transformFlags |= 192 /* AssertES2015 */;
- }
+ excludeFlags = 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
break;
case 223 /* DoStatement */:
case 224 /* WhileStatement */:
case 225 /* ForStatement */:
case 226 /* ForInStatement */:
// A loop containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) {
- transformFlags |= 192 /* AssertES2015 */;
+ if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
- case 279 /* SourceFile */:
- if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) {
- transformFlags |= 192 /* AssertES2015 */;
- }
+ case 284 /* SourceFile */:
break;
case 230 /* ReturnStatement */:
- // Return statements may require an `await` in ESNext.
- transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */;
+ // Return statements may require an `await` in ES2018.
+ transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */ | 16 /* AssertES2018 */;
break;
case 228 /* ContinueStatement */:
case 229 /* BreakStatement */:
- transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */;
+ transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */;
break;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
return transformFlags & ~excludeFlags;
}
+ function propagatePropertyNameFlags(node, transformFlags) {
+ return transformFlags | (node.transformFlags & 2048 /* PropertyNamePropagatingFlags */);
+ }
/**
* Gets the transform flags to exclude when unioning the transform flags of a subtree.
*
@@ -30594,33 +30850,33 @@
*/
function getTransformFlagsSubtreeExclusions(kind) {
if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) {
- return -3 /* TypeExcludes */;
+ return -2 /* TypeExcludes */;
}
switch (kind) {
case 191 /* CallExpression */:
case 192 /* NewExpression */:
case 187 /* ArrayLiteralExpression */:
- return 637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
case 244 /* ModuleDeclaration */:
- return 647001409 /* ModuleExcludes */;
+ return 537168896 /* ModuleExcludes */;
case 151 /* Parameter */:
- return 637535553 /* ParameterExcludes */;
+ return 536870912 /* ParameterExcludes */;
case 197 /* ArrowFunction */:
- return 653604161 /* ArrowFunctionExcludes */;
+ return 537371648 /* ArrowFunctionExcludes */;
case 196 /* FunctionExpression */:
case 239 /* FunctionDeclaration */:
- return 653620545 /* FunctionExcludes */;
+ return 537373696 /* FunctionExcludes */;
case 238 /* VariableDeclarationList */:
- return 639894849 /* VariableDeclarationListExcludes */;
+ return 536944640 /* VariableDeclarationListExcludes */;
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
- return 638121281 /* ClassExcludes */;
+ return 536888320 /* ClassExcludes */;
case 157 /* Constructor */:
- return 653616449 /* ConstructorExcludes */;
+ return 537372672 /* ConstructorExcludes */;
case 156 /* MethodDeclaration */:
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
- return 653616449 /* MethodOrAccessorExcludes */;
+ return 537372672 /* MethodOrAccessorExcludes */;
case 120 /* AnyKeyword */:
case 135 /* NumberKeyword */:
case 146 /* BigIntKeyword */:
@@ -30638,25 +30894,25 @@
case 162 /* IndexSignature */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- return -3 /* TypeExcludes */;
+ return -2 /* TypeExcludes */;
case 188 /* ObjectLiteralExpression */:
- return 638358849 /* ObjectLiteralExcludes */;
+ return 536896512 /* ObjectLiteralExcludes */;
case 274 /* CatchClause */:
- return 637797697 /* CatchClauseExcludes */;
+ return 536879104 /* CatchClauseExcludes */;
case 184 /* ObjectBindingPattern */:
case 185 /* ArrayBindingPattern */:
- return 637666625 /* BindingPatternExcludes */;
+ return 536875008 /* BindingPatternExcludes */;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
case 195 /* ParenthesizedExpression */:
case 98 /* SuperKeyword */:
- return 536872257 /* OuterExpressionExcludes */;
+ return 536870912 /* OuterExpressionExcludes */;
case 189 /* PropertyAccessExpression */:
case 190 /* ElementAccessExpression */:
- return 570426689 /* PropertyAccessExcludes */;
+ return 536870912 /* PropertyAccessExcludes */;
default:
- return 637535553 /* NodeExcludes */;
+ return 536870912 /* NodeExcludes */;
}
}
ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
@@ -30905,6 +31161,7 @@
var enumCount = 0;
var instantiationDepth = 0;
var constraintDepth = 0;
+ var currentNode;
var emptySymbols = ts.createSymbolTable();
var identityMapper = ts.identity;
var compilerOptions = host.getCompilerOptions();
@@ -30921,8 +31178,14 @@
var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
var emitResolver = createResolver();
var nodeBuilder = createNodeBuilder();
+ var globals = ts.createSymbolTable();
var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
undefinedSymbol.declarations = [];
+ var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
+ globalThisSymbol.exports = globals;
+ globalThisSymbol.valueDeclaration = ts.createNode(72 /* Identifier */);
+ globalThisSymbol.valueDeclaration.escapedText = "globalThis";
+ globals.set(globalThisSymbol.escapedName, globalThisSymbol);
var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
var requireSymbol = createSymbol(4 /* Property */, "require");
/** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
@@ -31052,11 +31315,13 @@
isContextSensitive: isContextSensitive,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0 /* Normal */);
},
getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */);
},
+ getExpandedParameters: getExpandedParameters,
+ hasEffectiveRestParameter: hasEffectiveRestParameter,
getConstantValue: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
return node ? getConstantValue(node) : undefined;
@@ -31118,6 +31383,8 @@
getNeverType: function () { return neverType; },
isSymbolAccessible: isSymbolAccessible,
getObjectFlags: ts.getObjectFlags,
+ isArrayType: isArrayType,
+ isTupleType: isTupleType,
isArrayLikeType: isArrayLikeType,
isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
@@ -31133,9 +31400,9 @@
getAccessibleSymbolChain: getAccessibleSymbolChain,
getTypePredicateOfSignature: getTypePredicateOfSignature,
resolveExternalModuleSymbol: resolveExternalModuleSymbol,
- tryGetThisTypeAt: function (node) {
+ tryGetThisTypeAt: function (node, includeGlobalThis) {
node = ts.getParseTreeNode(node);
- return node && tryGetThisTypeAt(node);
+ return node && tryGetThisTypeAt(node, includeGlobalThis);
},
getTypeArgumentConstraint: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
@@ -31182,10 +31449,10 @@
},
getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
apparentArgumentCount = undefined;
return res;
}
@@ -31194,6 +31461,7 @@
var intersectionTypes = ts.createMap();
var literalTypes = ts.createMap();
var indexedAccessTypes = ts.createMap();
+ var conditionalTypes = ts.createMap();
var evolvingArrayTypes = [];
var undefinedProperties = ts.createMap();
var unknownSymbol = createSymbol(4 /* Property */, "unknown");
@@ -31203,10 +31471,10 @@
var wildcardType = createIntrinsicType(1 /* Any */, "any");
var errorType = createIntrinsicType(1 /* Any */, "error");
var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
- var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
- var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined");
- var nullType = createIntrinsicType(65536 /* Null */, "null");
- var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null");
+ var undefinedType = createNullableType(32768 /* Undefined */, "undefined", 0);
+ var undefinedWideningType = strictNullChecks ? undefinedType : createNullableType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */);
+ var nullType = createNullableType(65536 /* Null */, "null", 0);
+ var nullWideningType = strictNullChecks ? nullType : createNullableType(65536 /* Null */, "null", 131072 /* ContainsWideningType */);
var stringType = createIntrinsicType(4 /* String */, "string");
var numberType = createIntrinsicType(8 /* Number */, "number");
var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
@@ -31248,7 +31516,7 @@
var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
// The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
// in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
- anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */;
+ anyFunctionType.objectFlags |= 524288 /* ContainsAnyFunctionType */;
var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
@@ -31262,7 +31530,6 @@
var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
- var globals = ts.createSymbolTable();
/** Key is "/path/to/a.ts|/path/to/b.ts". */
var amalgamatedDuplicates;
var reverseMappedCache = ts.createMap();
@@ -31461,9 +31728,11 @@
var CheckMode;
(function (CheckMode) {
CheckMode[CheckMode["Normal"] = 0] = "Normal";
- CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive";
+ CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
- CheckMode[CheckMode["Contextual"] = 3] = "Contextual";
+ CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
+ CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
+ CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
})(CheckMode || (CheckMode = {}));
var CallbackCheck;
(function (CallbackCheck) {
@@ -31550,18 +31819,6 @@
return diagnostic;
}
}
- function addRelatedInfo(diagnostic) {
- var relatedInformation = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- relatedInformation[_i - 1] = arguments[_i];
- }
- var _a;
- if (!diagnostic.relatedInformation) {
- diagnostic.relatedInformation = [];
- }
- (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
- return diagnostic;
- }
function error(location, message, arg0, arg1, arg2, arg3) {
var diagnostic = location
? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
@@ -31741,7 +31998,7 @@
err.relatedInformation = err.relatedInformation || [];
if (ts.length(err.relatedInformation) >= 5)
continue;
- addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here));
+ ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here));
}
}
function combineSymbolTables(first, second) {
@@ -31819,7 +32076,7 @@
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
}
function isGlobalSourceFile(node) {
- return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
@@ -31993,7 +32250,7 @@
// - parameters are only in the scope of function body
// This restriction does not apply to JSDoc comment types because they are parented
// at a higher level than type parameters would normally be
- if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) {
+ if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 296 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -32035,14 +32292,14 @@
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
// falls through
case 244 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) {
+ if (location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location)) {
// It's an external module. First see if the module has an export default and if the local
// name of that export default matches.
if (result = moduleExports.get("default" /* Default */)) {
@@ -32210,12 +32467,18 @@
// @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
// }
//
- if (location.parent && ts.isClassElement(location.parent)) {
+ // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
+ //
+ // type T = number;
+ // declare function y(x: T): any;
+ // @param(1 as T) // <-- T should resolve to the type alias outside of class C
+ // class C<T> {}
+ if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240 /* ClassDeclaration */)) {
location = location.parent;
}
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
// js type aliases do not resolve names from their host, so skip past it
location = ts.getJSDocHost(location);
break;
@@ -32234,7 +32497,7 @@
}
if (!result) {
if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */);
+ ts.Debug.assert(lastLocation.kind === 284 /* SourceFile */);
if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
return lastLocation.symbol;
}
@@ -32257,7 +32520,8 @@
!checkAndReportErrorForExtendingInterface(errorLocation) &&
!checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
!checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
- !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) {
+ !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
+ !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
var suggestion = void 0;
if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
@@ -32265,7 +32529,7 @@
var suggestionName = symbolToString(suggestion);
var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
if (suggestion.valueDeclaration) {
- addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
}
@@ -32422,6 +32686,16 @@
}
return false;
}
+ function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
+ if (meaning & (67897832 /* Type */ & ~1920 /* Namespace */)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, ~67897832 /* Type */ & 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
+ error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here, ts.unescapeLeadingUnderscores(name));
+ return true;
+ }
+ }
+ return false;
+ }
function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) {
if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") {
@@ -32430,7 +32704,7 @@
}
var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
- var message = (name === "Promise" || name === "Symbol")
+ var message = isES2015OrLaterConstructorName(name)
? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later
: ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
@@ -32439,6 +32713,18 @@
}
return false;
}
+ function isES2015OrLaterConstructorName(n) {
+ switch (n) {
+ case "Promise":
+ case "Symbol":
+ case "Map":
+ case "WeakMap":
+ case "Set":
+ case "WeakSet":
+ return true;
+ }
+ return false;
+ }
function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) {
var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
@@ -32481,7 +32767,7 @@
}
}
if (diagnosticMessage) {
- addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
}
@@ -32665,7 +32951,7 @@
var suggestionName = symbolToString(suggestion);
var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
if (suggestion.valueDeclaration) {
- addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
else {
@@ -32985,22 +33271,14 @@
return undefined;
}
if (moduleNotFoundError) {
- // For relative paths, see if this was possibly a projectReference redirect
- if (ts.pathIsRelative(moduleReference)) {
- var sourceFile_1 = ts.getSourceFileOfNode(location);
- var redirects = sourceFile_1.redirectedReferences;
- if (redirects) {
- var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName));
- for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) {
- var ext = _a[_i];
- var probePath = normalizedTargetPath + ext;
- if (redirects.indexOf(probePath) >= 0) {
- error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath);
+ // See if this was possibly a projectReference redirect
+ if (resolvedModule) {
+ var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
+ if (redirect) {
+ error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
return undefined;
}
}
- }
- }
if (resolutionDiagnostic) {
error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
}
@@ -33067,7 +33345,7 @@
function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
if (!dontResolveAlias && symbol) {
- if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) {
+ if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 284 /* SourceFile */)) {
var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
? "allowSyntheticDefaultImports"
: "esModuleInterop";
@@ -33345,6 +33623,11 @@
type.intrinsicName = intrinsicName;
return type;
}
+ function createNullableType(kind, intrinsicName, objectFlags) {
+ var type = createIntrinsicType(kind, intrinsicName);
+ type.objectFlags = objectFlags;
+ return type;
+ }
function createBooleanType(trueFalseTypes) {
var type = getUnionType(trueFalseTypes);
type.flags |= 16 /* Boolean */;
@@ -33413,7 +33696,7 @@
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
@@ -33653,10 +33936,10 @@
return node && getSymbolOfNode(node);
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
- return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -34025,8 +34308,8 @@
context.inferTypeParameters = type.root.inferTypeParameters;
var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
context.inferTypeParameters = saveInferTypeParameters;
- var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
- var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
+ var trueTypeNode = typeToTypeNodeHelper(type.trueType, context);
+ var falseTypeNode = typeToTypeNodeHelper(type.falseType, context);
context.approximateLength += 15;
return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
}
@@ -34113,7 +34396,7 @@
var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
(symbol.parent || // is exported function symbol
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
+ return declaration.parent.kind === 284 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
@@ -34153,13 +34436,14 @@
}
function typeReferenceToTypeNode(type) {
var typeArguments = type.typeArguments || ts.emptyArray;
- if (type.target === globalArrayType) {
+ if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
if (context.flags & 2 /* WriteArrayAsGenericType */) {
var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createTypeReferenceNode("Array", [typeArgumentNode]);
+ return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
}
var elementType = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createArrayTypeNode(elementType);
+ var arrayType = ts.createArrayTypeNode(elementType);
+ return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, arrayType);
}
else if (type.target.objectFlags & 8 /* Tuple */) {
if (typeArguments.length > 0) {
@@ -34172,11 +34456,13 @@
ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
ts.createOptionalTypeNode(tupleConstituentNodes[i]);
}
- return ts.createTupleTypeNode(tupleConstituentNodes);
+ var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
+ return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
}
}
if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
- return ts.createTupleTypeNode([]);
+ var tupleTypeNode = ts.createTupleTypeNode([]);
+ return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
}
context.encounteredError = true;
return undefined; // TODO: GH#18217
@@ -34340,7 +34626,7 @@
context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
context.enclosingDeclaration = saveEnclosingDeclaration;
var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined;
- if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) {
+ if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
var signatures = getSignaturesOfType(propertyType, 0 /* Call */);
for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
var signature = signatures_1[_i];
@@ -34476,7 +34762,7 @@
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
- type.symbol.declarations[0] &&
+ type.symbol.declarations && type.symbol.declarations[0] &&
ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
@@ -34495,7 +34781,7 @@
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */);
if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
- parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */);
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304 /* JSDocParameterTag */);
}
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
@@ -34653,7 +34939,7 @@
return top;
}
function getSpecifierForModuleSymbol(symbol, context) {
- var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */);
+ var file = ts.getDeclarationOfKind(symbol, 284 /* SourceFile */);
if (file && file.moduleName !== undefined) {
// Use the amd name if it is available
return file.moduleName;
@@ -34906,7 +35192,7 @@
ts.isExternalModuleAugmentation(node.parent.parent);
}
function isDefaultBindingContext(location) {
- return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location);
+ return location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location);
}
function getNameOfSymbolFromNameType(symbol, context) {
var nameType = symbol.nameType;
@@ -34983,8 +35269,8 @@
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
// Top-level jsdoc type aliases are considered exported
// First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file
return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
@@ -35011,7 +35297,7 @@
var parent = getDeclarationContainer(node);
// If the node is not exported or it is not ambient module element (except import declaration)
if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
- !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
+ !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 284 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
@@ -35053,7 +35339,7 @@
// Type parameters are always visible
case 150 /* TypeParameter */:
// Source file and namespace export are always visible
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 247 /* NamespaceExportDeclaration */:
return true;
// Export assignments do not create name bindings outside the module
@@ -35232,7 +35518,7 @@
if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
&& !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
&& isSpreadableProperty(prop)) {
- members.set(prop.escapedName, getSpreadSymbol(prop));
+ members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
}
}
var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
@@ -35301,17 +35587,8 @@
function getTypeForBindingElement(declaration) {
var pattern = declaration.parent;
var parentType = getTypeForBindingElementParent(pattern.parent);
- // If parent has the unknown (error) type, then so does this binding element
- if (parentType === errorType) {
- return errorType;
- }
- // If no type was specified or inferred for parent,
- // infer from the initializer of the binding element if one is present.
- // Otherwise, go with the undefined type of the parent.
- if (!parentType) {
- return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType;
- }
- if (isTypeAny(parentType)) {
+ // If no type or an any type was inferred for parent, infer that for the binding element
+ if (!parentType || isTypeAny(parentType)) {
return parentType;
}
// Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
@@ -35393,6 +35670,11 @@
if (optional === void 0) { optional = true; }
return strictNullChecks && optional ? getOptionalType(type) : type;
}
+ function isParameterOfContextuallyTypedFunction(node) {
+ return node.kind === 151 /* Parameter */ &&
+ (node.parent.kind === 196 /* FunctionExpression */ || node.parent.kind === 197 /* ArrowFunction */) &&
+ !!getContextualType(node.parent);
+ }
// Return the inferred type for a variable, parameter, or property declaration
function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
// A variable declared in a for..in statement is of type string, or of type keyof T when the
@@ -35468,8 +35750,9 @@
return containerObjectType;
}
}
- // Use the type of the initializer expression if one is present
- if (declaration.initializer) {
+ // Use the type of the initializer expression if one is present and the declaration is
+ // not a parameter of a contextually typed function
+ if (declaration.initializer && !isParameterOfContextuallyTypedFunction(declaration)) {
var type = checkDeclarationInitializer(declaration);
return addOptionality(type, isOptional);
}
@@ -35478,8 +35761,9 @@
// I.e <Elem attr /> is sugar for <Elem attr={true} />
return trueType;
}
- // If the declaration specifies a binding pattern, use the type implied by the binding pattern
- if (ts.isBindingPattern(declaration.name)) {
+ // If the declaration specifies a binding pattern and is not a parameter of a contextually
+ // typed function, use the type implied by the binding pattern
+ if (ts.isBindingPattern(declaration.name) && !isParameterOfContextuallyTypedFunction(declaration)) {
return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
}
// No type specified and nothing can be inferred
@@ -35535,7 +35819,7 @@
definedInConstructor = true;
}
}
- var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217
+ var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
type = getUnionType(sourceTypes, 2 /* Subtype */);
}
var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
@@ -35686,7 +35970,7 @@
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
var members = ts.createSymbolTable();
var stringIndexInfo;
- var objectFlags = 128 /* ObjectLiteral */;
+ var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
ts.forEach(pattern.elements, function (e) {
var name = e.propertyName || e.name;
if (e.dotDotDotToken) {
@@ -35707,7 +35991,6 @@
members.set(symbol.escapedName, symbol);
});
var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
- result.flags |= 268435456 /* ContainsObjectLiteral */;
result.objectFlags |= objectFlags;
if (includePatternInType) {
result.pattern = pattern;
@@ -35791,7 +36074,16 @@
}
function getTypeOfVariableOrParameterOrProperty(symbol) {
var links = getSymbolLinks(symbol);
- return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol));
+ if (!links.type) {
+ var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
+ // For a contextually typed parameter it is possible that a type has already
+ // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
+ // to preserve this type.
+ if (!links.type) {
+ links.type = type;
+ }
+ }
+ return links.type;
}
function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
// Handle prototype property
@@ -35824,19 +36116,19 @@
}
return type_1;
}
- if (declaration.kind === 254 /* ExportAssignment */) {
- return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
- }
// Handle variable, parameter or property
if (!pushTypeResolution(symbol, 0 /* Type */)) {
// Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
if (symbol.flags & 512 /* ValueModule */) {
return getTypeOfFuncClassEnumModule(symbol);
}
- return errorType;
+ return reportCircularityError(symbol);
}
var type;
- if (ts.isInJSFile(declaration) &&
+ if (declaration.kind === 254 /* ExportAssignment */) {
+ type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
+ }
+ else if (ts.isInJSFile(declaration) &&
(ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) {
type = getWidenedTypeFromAssignmentDeclaration(symbol);
}
@@ -35891,7 +36183,7 @@
if (symbol.flags & 512 /* ValueModule */) {
return getTypeOfFuncClassEnumModule(symbol);
}
- type = reportCircularityError(symbol);
+ return reportCircularityError(symbol);
}
return type;
}
@@ -36069,15 +36361,19 @@
return links.type;
}
function reportCircularityError(symbol) {
+ var declaration = symbol.valueDeclaration;
// Check if variable has type annotation that circularly references the variable itself
- if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) {
+ if (ts.getEffectiveTypeAnnotationNode(declaration)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
return errorType;
}
- // Otherwise variable has initializer that circularly references the variable itself
- if (noImplicitAny) {
+ // Check if variable has initializer that circularly references the variable itself
+ if (noImplicitAny && (declaration.kind !== 151 /* Parameter */ || declaration.initializer)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
}
+ // Circularities could also result from parameters in function expressions that end up
+ // having themselves as contextual types following type argument inference. In those cases
+ // we have already reported an implicit any error so we don't report anything here.
return anyType;
}
function getTypeOfSymbol(symbol) {
@@ -36153,15 +36449,15 @@
case 155 /* MethodSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 308 /* JSDocTemplateTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 181 /* MappedType */:
case 175 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -36282,7 +36578,7 @@
ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
}
}
- addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
+ ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
}
return type.resolvedBaseConstructorType = errorType;
}
@@ -36293,7 +36589,7 @@
function getBaseTypes(type) {
if (!type.resolvedBaseTypes) {
if (type.objectFlags & 8 /* Tuple */) {
- type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))];
+ type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
}
else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
if (type.symbol.flags & 32 /* Class */) {
@@ -36658,7 +36954,7 @@
}
return false;
}
- /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */
+ /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
function isThislessTypeParameter(node) {
var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
return !constraint || isThislessType(constraint);
@@ -36701,6 +36997,8 @@
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 157 /* Constructor */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
return isThislessFunctionLikeDeclaration(declaration);
}
}
@@ -37032,8 +37330,18 @@
return sig;
}
function cloneSignature(sig) {
- return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
+ var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
/*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes);
+ result.target = sig.target;
+ result.mapper = sig.mapper;
+ return result;
+ }
+ function createUnionSignature(signature, unionSignatures) {
+ var result = cloneSignature(signature);
+ result.unionSignatures = unionSignatures;
+ result.target = undefined;
+ result.mapper = undefined;
+ return result;
}
function getExpandedParameters(sig) {
if (sig.hasRestParameter) {
@@ -37142,9 +37450,8 @@
var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */);
thisParameter = createSymbolWithType(signature.thisParameter, thisType);
}
- s = cloneSignature(signature);
+ s = createUnionSignature(signature, unionSignatures);
s.thisParameter = thisParameter;
- s.unionSignatures = unionSignatures;
}
(result || (result = [])).push(s);
}
@@ -37259,13 +37566,22 @@
function unionSpreadIndexInfos(info1, info2) {
return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
}
- function includeMixinType(type, types, index) {
+ function findMixins(types) {
+ var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
+ var mixinFlags = ts.map(types, isMixinConstructorType);
+ if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
+ var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
+ mixinFlags[firstMixinIndex] = false;
+ }
+ return mixinFlags;
+ }
+ function includeMixinType(type, types, mixinFlags, index) {
var mixedTypes = [];
for (var i = 0; i < types.length; i++) {
if (i === index) {
mixedTypes.push(type);
}
- else if (isMixinConstructorType(types[i])) {
+ else if (mixinFlags[i]) {
mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
}
}
@@ -37279,7 +37595,8 @@
var stringIndexInfo;
var numberIndexInfo;
var types = type.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
+ var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
var _loop_6 = function (i) {
var t = type.types[i];
// When an intersection type contains mixin constructor types, the construct signatures from
@@ -37287,12 +37604,12 @@
// other construct signatures in the intersection type. For example, the intersection type
// '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
// 'new(s: string) => A & B'.
- if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) {
+ if (!mixinFlags[i]) {
var signatures = getSignaturesOfType(t, 1 /* Construct */);
if (signatures.length && mixinCount > 0) {
signatures = ts.map(signatures, function (s) {
var clone = cloneSignature(s);
- clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i);
+ clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
return clone;
});
}
@@ -37336,6 +37653,15 @@
var stringIndexInfo = void 0;
if (symbol.exports) {
members = getExportsOfSymbol(symbol);
+ if (symbol === globalThisSymbol) {
+ var varsOnly_1 = ts.createMap();
+ members.forEach(function (p) {
+ if (!(p.flags & 418 /* BlockScoped */)) {
+ varsOnly_1.set(p.escapedName, p);
+ }
+ });
+ members = varsOnly_1;
+ }
}
setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
if (symbol.flags & 32 /* Class */) {
@@ -37635,7 +37961,7 @@
var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
- return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected);
+ return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
});
}
function getAllPossiblePropertiesOfTypes(types) {
@@ -37668,6 +37994,9 @@
return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
}
function getConstraintOfIndexedAccess(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
+ }
+ function getConstraintFromIndexedAccess(type) {
var objectType = getConstraintOfType(type.objectType) || type.objectType;
if (objectType !== type.objectType) {
var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType);
@@ -37680,13 +38009,13 @@
}
function getDefaultConstraintOfConditionalType(type) {
if (!type.resolvedDefaultConstraint) {
- var rootTrueType = type.root.trueType;
- var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */)
- ? rootTrueType
- : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */
- ? rootTrueType.typeVariable
- : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]);
- type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]);
+ // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
+ // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
+ // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
+ // in effect treating `any` like `never` rather than `unknown` in this location.
+ var trueConstraint = getInferredTrueTypeFromConditionalType(type);
+ var falseConstraint = type.falseType;
+ type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
}
return type.resolvedDefaultConstraint;
}
@@ -37696,7 +38025,13 @@
// with its constraint. We do this because if the constraint is a union type it will be distributed
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
- if (type.root.isDistributive) {
+ // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
+ // as the constraint for all type params (check type included) have been replace with `unknown`, which
+ // is going to produce even more false positive/negative results than the distribute constraint already does.
+ // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
+ // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
+ // likely doesn't need to exist.
+ if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
var simplified = getSimplifiedType(type.checkType);
var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
if (constraint && constraint !== type.checkType) {
@@ -37709,9 +38044,12 @@
}
return undefined;
}
- function getConstraintOfConditionalType(type) {
+ function getConstraintFromConditionalType(type) {
return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
}
+ function getConstraintOfConditionalType(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
+ }
function getUnionConstraintOfIntersection(type, targetIsUnion) {
var constraints;
var hasDisjointDomainType = false;
@@ -37785,18 +38123,31 @@
if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
return circularConstraintType;
}
- if (constraintDepth === 50) {
+ if (constraintDepth >= 50) {
// We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
// very high likelyhood we're dealing with an infinite generic type that perpetually generates
// new type identities as we descend into it. We stop the recursion here and mark this type
// and the outer types as having circular constraints.
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
nonTerminating = true;
return t.immediateBaseConstraint = noConstraintType;
}
constraintDepth++;
var result = computeBaseConstraint(getSimplifiedType(t));
constraintDepth--;
- if (!popTypeResolution() || nonTerminating) {
+ if (!popTypeResolution()) {
+ if (t.flags & 262144 /* TypeParameter */) {
+ var errorNode = getConstraintDeclaration(t);
+ if (errorNode) {
+ var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
+ if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
+ }
+ }
+ }
+ result = circularConstraintType;
+ }
+ if (nonTerminating) {
result = circularConstraintType;
}
t.immediateBaseConstraint = result || noConstraintType;
@@ -37838,8 +38189,11 @@
return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined;
}
if (t.flags & 16777216 /* Conditional */) {
- var constraint = getConstraintOfConditionalType(t);
- return constraint && getBaseConstraint(constraint);
+ var constraint = getConstraintFromConditionalType(t);
+ constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
+ var result = constraint && getBaseConstraint(constraint);
+ constraintDepth--;
+ return result;
}
if (t.flags & 33554432 /* Substitution */) {
return getBaseConstraint(t.substitute);
@@ -37900,7 +38254,7 @@
var typeVariable = getHomomorphicTypeVariable(type);
if (typeVariable) {
var constraint = getConstraintOfTypeParameter(typeVariable);
- if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) {
+ if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
var mapper = makeUnaryTypeMapper(typeVariable, constraint);
return instantiateType(type, combineTypeMappers(mapper, type.mapper));
}
@@ -37918,7 +38272,7 @@
t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
t.flags & 132 /* StringLike */ ? globalStringType :
t.flags & 296 /* NumberLike */ ? globalNumberType :
- t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) :
+ t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ESNext */) :
t.flags & 528 /* BooleanLike */ ? globalBooleanType :
t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
@@ -37926,7 +38280,7 @@
t;
}
function createUnionOrIntersectionProperty(containingType, name) {
- var props;
+ var propSet = ts.createMap();
var indexTypes;
var isUnion = containingType.flags & 1048576 /* Union */;
var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0;
@@ -37942,7 +38296,10 @@
var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
if (prop && !(modifiers & excludeModifiers)) {
commonFlags &= prop.flags;
- props = ts.appendIfUnique(props, prop);
+ var id = "" + getSymbolId(prop);
+ if (!propSet.has(id)) {
+ propSet.set(id, prop);
+ }
checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
(!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) |
(modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) |
@@ -37964,9 +38321,10 @@
}
}
}
- if (!props) {
+ if (!propSet.size) {
return undefined;
}
+ var props = ts.arrayFrom(propSet.values());
if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) {
return props[0];
}
@@ -38138,10 +38496,10 @@
function isJSDocOptionalParameter(node) {
return ts.isInJSFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 288 /* JSDocOptionalType */
+ node.type && node.type.kind === 293 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -38175,7 +38533,7 @@
return false;
}
var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}
function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
@@ -38409,32 +38767,23 @@
}
}
signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
- createTypePredicateFromTypePredicateNode(type, signature.declaration) :
+ createTypePredicateFromTypePredicateNode(type, signature) :
jsdocPredicate || noTypePredicate;
}
ts.Debug.assert(!!signature.resolvedTypePredicate);
}
return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
}
- function createTypePredicateFromTypePredicateNode(node, func) {
+ function createTypePredicateFromTypePredicateNode(node, signature) {
var parameterName = node.parameterName;
var type = getTypeFromTypeNode(node.type);
if (parameterName.kind === 72 /* Identifier */) {
- return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type);
+ return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
}
else {
return createThisTypePredicate(type);
}
}
- function getTypePredicateParameterIndex(parameterList, parameter) {
- for (var i = 0; i < parameterList.length; i++) {
- var param = parameterList[i];
- if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) {
- return i;
- }
- }
- return -1;
- }
function getReturnTypeOfSignature(signature) {
if (!signature.resolvedReturnType) {
if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
@@ -38506,8 +38855,19 @@
}
return undefined;
}
- function getSignatureInstantiation(signature, typeArguments, isJavascript) {
- return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ if (inferredTypeParameters) {
+ var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
+ if (returnSignature) {
+ var newReturnSignature = cloneSignature(returnSignature);
+ newReturnSignature.typeParameters = inferredTypeParameters;
+ var newInstantiatedSignature = cloneSignature(instantiatedSignature);
+ newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
+ return newInstantiatedSignature;
+ }
+ }
+ return instantiatedSignature;
}
function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
@@ -38702,10 +39062,10 @@
for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
var type = types_5[_i];
if (!(type.flags & excludeKinds)) {
- result |= type.flags;
+ result |= ts.getObjectFlags(type);
}
}
- return result & 939524096 /* PropagatingFlags */;
+ return result & 917504 /* PropagatingFlags */;
}
function createTypeReference(target, typeArguments) {
var id = getTypeListId(typeArguments);
@@ -38713,7 +39073,7 @@
if (!type) {
type = createObjectType(4 /* Reference */, target.symbol);
target.instantiations.set(id, type);
- type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
+ type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
type.target = target;
type.typeArguments = typeArguments;
}
@@ -38879,7 +39239,7 @@
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
- if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
+ if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
if (jsdocType) {
return jsdocType;
@@ -38900,6 +39260,9 @@
}
}
function getSubstitutionType(typeVariable, substitute) {
+ if (substitute.flags & 3 /* AnyOrUnknown */) {
+ return typeVariable;
+ }
var result = createType(33554432 /* Substitution */);
result.typeVariable = typeVariable;
result.substitute = substitute;
@@ -38915,7 +39278,7 @@
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) {
+ while (node && !ts.isStatement(node) && node.kind !== 296 /* JSDocComment */) {
var parent = node.parent;
if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -39147,19 +39510,19 @@
function createIterableIteratorType(iteratedType) {
return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]);
}
- function createArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalArrayType, [elementType]);
- }
- function createReadonlyArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]);
+ function createArrayType(elementType, readonly) {
+ return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
}
function getTypeFromArrayTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType));
+ links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType), isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
+ function isReadonlyTypeOperator(node) {
+ return ts.isTypeOperatorNode(node) && node.operator === 133 /* ReadonlyKeyword */;
+ }
// We represent tuple types as type references to synthesized generic interface types created by
// this function. The types are of the form:
//
@@ -39167,7 +39530,7 @@
//
// Note that the generic type created by this function has no symbol associated with it. The same
// is true for each of the synthesized type parameters.
- function createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) {
+ function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
var typeParameters;
var properties = [];
var maxLength = hasRestElement ? arity - 1 : arity;
@@ -39176,7 +39539,7 @@
for (var i = 0; i < arity; i++) {
var typeParameter = typeParameters[i] = createTypeParameter();
if (i < maxLength) {
- var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i);
+ var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
property.type = typeParameter;
properties.push(property);
}
@@ -39206,25 +39569,27 @@
type.declaredNumberIndexInfo = undefined;
type.minLength = minLength;
type.hasRestElement = hasRestElement;
+ type.readonly = readonly;
type.associatedNames = associatedNames;
return type;
}
- function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) {
- var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
+ function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
+ var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
var type = tupleTypes.get(key);
if (!type) {
- tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames));
+ tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
}
return type;
}
- function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) {
+ function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
if (minLength === void 0) { minLength = elementTypes.length; }
if (hasRestElement === void 0) { hasRestElement = false; }
+ if (readonly === void 0) { readonly = false; }
var arity = elementTypes.length;
if (arity === 1 && hasRestElement) {
- return createArrayType(elementTypes[0]);
+ return createArrayType(elementTypes[0], readonly);
}
- var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames);
+ var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
}
function getTypeFromTupleTypeNode(node) {
@@ -39237,7 +39602,7 @@
var type = getTypeFromTypeNode(n);
return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type;
});
- links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1);
+ links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1, isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
@@ -39247,7 +39612,7 @@
// don't slice off rest element
index = Math.min(index, getTypeReferenceArity(type) - 1);
}
- return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index));
+ return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
}
function getTypeFromOptionalTypeNode(node) {
var type = getTypeFromTypeNode(node.type);
@@ -39305,12 +39670,14 @@
// intersections of unit types into 'never' upon construction, but deferring the reduction makes it
// easier to reason about their origin.
if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) {
- includes |= flags & ~939524096 /* ConstructionFlags */;
+ includes |= flags & 1835007 /* IncludesMask */;
+ if (flags & 66846720 /* StructuredOrInstantiable */)
+ includes |= 262144 /* IncludesStructuredOrInstantiable */;
if (type === wildcardType)
- includes |= 268435456 /* Wildcard */;
+ includes |= 4194304 /* IncludesWildcard */;
if (!strictNullChecks && flags & 98304 /* Nullable */) {
- if (!(flags & 134217728 /* ContainsWideningType */))
- includes |= 134217728 /* NonWideningType */;
+ if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */))
+ includes |= 2097152 /* IncludesNonWideningType */;
}
else {
var len = typeSet.length;
@@ -39331,17 +39698,6 @@
}
return includes;
}
- function isSubtypeOfAny(source, targets) {
- for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
- var target = targets_1[_i];
- if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
- !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
- isTypeDerivedFrom(source, target))) {
- return true;
- }
- }
- return false;
- }
function isSetOfLiteralsFromSameEnum(types) {
var first = types[0];
if (first.flags & 1024 /* EnumLiteral */) {
@@ -39356,18 +39712,43 @@
}
return false;
}
- function removeSubtypes(types) {
- if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) {
- return;
+ function removeSubtypes(types, primitivesOnly) {
+ var len = types.length;
+ if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
+ return true;
}
- var i = types.length;
+ var i = len;
+ var count = 0;
while (i > 0) {
i--;
- if (isSubtypeOfAny(types[i], types)) {
+ var source = types[i];
+ for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
+ var target = types_7[_i];
+ if (source !== target) {
+ if (count === 100000) {
+ // After 100000 subtype checks we estimate the remaining amount of work by assuming the
+ // same ratio of checks per element. If the estimated number of remaining type checks is
+ // greater than an upper limit we deem the union type too complex to represent. The
+ // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
+ // caps union types at 5000 unique literal types and 1000 unique object types.
+ var estimatedCount = (count / (len - i)) * len;
+ if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
+ error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
+ return false;
+ }
+ }
+ count++;
+ if (isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
+ !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
+ isTypeDerivedFrom(source, target))) {
ts.orderedRemoveItemAt(types, i);
+ break;
+ }
}
}
}
+ return true;
+ }
function removeRedundantLiteralTypes(types, includes) {
var i = types.length;
while (i > 0) {
@@ -39402,25 +39783,27 @@
var includes = addTypesToUnion(typeSet, 0, types);
if (unionReduction !== 0 /* None */) {
if (includes & 3 /* AnyOrUnknown */) {
- return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType;
+ return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
}
switch (unionReduction) {
case 1 /* Literal */:
- if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) {
+ if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
removeRedundantLiteralTypes(typeSet, includes);
}
break;
case 2 /* Subtype */:
- removeSubtypes(typeSet);
+ if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
+ return errorType;
+ }
break;
}
if (typeSet.length === 0) {
- return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType :
- includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType :
+ return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType :
+ includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
neverType;
}
}
- return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments);
+ return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments);
}
function getUnionTypePredicate(signatures) {
var first;
@@ -39457,7 +39840,7 @@
: !ts.isIdentifierTypePredicate(b);
}
// This function assumes the constituent type list is sorted and deduplicated.
- function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) {
+ function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
if (types.length === 0) {
return neverType;
}
@@ -39467,11 +39850,10 @@
var id = getTypeListId(types);
var type = unionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
- type = createType(1048576 /* Union */ | propagatedFlags);
+ type = createType(1048576 /* Union */);
unionTypes.set(id, type);
+ type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
type.types = types;
- type.primitiveTypesOnly = primitiveTypesOnly;
/*
Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
@@ -39497,16 +39879,16 @@
return addTypesToIntersection(typeSet, includes, type.types);
}
if (isEmptyAnonymousObjectType(type)) {
- if (!(includes & 536870912 /* EmptyObject */)) {
- includes |= 536870912 /* EmptyObject */;
+ if (!(includes & 8388608 /* IncludesEmptyObject */)) {
+ includes |= 8388608 /* IncludesEmptyObject */;
typeSet.push(type);
}
}
else {
- includes |= flags & ~939524096 /* ConstructionFlags */;
+ includes |= flags & 1835007 /* IncludesMask */;
if (flags & 3 /* AnyOrUnknown */) {
if (type === wildcardType)
- includes |= 268435456 /* Wildcard */;
+ includes |= 4194304 /* IncludesWildcard */;
}
else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) {
typeSet.push(type);
@@ -39517,8 +39899,8 @@
// Add the given types to the given type set. Order is preserved, freshness is removed from literal
// types, duplicates are removed, and nested types of the given kind are flattened into the set.
function addTypesToIntersection(typeSet, includes, types) {
- for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
- var type = types_7[_i];
+ for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
+ var type = types_8[_i];
includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
}
return includes;
@@ -39561,7 +39943,7 @@
// other unions and return true. Otherwise, do nothing and return false.
function intersectUnionsOfPrimitiveTypes(types) {
var unionTypes;
- var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576 /* Union */) && t.primitiveTypesOnly; });
+ var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); });
if (index < 0) {
return false;
}
@@ -39570,7 +39952,7 @@
// the unionTypes array.
while (i < types.length) {
var t = types[i];
- if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) {
+ if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) {
(unionTypes || (unionTypes = [types[index]])).push(t);
ts.orderedRemoveItemAt(types, i);
}
@@ -39599,7 +39981,7 @@
}
}
// Finally replace the first union with the result
- types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true);
+ types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */);
return true;
}
// We normalize combinations of intersection and union types based on the distributive property of the '&'
@@ -39619,7 +40001,7 @@
return neverType;
}
if (includes & 1 /* Any */) {
- return includes & 268435456 /* Wildcard */ ? wildcardType : anyType;
+ return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType;
}
if (!strictNullChecks && includes & 98304 /* Nullable */) {
return includes & 32768 /* Undefined */ ? undefinedType : nullType;
@@ -39630,7 +40012,7 @@
includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
removeRedundantPrimitiveTypes(typeSet, includes);
}
- if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) {
+ if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
}
if (typeSet.length === 0) {
@@ -39655,9 +40037,9 @@
var id = getTypeListId(typeSet);
var type = intersectionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */);
- type = createType(2097152 /* Intersection */ | propagatedFlags);
+ type = createType(2097152 /* Intersection */);
intersectionTypes.set(id, type);
+ type.objectFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */);
type.types = typeSet;
type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
type.aliasTypeArguments = aliasTypeArguments;
@@ -39712,7 +40094,7 @@
return neverType;
}
function getLiteralTypeFromProperties(type, include) {
- return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); }));
+ return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
}
function getNonEnumNumberIndexInfo(type) {
var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
@@ -39754,6 +40136,9 @@
? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
: errorType;
break;
+ case 133 /* ReadonlyKeyword */:
+ links.resolvedType = getTypeFromTypeNode(node.type);
+ break;
}
}
return links.resolvedType; // TODO: GH#18217
@@ -39856,7 +40241,10 @@
return anyType;
}
if (accessExpression && !isConstEnumObjectType(objectType)) {
- if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
+ if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
+ error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
+ }
+ else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
}
@@ -39908,7 +40296,7 @@
: accessNode;
}
function isGenericObjectType(type) {
- return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */);
+ return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 131072 /* GenericMappedType */);
}
function isGenericIndexType(type) {
return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */);
@@ -39954,12 +40342,15 @@
// that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
// construct the type Box<T[X]>.
if (isGenericMappedType(objectType)) {
- var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
- var templateMapper = combineTypeMappers(objectType.mapper, mapper);
- return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType);
+ return type.simplified = mapType(substituteIndexedMappedType(objectType, type.indexType), getSimplifiedType);
}
return type.simplified = type;
}
+ function substituteIndexedMappedType(objectType, index) {
+ var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
+ var templateMapper = combineTypeMappers(objectType.mapper, mapper);
+ return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
+ }
function getIndexedAccessType(objectType, indexType, accessNode, missingType) {
if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; }
if (objectType === wildcardType || indexType === wildcardType) {
@@ -40041,13 +40432,48 @@
function getActualTypeVariable(type) {
return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type;
}
+ /**
+ * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
+ */
+ function isIntersectionEmpty(type1, type2) {
+ return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
+ }
function getConditionalType(root, mapper) {
var checkType = instantiateType(root.checkType, mapper);
var extendsType = instantiateType(root.extendsType, mapper);
if (checkType === wildcardType || extendsType === wildcardType) {
return wildcardType;
}
- var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */);
+ var trueType = instantiateType(root.trueType, mapper);
+ var falseType = instantiateType(root.falseType, mapper);
+ var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType);
+ var result = conditionalTypes.get(instantiationId);
+ if (result) {
+ return result;
+ }
+ var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType);
+ conditionalTypes.set(instantiationId, newResult);
+ return newResult;
+ }
+ function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) {
+ // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
+ if (falseType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) {
+ if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
+ return trueType;
+ }
+ else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
+ return neverType;
+ }
+ }
+ else if (trueType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(falseType), getActualTypeVariable(checkType))) {
+ if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
+ return neverType;
+ }
+ else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
+ return falseType;
+ }
+ }
+ var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */);
var combinedMapper;
if (root.inferTypeParameters) {
var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
@@ -40057,25 +40483,25 @@
// types rules (i.e. proper contravariance) for inferences.
inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
}
- combinedMapper = combineTypeMappers(mapper, context);
+ combinedMapper = combineTypeMappers(mapper, context.mapper);
}
// Instantiate the extends type including inferences for 'infer T' type parameters
var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
// We attempt to resolve the conditional type only when the check and extends types are non-generic
- if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */)) {
+ if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) {
if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) {
- return instantiateType(root.trueType, mapper);
+ return trueType;
}
// Return union of trueType and falseType for 'any' since it matches anything
if (checkType.flags & 1 /* Any */) {
- return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
+ return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]);
}
- // Return falseType for a definitely false extends check. We check an instantations of the two
+ // Return falseType for a definitely false extends check. We check an instantiations of the two
// types with type parameters mapped to the wildcard type, the most permissive instantiations
// possible (the wildcard type is assignable to and from all types). If those are not related,
- // then no instatiations will be and we can just return the false branch type.
+ // then no instantiations will be and we can just return the false branch type.
if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) {
- return instantiateType(root.falseType, mapper);
+ return falseType;
}
// Return trueType for a definitely true extends check. We check instantiations of the two
// types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
@@ -40087,6 +40513,9 @@
}
}
// Return a deferred type for a check that is neither definitely true nor definitely false
+ return getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType);
+ }
+ function getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType) {
var erasedCheckType = getActualTypeVariable(checkType);
var result = createType(16777216 /* Conditional */);
result.root = root;
@@ -40094,15 +40523,14 @@
result.extendsType = extendsType;
result.mapper = mapper;
result.combinedMapper = combinedMapper;
+ result.trueType = trueType;
+ result.falseType = falseType;
result.aliasSymbol = root.aliasSymbol;
result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
return result;
}
- function getTrueTypeFromConditionalType(type) {
- return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
- }
- function getFalseTypeFromConditionalType(type) {
- return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
+ function getInferredTrueTypeFromConditionalType(type) {
+ return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper));
}
function getInferTypeParameters(node) {
var result;
@@ -40271,7 +40699,7 @@
* this function should be called in a left folding style, with left = previous result of getSpreadType
* and right = the new element to be spread.
*/
- function getSpreadType(left, right, symbol, typeFlags, objectFlags) {
+ function getSpreadType(left, right, symbol, objectFlags, readonly) {
if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
return anyType;
}
@@ -40285,10 +40713,10 @@
return left;
}
if (left.flags & 1048576 /* Union */) {
- return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); });
+ return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
}
if (right.flags & 1048576 /* Union */) {
- return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); });
+ return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
}
if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
return left;
@@ -40304,7 +40732,7 @@
var types = left.types;
var lastLeft = types[types.length - 1];
if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
- return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)]));
+ return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
}
}
return getIntersectionType([left, right]);
@@ -40328,7 +40756,7 @@
skippedPrivateMembers.set(rightProp.escapedName, true);
}
else if (isSpreadableProperty(rightProp)) {
- members.set(rightProp.escapedName, getSpreadSymbol(rightProp));
+ members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
}
}
for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
@@ -40352,12 +40780,11 @@
}
}
else {
- members.set(leftProp.escapedName, getSpreadSymbol(leftProp));
+ members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
}
}
- var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo));
- spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags;
- spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
+ var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
+ spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
return spread;
}
/** We approximate own properties as non-methods plus methods that are inside the object literal */
@@ -40365,25 +40792,21 @@
return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
!prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); });
}
- function getSpreadSymbol(prop) {
- var isReadonly = isReadonlySymbol(prop);
+ function getSpreadSymbol(prop, readonly) {
var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
- if (!isReadonly && !isSetonlyAccessor) {
+ if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
return prop;
}
var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
- var result = createSymbol(flags, prop.escapedName);
+ var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
result.declarations = prop.declarations;
result.nameType = prop.nameType;
result.syntheticOrigin = prop;
return result;
}
- function getNonReadonlyIndexSignature(index) {
- if (index && index.isReadonly) {
- return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration);
- }
- return index;
+ function getIndexInfoWithReadonly(info, readonly) {
+ return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
}
function createLiteralType(flags, value, symbol) {
var type = createType(flags);
@@ -40471,8 +40894,8 @@
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 120 /* AnyKeyword */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return anyType;
case 143 /* UnknownKeyword */:
return unknownType;
@@ -40519,23 +40942,23 @@
return getTypeFromUnionTypeNode(node);
case 174 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 177 /* ParenthesizedType */:
case 172 /* RestType */:
- case 287 /* JSDocNonNullableType */:
- case 283 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 288 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 297 /* JSDocTypeLiteral */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 179 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -40611,16 +41034,8 @@
* Maps forward-references to later types parameters to the empty object type.
* This is used during inference when instantiating type parameter defaults.
*/
- function createBackreferenceMapper(typeParameters, index) {
- return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; };
- }
- function isInferenceContext(mapper) {
- return !!mapper.typeParameters;
- }
- function cloneTypeMapper(mapper) {
- return mapper && isInferenceContext(mapper) ?
- createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
- mapper;
+ function createBackreferenceMapper(context, index) {
+ return function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? emptyObjectType : t; };
}
function combineTypeMappers(mapper1, mapper2) {
if (!mapper1)
@@ -40703,7 +41118,7 @@
}
// Keep the flags from the symbol we're instantiating. Mark that is instantiated, and
// also transient so that we can just store data on it directly.
- var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */));
+ var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */));
result.declarations = symbol.declarations;
result.parent = symbol.parent;
result.target = symbol;
@@ -40799,7 +41214,7 @@
function getHomomorphicTypeVariable(type) {
var constraintType = getConstraintTypeFromMappedType(type);
if (constraintType.flags & 4194304 /* Index */) {
- var typeVariable = constraintType.type;
+ var typeVariable = getActualTypeVariable(constraintType.type);
if (typeVariable.flags & 262144 /* TypeParameter */) {
return typeVariable;
}
@@ -40821,30 +41236,27 @@
if (typeVariable) {
var mappedTypeVariable = instantiateType(typeVariable, mapper);
if (typeVariable !== mappedTypeVariable) {
- // If we are already in the process of creating an instantiation of this mapped type,
- // return the error type. This situation only arises if we are instantiating the mapped
- // type for an array or tuple type, as we then need to eagerly resolve the (possibly
- // circular) element type(s).
- if (type.instantiating) {
- return errorType;
- }
- type.instantiating = true;
- var result = mapType(mappedTypeVariable, function (t) {
- if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) {
+ return mapType(mappedTypeVariable, function (t) {
+ if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
var replacementMapper = createReplacementMapper(typeVariable, t, mapper);
- return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
- isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
+ return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
instantiateAnonymousType(type, replacementMapper);
}
return t;
});
- type.instantiating = false;
- return result;
}
}
return instantiateAnonymousType(type, mapper);
}
+ function getModifiedReadonlyState(state, modifiers) {
+ return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
+ }
+ function instantiateMappedArrayType(arrayType, mappedType, mapper) {
+ var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
+ return elementType === errorType ? errorType :
+ createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
+ }
function instantiateMappedTupleType(tupleType, mappedType, mapper) {
var minLength = tupleType.target.minLength;
var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) {
@@ -40854,7 +41266,9 @@
var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 :
modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) :
minLength;
- return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames);
+ var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
+ return ts.contains(elementTypes, errorType) ? errorType :
+ createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
}
function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key]));
@@ -40920,6 +41334,7 @@
// We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
// with a combination of infinite generic types that perpetually generate new type identities. We stop
// the recursion here by yielding the error type.
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
return errorType;
}
instantiationDepth++;
@@ -40971,7 +41386,17 @@
return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
}
if (flags & 33554432 /* Substitution */) {
- return instantiateType(type.typeVariable, mapper);
+ var maybeVariable = instantiateType(type.typeVariable, mapper);
+ if (maybeVariable.flags & 8650752 /* TypeVariable */) {
+ return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
+ }
+ else {
+ var sub = instantiateType(type.substitute, mapper);
+ if (sub.flags & 3 /* AnyOrUnknown */ || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
+ return maybeVariable;
+ }
+ return sub;
+ }
}
return type;
}
@@ -40980,8 +41405,20 @@
type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
}
function getRestrictiveInstantiation(type) {
- return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
- type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper));
+ if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
+ return type;
+ }
+ if (type.restrictiveInstantiation) {
+ return type.restrictiveInstantiation;
+ }
+ type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
+ // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
+ // which is redundant - we'll produce new type identities, but all type params have already been mapped.
+ // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
+ // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
+ // are constrained to `unknown` and produce tons of false positives/negatives!
+ type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
+ return type.restrictiveInstantiation;
}
function instantiateIndexInfo(info, mapper) {
return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
@@ -41180,7 +41617,7 @@
var resultObj = {};
checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj);
var diagnostic = resultObj.error;
- addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
return true;
}
}
@@ -41215,7 +41652,7 @@
checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj);
if (resultObj.error) {
if (target.symbol && ts.length(target.symbol.declarations)) {
- addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
+ ts.addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
}
return true;
}
@@ -41262,13 +41699,13 @@
undefined;
if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
issuedElaboration = true;
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
+ ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
}
}
if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
+ ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
}
}
}
@@ -41339,7 +41776,7 @@
// child is of the type of the expression
return { errorNode: child, innerExpression: child.expression, nameType: nameType };
case 11 /* JsxText */:
- if (child.containsOnlyWhiteSpaces) {
+ if (child.containsOnlyTriviaWhiteSpaces) {
break; // Whitespace only jsx text isn't real jsx text
}
// child is a string
@@ -41362,7 +41799,7 @@
var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
var childrenNameType = getLiteralType(childrenPropName);
var childrenTargetType = getIndexedAccessType(target, childrenNameType);
- var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; });
+ var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
if (!ts.length(validChildren)) {
return result;
}
@@ -41450,7 +41887,7 @@
return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
}
// recreate a tuple from the elements, if possible
- var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true);
+ var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
if (isTupleLikeType(tupleizedType)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
}
@@ -41516,6 +41953,14 @@
/*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */;
}
/**
+ * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
+ */
+ function isAnySignature(s) {
+ return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
+ s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
+ isTypeAny(getReturnTypeOfSignature(s));
+ }
+ /**
* See signatureRelatedTo, compareSignaturesIdentical
*/
function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) {
@@ -41523,13 +41968,16 @@
if (source === target) {
return -1 /* True */;
}
+ if (isAnySignature(target)) {
+ return -1 /* True */;
+ }
var targetCount = getParameterCount(target);
if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) {
return 0 /* False */;
}
if (source.typeParameters && source.typeParameters !== target.typeParameters) {
target = getCanonicalSignature(target);
- source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes);
+ source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
}
var sourceCount = getParameterCount(source);
var sourceRestType = getNonArrayRestType(source);
@@ -41600,7 +42048,7 @@
if (targetTypePredicate) {
var sourceTypePredicate = getTypePredicateOfSignature(source);
if (sourceTypePredicate) {
- result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217
+ result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
}
else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
if (reportErrors) {
@@ -41619,7 +42067,7 @@
}
return result;
}
- function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) {
+ function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
if (source.kind !== target.kind) {
if (reportErrors) {
errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
@@ -41628,12 +42076,9 @@
return 0 /* False */;
}
if (source.kind === 1 /* Identifier */) {
- var targetPredicate = target;
- var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0);
- var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0);
- if (sourceIndex !== targetIndex) {
+ if (source.parameterIndex !== target.parameterIndex) {
if (reportErrors) {
- errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName);
+ errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
}
return 0 /* False */;
@@ -41834,7 +42279,7 @@
}
var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
if (relatedInfo) {
- addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
+ ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
}
if (errorOutputContainer) {
errorOutputContainer.error = diag;
@@ -42441,8 +42886,8 @@
if (source.root.isDistributive === target.root.isDistributive) {
if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
- if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
- if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
+ if (result_3 &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) {
+ if (result_3 &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) {
return result_3;
}
}
@@ -42457,6 +42902,7 @@
}
var result;
var originalErrorInfo;
+ var varianceCheckFailed = false;
var saveErrorInfo = errorInfo;
// We limit alias variance probing to only object and conditional types since their alias behavior
// is more predictable than other, interned types, which may or may not have an alias depending on
@@ -42465,11 +42911,10 @@
source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
!(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
var variances = getAliasVariances(source.aliasSymbol);
- if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) {
- return result;
+ var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
}
if (target.flags & 262144 /* TypeParameter */) {
// A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q].
@@ -42526,9 +42971,18 @@
template.indexType === getTypeParameterFromMappedType(target)) {
return -1 /* True */;
}
+ if (!isGenericMappedType(source)) {
+ var targetConstraint = getConstraintTypeFromMappedType(target);
+ var sourceKeys_1 = getIndexType(source);
+ var hasOptionalUnionKeys = modifiers & 4 /* IncludeOptional */ && targetConstraint.flags & 1048576 /* Union */;
+ var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined;
// A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X.
- if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) {
- var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target));
+ // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X.
+ if (hasOptionalUnionKeys
+ ? !(filteredByApplicability.flags & 131072 /* Never */)
+ : isRelatedTo(targetConstraint, sourceKeys_1)) {
+ var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target);
+ var indexedAccessType = getIndexedAccessType(source, indexingType);
var templateType = getTemplateTypeFromMappedType(target);
if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
return result;
@@ -42538,6 +42992,7 @@
errorInfo = saveErrorInfo;
}
}
+ }
if (source.flags & 8650752 /* TypeVariable */) {
if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
// A type S[K] is related to a type T[J] if S is related to T and K is related to J.
@@ -42581,8 +43036,8 @@
// and Y1 is related to Y2.
if (isTypeIdenticalTo(source.extendsType, target.extendsType) &&
(isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
- if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) {
- result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
+ if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) {
+ result &= isRelatedTo(source.falseType, target.falseType, reportErrors);
}
if (result) {
errorInfo = saveErrorInfo;
@@ -42631,36 +43086,19 @@
// type references (which are intended by be compared structurally). Obtain the variance
// information for the type parameters and relate the type arguments accordingly.
var variances = getVariances(source.target);
- if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) {
- return result;
- }
- // The type arguments did not relate appropriately, but it may be because we have no variance
- // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
- // arguments). It might also be the case that the target type has a 'void' type argument for
- // a covariant type parameter that is only used in return positions within the generic type
- // (in which case any type argument is permitted on the source side). In those cases we proceed
- // with a structural comparison. Otherwise, we know for certain the instantiations aren't
- // related and we can return here.
- if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) {
- // In some cases generic types that are covariant in regular type checking mode become
- // invariant in --strictFunctionTypes mode because one or more type parameters are used in
- // both co- and contravariant positions. In order to make it easier to diagnose *why* such
- // types are invariant, if any of the type parameters are invariant we reset the reported
- // errors and instead force a structural comparison (which will include elaborations that
- // reveal the reason).
- if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
- return 0 /* False */;
+ var varianceResult = relateVariances(source.typeArguments, target.typeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
- // We remember the original error information so we can restore it in case the structural
- // comparison unexpectedly succeeds. This can happen when the structural comparison result
- // is a Ternary.Maybe for example caused by the recursion depth limiter.
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
}
- }
- else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) {
+ else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
}
+ // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
+ // and not `{} <- fresh({}) <- {[idx: string]: any}`
+ else if (relation === subtypeRelation && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
+ return 0 /* False */;
+ }
// Even if relationship doesn't hold for unions, intersections, or generic type references,
// it may hold in a structural comparison.
// In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
@@ -42682,17 +43120,57 @@
}
}
}
- if (result) {
- if (!originalErrorInfo) {
- errorInfo = saveErrorInfo;
+ if (varianceCheckFailed && result) {
+ errorInfo = originalErrorInfo || errorInfo || saveErrorInfo; // Use variance error (there is no structural one) and return false
+ }
+ else if (result) {
return result;
}
- errorInfo = originalErrorInfo;
}
}
+ return 0 /* False */;
+ function isNonGeneric(type) {
+ // If we're already in identity relationship checking, we should use `isRelatedTo`
+ // to catch the `Maybe` from an excessively deep type (which we then assume means
+ // that the type could possibly contain a generic)
+ if (relation === identityRelation) {
+ return isRelatedTo(type, getPermissiveInstantiation(type)) === -1 /* True */;
}
+ return isTypeIdenticalTo(type, getPermissiveInstantiation(type));
+ }
+ function relateVariances(sourceTypeArguments, targetTypeArguments, variances) {
+ if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors)) {
+ return result;
+ }
+ var allowStructuralFallback = (targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances)) || isNonGeneric(source) || isNonGeneric(target);
+ varianceCheckFailed = !allowStructuralFallback;
+ // The type arguments did not relate appropriately, but it may be because we have no variance
+ // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
+ // arguments). It might also be the case that the target type has a 'void' type argument for
+ // a covariant type parameter that is only used in return positions within the generic type
+ // (in which case any type argument is permitted on the source side). In those cases we proceed
+ // with a structural comparison. Otherwise, we know for certain the instantiations aren't
+ // related and we can return here.
+ if (variances !== ts.emptyArray && !allowStructuralFallback) {
+ // In some cases generic types that are covariant in regular type checking mode become
+ // invariant in --strictFunctionTypes mode because one or more type parameters are used in
+ // both co- and contravariant positions. In order to make it easier to diagnose *why* such
+ // types are invariant, if any of the type parameters are invariant we reset the reported
+ // errors and instead force a structural comparison (which will include elaborations that
+ // reveal the reason).
+ // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
+ // we can return `False` early here to skip calculating the structural error message we don't need.
+ if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
return 0 /* False */;
}
+ // We remember the original error information so we can restore it in case the structural
+ // comparison unexpectedly succeeds. This can happen when the structural comparison result
+ // is a Ternary.Maybe for example caused by the recursion depth limiter.
+ originalErrorInfo = errorInfo;
+ errorInfo = saveErrorInfo;
+ }
+ }
+ }
// 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.
@@ -43171,20 +43649,17 @@
return variances;
}
function getVariances(type) {
- if (!strictFunctionTypes) {
- return ts.emptyArray;
- }
- if (type === globalArrayType || type === globalReadonlyArrayType) {
- // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters)
+ // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters)
+ if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
return ts.emptyArray;
}
return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
}
// Return true if the given type reference has a 'void' type argument for a covariant type parameter.
// See comment at call in recursiveTypeRelatedTo for when this case matters.
- function hasCovariantVoidArgument(type, variances) {
+ function hasCovariantVoidArgument(typeArguments, variances) {
for (var i = 0; i < variances.length; i++) {
- if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) {
+ if (variances[i] === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
return true;
}
}
@@ -43413,8 +43888,8 @@
}
function literalTypesWithSameBaseType(types) {
var commonBaseType;
- for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
- var t = types_8[_i];
+ for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
+ var t = types_9[_i];
var baseType = getBaseTypeOfLiteralType(t);
if (!commonBaseType) {
commonBaseType = baseType;
@@ -43447,7 +43922,7 @@
return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
}
function isArrayType(type) {
- return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType;
+ return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
}
function isReadonlyArrayType(type) {
return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
@@ -43458,8 +43933,7 @@
function isArrayLikeType(type) {
// A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
// or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
- return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) ||
- !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
+ return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
}
function isEmptyArrayLiteralType(type) {
var elementType = isArrayType(type) ? type.typeArguments[0] : undefined;
@@ -43544,8 +44018,8 @@
}
function getFalsyFlagsOfTypes(types) {
var result = 0;
- for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
- var t = types_9[_i];
+ for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
+ var t = types_10[_i];
result |= getFalsyFlags(t);
}
return result;
@@ -43659,7 +44133,7 @@
var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
regularNew.flags = resolved.flags;
- regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */);
+ regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
type.regularType = regularNew;
return regularNew;
}
@@ -43745,7 +44219,7 @@
return getWidenedTypeWithContext(type, /*context*/ undefined);
}
function getWidenedTypeWithContext(type, context) {
- if (type.flags & 402653184 /* RequiresWidening */) {
+ if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) {
if (type.flags & 98304 /* Nullable */) {
return anyType;
}
@@ -43782,7 +44256,7 @@
*/
function reportWideningErrorsInType(type) {
var errorReported = false;
- if (type.flags & 134217728 /* ContainsWideningType */) {
+ if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
if (type.flags & 1048576 /* Union */) {
if (ts.some(type.types, isEmptyObjectType)) {
errorReported = true;
@@ -43808,7 +44282,7 @@
for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
var p = _e[_d];
var t = getTypeOfSymbol(p);
- if (t.flags & 134217728 /* ContainsWideningType */) {
+ if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) {
if (!reportWideningErrorsInType(t)) {
error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
}
@@ -43854,7 +44328,7 @@
return;
}
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
case 239 /* FunctionDeclaration */:
@@ -43881,14 +44355,14 @@
errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
}
function reportErrorsFromWidening(declaration, type) {
- if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) {
+ if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
// Report implicit any error within type if possible, otherwise report error on declaration
if (!reportWideningErrorsInType(type)) {
reportImplicitAny(declaration, type);
}
}
}
- function forEachMatchingParameterType(source, target, callback) {
+ function applyToParameterTypes(source, target, callback) {
var sourceCount = getParameterCount(source);
var targetCount = getParameterCount(target);
var sourceRestType = getEffectiveRestType(source);
@@ -43909,25 +44383,55 @@
callback(getRestTypeAtPosition(source, paramCount), targetRestType);
}
}
- function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
- var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo);
- var context = mapper;
- context.typeParameters = typeParameters;
- context.signature = signature;
- context.inferences = inferences;
- context.flags = flags;
- context.compareTypes = compareTypes || compareTypesAssignable;
+ function applyToReturnTypes(source, target, callback) {
+ var sourceTypePredicate = getTypePredicateOfSignature(source);
+ var targetTypePredicate = getTypePredicateOfSignature(target);
+ if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind &&
+ (sourceTypePredicate.kind === 0 /* This */ || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) {
+ callback(sourceTypePredicate.type, targetTypePredicate.type);
+ }
+ else {
+ callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
+ }
+ }
+ function createInferenceContext(typeParameters, signature, flags, compareTypes) {
+ return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
+ }
+ function cloneInferenceContext(context, extraFlags) {
+ if (extraFlags === void 0) { extraFlags = 0; }
+ return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
+ }
+ function cloneInferredPartOfContext(context) {
+ var inferences = ts.filter(context.inferences, hasInferenceCandidates);
+ return inferences.length ?
+ createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
+ undefined;
+ }
+ function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
+ var context = {
+ inferences: inferences,
+ signature: signature,
+ flags: flags,
+ compareTypes: compareTypes,
+ mapper: function (t) { return mapToInferredType(context, t, /*fix*/ true); },
+ nonFixingMapper: function (t) { return mapToInferredType(context, t, /*fix*/ false); },
+ };
return context;
- function mapper(t) {
+ }
+ function mapToInferredType(context, t, fix) {
+ var inferences = context.inferences;
for (var i = 0; i < inferences.length; i++) {
- if (t === inferences[i].typeParameter) {
- inferences[i].isFixed = true;
+ var inference = inferences[i];
+ if (t === inference.typeParameter) {
+ if (fix && !inference.isFixed) {
+ inference.isFixed = true;
+ inference.inferredType = undefined;
+ }
return getInferredType(context, i);
}
}
return t;
}
- }
function createInferenceInfo(typeParameter) {
return {
typeParameter: typeParameter,
@@ -43950,6 +44454,9 @@
isFixed: inference.isFixed
};
}
+ function getMapperFromContext(context) {
+ return context && context.mapper;
+ }
// Return true if the given type could possibly reference a type parameter for which
// we perform type inference (i.e. a type parameter of a generic function). We cache
// results for union and intersection types for performance reasons.
@@ -44014,23 +44521,20 @@
// is incomplete and we can't infer a meaningful input type.
for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
var prop = properties_3[_i];
- if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) {
+ if (ts.getObjectFlags(getTypeOfSymbol(prop)) & 524288 /* ContainsAnyFunctionType */) {
return undefined;
}
}
// For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
// applied to the element type(s).
if (isArrayType(source)) {
- return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint));
- }
- if (isReadonlyArrayType(source)) {
- return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint));
+ return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint), isReadonlyArrayType(source));
}
if (isTupleType(source)) {
var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); });
var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength;
- return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames);
+ return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, source.target.associatedNames);
}
// For all other object types we infer a new object type where the reverse mapping has been
// applied to the type of each property.
@@ -44104,11 +44608,11 @@
inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
emptyObjectType;
}
- function inferTypes(inferences, originalSource, originalTarget, priority) {
+ function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
if (priority === void 0) { priority = 0; }
+ if (contravariant === void 0) { contravariant = false; }
var symbolStack;
var visited;
- var contravariant = false;
var bivariant = false;
var propagationType;
var allowComplexConstraintInference = true;
@@ -44184,7 +44688,7 @@
// 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.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) {
+ if (ts.getObjectFlags(source) & 524288 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) {
return;
}
var inference = getInferenceInfoForType(target);
@@ -44193,6 +44697,7 @@
if (inference.priority === undefined || priority < inference.priority) {
inference.candidates = undefined;
inference.contraCandidates = undefined;
+ inference.topLevel = true;
inference.priority = priority;
}
if (priority === inference.priority) {
@@ -44200,14 +44705,19 @@
// We make contravariant inferences only if we are in a pure contravariant position,
// i.e. only if we have not descended into a bivariant position.
if (contravariant && !bivariant) {
- inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate);
+ if (!ts.contains(inference.contraCandidates, candidate)) {
+ inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
+ inference.inferredType = undefined;
}
- else {
- inference.candidates = ts.appendIfUnique(inference.candidates, candidate);
+ }
+ else if (!ts.contains(inference.candidates, candidate)) {
+ inference.candidates = ts.append(inference.candidates, candidate);
+ inference.inferredType = undefined;
}
}
- if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
+ if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
inference.topLevel = false;
+ inference.inferredType = undefined;
}
}
return;
@@ -44231,6 +44741,9 @@
}
}
}
+ else if (target.flags & 33554432 /* Substitution */) {
+ inferFromTypes(source, target.typeVariable);
+ }
if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) {
// If source and target are references to the same generic type, infer from type arguments
var sourceTypes = source.typeArguments || ts.emptyArray;
@@ -44267,42 +44780,32 @@
else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
inferFromTypes(source.checkType, target.checkType);
inferFromTypes(source.extendsType, target.extendsType);
- inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
- inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
+ inferFromTypes(source.trueType, target.trueType);
+ inferFromTypes(source.falseType, target.falseType);
}
- else if (target.flags & 16777216 /* Conditional */) {
- inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]));
+ else if (target.flags & 16777216 /* Conditional */ && !contravariant) {
+ inferFromTypes(source, target.trueType);
+ inferFromTypes(source, target.falseType);
}
else if (target.flags & 3145728 /* UnionOrIntersection */) {
- var targetTypes = target.types;
- var typeVariableCount = 0;
- var typeVariable = void 0;
- // First infer to each type in union or intersection that isn't a type variable
- for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) {
- var t = targetTypes_3[_d];
+ for (var _d = 0, _e = target.types; _d < _e.length; _d++) {
+ var t = _e[_d];
+ var savePriority = priority;
+ // Inferences directly to naked type variables are given lower priority as they are
+ // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
+ // we want to infer string for T, not Promise<string> | string.
if (getInferenceInfoForType(t)) {
- typeVariable = t;
- typeVariableCount++;
+ priority |= 1 /* NakedTypeVariable */;
}
- else {
inferFromTypes(source, t);
- }
- }
- // Next, if target containings a single naked type variable, make a secondary inference to that type
- // variable. This gives meaningful results for union types in co-variant positions and intersection
- // types in contra-variant positions (such as callback parameters).
- if (typeVariableCount === 1) {
- var savePriority = priority;
- priority |= 1 /* NakedTypeVariable */;
- inferFromTypes(source, typeVariable);
priority = savePriority;
}
}
else if (source.flags & 1048576 /* Union */) {
// Source is a union or intersection type, infer from each constituent type
var sourceTypes = source.types;
- for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) {
- var sourceType = sourceTypes_3[_e];
+ for (var _f = 0, sourceTypes_3 = sourceTypes; _f < sourceTypes_3.length; _f++) {
+ var sourceType = sourceTypes_3[_f];
inferFromTypes(sourceType, target);
}
}
@@ -44318,7 +44821,7 @@
// that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
// here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
// (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
- // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just
+ // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
// remove this `allowComplexConstraintInference` flag.
allowComplexConstraintInference = false;
return inferFromTypes(apparentSource, target);
@@ -44380,12 +44883,12 @@
}
return undefined;
}
- function inferFromMappedTypeConstraint(source, target, constraintType) {
+ function inferToMappedType(source, target, constraintType) {
if (constraintType.flags & 1048576 /* Union */) {
var result = false;
for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
var type = _a[_i];
- result = inferFromMappedTypeConstraint(source, target, type) || result;
+ result = inferToMappedType(source, target, type) || result;
}
return result;
}
@@ -44407,12 +44910,22 @@
return true;
}
if (constraintType.flags & 262144 /* TypeParameter */) {
- // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type
- // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X.
+ // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
+ // parameter. First infer from 'keyof S' to K.
var savePriority = priority;
priority |= 4 /* MappedTypeConstraint */;
inferFromTypes(getIndexType(source), constraintType);
priority = savePriority;
+ // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
+ // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
+ // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
+ // Pick<T, K>.
+ var extendedConstraint = getConstraintOfType(constraintType);
+ if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
+ return true;
+ }
+ // If no inferences can be made to K's constraint, infer from a union of the property types
+ // in the source to the template type X.
var valueTypes = ts.compact([
getIndexTypeOfType(source, 0 /* String */),
getIndexTypeOfType(source, 1 /* Number */)
@@ -44431,7 +44944,7 @@
}
if (ts.getObjectFlags(target) & 32 /* Mapped */) {
var constraintType = getConstraintTypeFromMappedType(target);
- if (inferFromMappedTypeConstraint(source, target, constraintType)) {
+ if (inferToMappedType(source, target, constraintType)) {
return;
}
}
@@ -44444,11 +44957,11 @@
}
}
function inferFromProperties(source, target) {
- if (isTupleType(source)) {
+ if (isArrayType(source) || isTupleType(source)) {
if (isTupleType(target)) {
- var sourceLength = getLengthOfTupleType(source);
+ var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
var targetLength = getLengthOfTupleType(target);
- var sourceRestType = getRestTypeOfTupleType(source);
+ var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
var targetRestType = getRestTypeOfTupleType(target);
var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
for (var i = 0; i < fixedLength; i++) {
@@ -44485,7 +44998,7 @@
var sourceLen = sourceSignatures.length;
var targetLen = targetSignatures.length;
var len = sourceLen < targetLen ? sourceLen : targetLen;
- var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */);
+ var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* ContainsAnyFunctionType */);
for (var i = 0; i < len; i++) {
inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters);
}
@@ -44496,17 +45009,10 @@
var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
// Once we descend into a bivariant signature we remain bivariant for all nested inferences
bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */;
- forEachMatchingParameterType(source, target, inferFromContravariantTypes);
+ applyToParameterTypes(source, target, inferFromContravariantTypes);
bivariant = saveBivariant;
}
- var sourceTypePredicate = getTypePredicateOfSignature(source);
- var targetTypePredicate = getTypePredicateOfSignature(target);
- if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) {
- inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type);
- }
- else {
- inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
- }
+ applyToReturnTypes(source, target, inferFromTypes);
}
function inferFromIndexTypes(source, target) {
var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
@@ -44529,8 +45035,8 @@
}
}
function typeIdenticalToSomeType(type, types) {
- for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
- var t = types_10[_i];
+ for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
+ var t = types_11[_i];
if (isTypeIdenticalTo(t, type)) {
return true;
}
@@ -44623,7 +45129,7 @@
if (defaultType) {
// Instantiate the default type. Any forward reference to a type
// parameter should be instantiated to the empty object type.
- inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
}
else {
inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
@@ -44636,7 +45142,7 @@
inference.inferredType = inferredType;
var constraint = getConstraintOfTypeParameter(inference.typeParameter);
if (constraint) {
- var instantiatedConstraint = instantiateType(constraint, context);
+ var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
inference.inferredType = inferredType = instantiatedConstraint;
}
@@ -44661,17 +45167,23 @@
case "console":
return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
case "$":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
case "describe":
case "suite":
case "it":
case "test":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha;
case "process":
case "require":
case "Buffer":
case "module":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
case "Map":
case "Set":
case "Promise":
@@ -44807,9 +45319,8 @@
}
return false;
}
- function hasNarrowableDeclaredType(expr) {
- var type = getDeclaredTypeOfReference(expr);
- return !!(type && type.flags & 1048576 /* Union */);
+ function isSyntheticThisPropertyAccess(expr) {
+ return ts.isAccessExpression(expr) && expr.expression.kind === 100 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */);
}
function findDiscriminantProperties(sourceProperties, target) {
var result;
@@ -44886,8 +45397,8 @@
}
function getTypeFactsOfTypes(types) {
var result = 0 /* None */;
- for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
- var t = types_11[_i];
+ for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
+ var t = types_12[_i];
result |= getTypeFacts(t);
}
return result;
@@ -45167,7 +45678,7 @@
if (type.flags & 1048576 /* Union */) {
var types = type.types;
var filtered = ts.filter(types, f);
- return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly);
+ return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
}
return f(type) ? type : neverType;
}
@@ -45181,8 +45692,8 @@
var types = type.types;
var mappedType;
var mappedTypes;
- for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
- var current = types_12[_i];
+ for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
+ var current = types_13[_i];
var t = mapper(current);
if (t) {
if (!mappedType) {
@@ -45264,8 +45775,8 @@
}
function isEvolvingArrayTypeList(types) {
var hasEvolvingArrayType = false;
- for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
- var t = types_13[_i];
+ for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
+ var t = types_14[_i];
if (!(t.flags & 131072 /* Never */)) {
if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
return false;
@@ -45763,6 +46274,15 @@
assumeTrue = !assumeTrue;
}
var valueType = getTypeOfExpression(value);
+ if ((type.flags & 2 /* Unknown */) && (operator === 35 /* EqualsEqualsEqualsToken */) && assumeTrue) {
+ if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
+ return valueType;
+ }
+ if (valueType.flags & 524288 /* Object */) {
+ return nonPrimitiveType;
+ }
+ return type;
+ }
if (valueType.flags & 98304 /* Nullable */) {
if (!strictNullChecks) {
return type;
@@ -45792,9 +46312,9 @@
// We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands
var target = getReferenceCandidate(typeOfExpr.expression);
if (!isMatchingReference(reference, target)) {
- // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a
- // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type.
- if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) {
+ // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the
+ // narrowed type of 'y' to its declared type.
+ if (containsMatchingReference(reference, target)) {
return declaredType;
}
return type;
@@ -45835,13 +46355,37 @@
}
}
function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
- // We only narrow if all case expressions specify values with unit types
+ // We only narrow if all case expressions specify
+ // values with unit types, except for the case where
+ // `type` is unknown. In this instance we map object
+ // types to the nonPrimitive type and narrow with that.
var switchTypes = getSwitchClauseTypes(switchStatement);
if (!switchTypes.length) {
return type;
}
var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
+ if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
+ var groundClauseTypes = void 0;
+ for (var i = 0; i < clauseTypes.length; i += 1) {
+ var t = clauseTypes[i];
+ if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
+ if (groundClauseTypes !== undefined) {
+ groundClauseTypes.push(t);
+ }
+ }
+ else if (t.flags & 524288 /* Object */) {
+ if (groundClauseTypes === undefined) {
+ groundClauseTypes = clauseTypes.slice(0, i);
+ }
+ groundClauseTypes.push(nonPrimitiveType);
+ }
+ else {
+ return type;
+ }
+ }
+ return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
+ }
var discriminantType = getUnionType(clauseTypes);
var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
@@ -45942,9 +46486,14 @@
function narrowTypeByInstanceof(type, expr, assumeTrue) {
var left = getReferenceCandidate(expr.left);
if (!isMatchingReference(reference, left)) {
- // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an
- // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type.
- if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) {
+ // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the
+ // narrowed type of 'y' to its declared type. We do this because preceding 'x.y'
+ // references might reference a different 'y' property. However, we make an exception
+ // for property accesses where x is a synthetic 'this' expression, indicating that we
+ // were called from isPropertyInitializedInConstructor. Without this exception,
+ // initializations of 'this' properties that occur before a 'this instanceof XXX'
+ // check would not be considered.
+ if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) {
return declaredType;
}
return type;
@@ -46011,7 +46560,7 @@
return type;
}
if (ts.isIdentifierTypePredicate(predicate)) {
- var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)];
+ var predicateArgument = callExpression.arguments[predicate.parameterIndex];
if (predicateArgument) {
if (isMatchingReference(reference, predicateArgument)) {
return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
@@ -46088,7 +46637,7 @@
return ts.findAncestor(node.parent, function (node) {
return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
node.kind === 245 /* ModuleBlock */ ||
- node.kind === 279 /* SourceFile */ ||
+ node.kind === 284 /* SourceFile */ ||
node.kind === 154 /* PropertyDeclaration */;
});
}
@@ -46209,7 +46758,7 @@
// to the constructor in the initializer, we will need to substitute that
// binding with an alias as the class name is not in scope.
var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
- while (container.kind !== 279 /* SourceFile */) {
+ while (container.kind !== 284 /* SourceFile */) {
if (container.parent === declaration) {
if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
@@ -46315,6 +46864,7 @@
function checkNestedBlockScopedBinding(node, symbol) {
if (languageVersion >= 2 /* ES2015 */ ||
(symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
+ ts.isSourceFile(symbol.valueDeclaration) ||
symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) {
return;
}
@@ -46502,22 +47052,27 @@
if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
captureLexicalThis(node, container);
}
- var type = tryGetThisTypeAt(node, container);
- if (!type && noImplicitThis) {
+ var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
+ if (noImplicitThis) {
+ var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
+ if (type === globalThisType_1 && capturedByArrowFunction) {
+ error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
+ }
+ else if (!type) {
// With noImplicitThis, functions may not reference 'this' if it has type 'any'
- var diag = error(node, capturedByArrowFunction && container.kind === 279 /* SourceFile */ ?
- ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any :
- ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
+ var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
if (!ts.isSourceFile(container)) {
var outsideThis = tryGetThisTypeAt(container);
- if (outsideThis) {
- addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ if (outsideThis && outsideThis !== globalThisType_1) {
+ ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ }
}
}
}
return type || anyType;
}
- function tryGetThisTypeAt(node, container) {
+ function tryGetThisTypeAt(node, includeGlobalThis, container) {
+ if (includeGlobalThis === void 0) { includeGlobalThis = true; }
if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
var isInJS = ts.isInJSFile(node);
if (ts.isFunctionLike(container) &&
@@ -46562,6 +47117,16 @@
return getFlowTypeOfReference(node, type);
}
}
+ if (ts.isSourceFile(container)) {
+ // look up in the source file's locals or exports
+ if (container.commonJsModuleIndicator) {
+ var fileSymbol = getSymbolOfNode(container);
+ return fileSymbol && getTypeOfSymbol(fileSymbol);
+ }
+ else if (includeGlobalThis) {
+ return getTypeOfSymbol(globalThisSymbol);
+ }
+ }
}
function getClassNameFromPrototypeMethod(container) {
// Check if it's the RHS of a x.prototype.y = function [name]() { .... }
@@ -46617,7 +47182,7 @@
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 294 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -46631,7 +47196,7 @@
}
}
function isInConstructorArgumentInitializer(node, constructorDecl) {
- return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; });
+ return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 151 /* Parameter */ && n.parent === constructorDecl; });
}
function checkSuperExpression(node) {
var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node;
@@ -46856,7 +47421,7 @@
while (type) {
var thisType = getThisTypeFromContextualType(type);
if (thisType) {
- return instantiateType(thisType, getContextualMapper(containingLiteral));
+ return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
}
if (literal.parent.kind !== 275 /* PropertyAssignment */) {
break;
@@ -47151,7 +47716,15 @@
}
function getTypeOfPropertyOfContextualType(type, name) {
return mapType(type, function (t) {
- if (t.flags & 3670016 /* StructuredType */) {
+ if (isGenericMappedType(t)) {
+ var constraint = getConstraintTypeFromMappedType(t);
+ var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
+ var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
+ if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
+ return substituteIndexedMappedType(t, propertyNameType);
+ }
+ }
+ else if (t.flags & 3670016 /* StructuredType */) {
var prop = getPropertyOfType(t, name);
if (prop) {
return getTypeOfSymbol(prop);
@@ -47287,18 +47860,46 @@
// Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
// be "pushed" onto a node using the contextualType property.
function getApparentTypeOfContextualType(node) {
- var contextualType = getContextualType(node);
- contextualType = contextualType && mapType(contextualType, getApparentType);
- if (contextualType && contextualType.flags & 1048576 /* Union */) {
+ var contextualType = instantiateContextualType(getContextualType(node), node);
+ if (contextualType) {
+ var apparentType = mapType(contextualType, getApparentType, /*noReductions*/ true);
+ if (apparentType.flags & 1048576 /* Union */) {
if (ts.isObjectLiteralExpression(node)) {
- return discriminateContextualTypeByObjectMembers(node, contextualType);
+ return discriminateContextualTypeByObjectMembers(node, apparentType);
}
else if (ts.isJsxAttributes(node)) {
- return discriminateContextualTypeByJSXAttributes(node, contextualType);
+ return discriminateContextualTypeByJSXAttributes(node, apparentType);
+ }
+ }
+ return apparentType;
+ }
+ }
+ // If the given contextual type contains instantiable types and if a mapper representing
+ // return type inferences is available, instantiate those types using that mapper.
+ function instantiateContextualType(contextualType, node) {
+ if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
+ var inferenceContext = getInferenceContext(node);
+ if (inferenceContext && inferenceContext.returnMapper) {
+ return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
}
}
return contextualType;
}
+ // This function is similar to instantiateType, except that (a) it only instantiates types that
+ // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
+ // no reductions on instantiated union types.
+ function instantiateInstantiableTypes(type, mapper) {
+ if (type.flags & 63176704 /* Instantiable */) {
+ return instantiateType(type, mapper);
+ }
+ if (type.flags & 1048576 /* Union */) {
+ return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
+ }
+ if (type.flags & 2097152 /* Intersection */) {
+ return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
+ }
+ return type;
+ }
/**
* Woah! Do you really want to use this function?
*
@@ -47344,7 +47945,7 @@
return getContextualTypeForArgument(parent, node);
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- return getTypeFromTypeNode(parent.type);
+ return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
case 204 /* BinaryExpression */:
return getContextualTypeForBinaryOperand(node);
case 275 /* PropertyAssignment */:
@@ -47378,9 +47979,9 @@
}
return undefined;
}
- function getContextualMapper(node) {
- var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; });
- return ancestor ? ancestor.contextualMapper : identityMapper;
+ function getInferenceContext(node) {
+ var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
+ return ancestor && ancestor.inferenceContext;
}
function getContextualJsxElementAttributesType(node) {
if (ts.isJsxOpeningElement(node) && node.parent.contextualType) {
@@ -47561,8 +48162,8 @@
}
var signatureList;
var types = type.types;
- for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
- var current = types_14[_i];
+ for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
+ var current = types_15[_i];
var signature = getContextualCallSignature(current, node);
if (signature) {
if (!signatureList) {
@@ -47580,12 +48181,7 @@
}
}
// Result is union of signatures collected (return type is union of return types of this signature set)
- var result;
- if (signatureList) {
- result = cloneSignature(signatureList[0]);
- result.unionSignatures = signatureList;
- }
- return result;
+ return signatureList && createUnionSignature(signatureList[0], signatureList);
}
function checkSpreadExpression(node, checkMode) {
if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
@@ -47605,6 +48201,7 @@
var elementTypes = [];
var inDestructuringPattern = ts.isAssignmentTarget(node);
var contextualType = getApparentTypeOfContextualType(node);
+ var inConstContext = isConstContext(node);
for (var index = 0; index < elementCount; index++) {
var e = elements[index];
if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) {
@@ -47647,21 +48244,24 @@
type.pattern = node;
return type;
}
- else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) {
+ else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, inConstContext)) {
return tupleResult;
}
else if (forceTuple) {
return createTupleType(elementTypes, minLength, hasRestElement);
}
}
- return getArrayLiteralType(elementTypes, 2 /* Subtype */);
+ return createArrayType(elementTypes.length ?
+ getUnionType(elementTypes, 2 /* Subtype */) :
+ strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext);
}
- function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) {
+ function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
if (elementCount === void 0) { elementCount = elementTypes.length; }
+ if (readonly === void 0) { readonly = false; }
// Infer a tuple type when the contextual type is or contains a tuple-like type
- if (contextualType && forEachType(contextualType, isTupleLikeType)) {
+ if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
var minLength = elementCount - (hasRestElement ? 1 : 0);
- var pattern = contextualType.pattern;
+ var pattern = contextualType && contextualType.pattern;
// If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting
// tuple type with the corresponding binding or assignment element types to make the lengths equal.
if (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) {
@@ -47679,14 +48279,8 @@
}
}
}
- return createTupleType(elementTypes, minLength, hasRestElement);
- }
+ return createTupleType(elementTypes, minLength, hasRestElement, readonly);
}
- function getArrayLiteralType(elementTypes, unionReduction) {
- if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
- return createArrayType(elementTypes.length ?
- getUnionType(elementTypes, unionReduction) :
- strictNullChecks ? implicitNeverType : undefinedWideningType);
}
function isNumericName(name) {
switch (name.kind) {
@@ -47750,15 +48344,15 @@
}
return links.resolvedType;
}
- function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) {
+ function getObjectLiteralIndexInfo(node, offset, properties, kind) {
var propTypes = [];
for (var i = 0; i < properties.length; i++) {
- if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) {
+ if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
propTypes.push(getTypeOfSymbol(properties[i]));
}
}
var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
- return createIndexInfo(unionType, /*isReadonly*/ false);
+ return createIndexInfo(unionType, isConstContext(node));
}
function getImmediateAliasedSymbol(symbol) {
ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
@@ -47778,14 +48372,15 @@
var propertiesTable;
var propertiesArray = [];
var spread = emptyObjectType;
- var propagatedFlags = 0;
var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */);
+ var inConstContext = isConstContext(node);
+ var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
var enumTag = ts.getJSDocEnumTag(node);
var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
- var typeFlags = 0;
+ var objectFlags = freshObjectLiteralFlag;
var patternWithComputedProperties = false;
var hasComputedStringProperty = false;
var hasComputedNumberProperty = false;
@@ -47812,11 +48407,11 @@
checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
}
}
- typeFlags |= type.flags;
+ objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */;
var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
var prop = nameType ?
- createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), 2048 /* Late */) :
- createSymbol(4 /* Property */ | member.flags, member.escapedName);
+ createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 2048 /* Late */) :
+ createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
if (nameType) {
prop.nameType = nameType;
}
@@ -47854,19 +48449,18 @@
checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
}
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
propertiesArray = [];
propertiesTable = ts.createSymbolTable();
hasComputedStringProperty = false;
hasComputedNumberProperty = false;
- typeFlags = 0;
}
var type = checkExpression(memberDecl.expression);
if (!isValidSpreadType(type)) {
error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
return errorType;
}
- spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
offset = i + 1;
continue;
}
@@ -47913,17 +48507,16 @@
}
if (spread !== emptyObjectType) {
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
}
return spread;
}
return createObjectLiteralType();
function createObjectLiteralType() {
- var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined;
- var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined;
+ var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
+ var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
- result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */;
- result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag;
+ result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
if (isJSObjectLiteral) {
result.objectFlags |= 16384 /* JSLiteral */;
}
@@ -47933,7 +48526,6 @@
if (inDestructuringPattern) {
result.pattern = node;
}
- propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */;
return result;
}
}
@@ -48009,7 +48601,6 @@
var hasSpreadAnyType = false;
var typeToIntersect;
var explicitlySpecifyChildrenAttribute = false;
- var typeFlags = 0;
var objectFlags = 4096 /* JsxAttributes */;
var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
@@ -48017,7 +48608,7 @@
var member = attributeDecl.symbol;
if (ts.isJsxAttribute(attributeDecl)) {
var exprType = checkJsxAttribute(attributeDecl, checkMode);
- typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */;
+ objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */;
var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
attributeSymbol.declarations = member.declarations;
attributeSymbol.parent = member.parent;
@@ -48034,7 +48625,7 @@
else {
ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */);
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
attributesTable = ts.createSymbolTable();
}
var exprType = checkExpressionCached(attributeDecl.expression, checkMode);
@@ -48042,7 +48633,7 @@
hasSpreadAnyType = true;
}
if (isValidSpreadType(exprType)) {
- spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
}
else {
typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
@@ -48051,7 +48642,7 @@
}
if (!hasSpreadAnyType) {
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
}
}
// Handle children attribute
@@ -48079,7 +48670,7 @@
childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
var childPropMap = ts.createSymbolTable();
childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
- spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
}
}
if (hasSpreadAnyType) {
@@ -48097,8 +48688,7 @@
function createJsxAttributesType() {
objectFlags |= freshObjectLiteralFlag;
var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
- result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags;
- result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags;
+ result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
return result;
}
}
@@ -48109,7 +48699,7 @@
// In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
// because then type of children property will have constituent of string type.
if (child.kind === 11 /* JsxText */) {
- if (!child.containsOnlyWhiteSpaces) {
+ if (!child.containsOnlyTriviaWhiteSpaces) {
childrenTypes.push(stringType);
}
}
@@ -48180,7 +48770,7 @@
var namespaceName = getJsxNamespace(location);
var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
if (resolvedNamespace) {
- var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */);
+ var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
if (candidate) {
if (links) {
links.jsxNamespace = candidate;
@@ -48385,7 +48975,7 @@
// Mark local symbol as referenced here because it might not have been marked
// if jsx emit was not react as there wont be error being emitted
reactSym.isReferenced = 67108863 /* All */;
- // If react symbol is alias, mark it as refereced
+ // If react symbol is alias, mark it as referenced
if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) {
markAliasSymbolAsReferenced(reactSym);
}
@@ -48623,6 +49213,15 @@
if (isJSLiteralType(leftType)) {
return anyType;
}
+ if (leftType.symbol === globalThisSymbol) {
+ if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
+ error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
+ }
+ else if (noImplicitAny) {
+ error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
+ }
+ return anyType;
+ }
if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType);
}
@@ -48701,7 +49300,7 @@
diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
}
if (diagnosticMessage) {
- addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
function isInPropertyInitializer(node) {
@@ -48710,7 +49309,19 @@
case 154 /* PropertyDeclaration */:
return true;
case 275 /* PropertyAssignment */:
- // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`.
+ case 156 /* MethodDeclaration */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
+ case 277 /* SpreadAssignment */:
+ case 149 /* ComputedPropertyName */:
+ case 216 /* TemplateSpan */:
+ case 270 /* JsxExpression */:
+ case 267 /* JsxAttribute */:
+ case 268 /* JsxAttributes */:
+ case 269 /* JsxSpreadAttribute */:
+ case 262 /* JsxOpeningElement */:
+ case 211 /* ExpressionWithTypeArguments */:
+ case 273 /* HeritageClause */:
return false;
default:
return ts.isExpressionNode(node) ? false : "quit";
@@ -48778,7 +49389,7 @@
}
var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
if (relatedInfo) {
- addRelatedInfo(resultDiagnostic, relatedInfo);
+ ts.addRelatedInfo(resultDiagnostic, relatedInfo);
}
diagnostics.add(resultDiagnostic);
}
@@ -49177,38 +49788,34 @@
return undefined;
}
// Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
- function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
+ function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
- var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
- forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
+ // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
+ // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
+ // for T but leave it possible to later infer '[any]' back to A.
+ var restType = getEffectiveRestType(contextualSignature);
+ var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
+ var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
+ applyToParameterTypes(sourceSignature, signature, function (source, target) {
// Type parameters from outer context referenced by source type are fixed by instantiation of the source type
inferTypes(context.inferences, source, target);
});
- if (!contextualMapper) {
- inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
+ if (!inferenceContext) {
+ applyToReturnTypes(contextualSignature, signature, function (source, target) {
+ inferTypes(context.inferences, source, target, 8 /* ReturnType */);
+ });
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
}
- function inferJsxTypeArguments(node, signature, excludeArgument, context) {
+ function inferJsxTypeArguments(node, signature, checkMode, context) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context);
+ var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
- function inferTypeArguments(node, signature, args, excludeArgument, context) {
- // Clear out all the inference results from the last time inferTypeArguments was called on this context
- for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
- var inference = _a[_i];
- // As an optimization, we don't have to clear (and later recompute) inferred types
- // for type parameters that have already been fixed on the previous call to inferTypeArguments.
- // It would be just as correct to reset all of them. But then we'd be repeating the same work
- // for the type parameters that were fixed, namely the work done by getInferredType.
- if (!inference.isFixed) {
- inference.inferredType = undefined;
- }
- }
+ function inferTypeArguments(node, signature, args, checkMode, context) {
if (ts.isJsxOpeningLikeElement(node)) {
- return inferJsxTypeArguments(node, signature, excludeArgument, context);
+ return inferJsxTypeArguments(node, signature, checkMode, context);
}
// If a contextual type is available, infer from that type to the return type of the call expression. For
// example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
@@ -49217,10 +49824,11 @@
if (node.kind !== 152 /* Decorator */) {
var contextualType = getContextualType(node);
if (contextualType) {
- // We clone the contextual mapper to avoid disturbing a resolution in progress for an
+ // 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 instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node)));
+ var outerMapper = getMapperFromContext(cloneInferenceContext(getInferenceContext(node), 1 /* 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
@@ -49235,6 +49843,9 @@
var inferenceTargetType = getReturnTypeOfSignature(signature);
// Inferences made from return types have lower priority than all other inferences.
inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */);
+ // Create a type mapper for instantiating generic contextual types using the inferences made
+ // from the return type.
+ context.returnMapper = getMapperFromContext(cloneInferredPartOfContext(context));
}
}
var thisType = getThisTypeOfSignature(signature);
@@ -49249,10 +49860,7 @@
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
- // context sensitive function expressions as wildcards
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- var argType = checkExpressionWithContextualType(arg, paramType, mapper);
+ var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
inferTypes(context.inferences, argType, paramType);
}
}
@@ -49276,7 +49884,7 @@
// and the argument are ...x forms.
return arg.kind === 215 /* SyntheticExpression */ ?
createArrayType(arg.type) :
- getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
}
}
var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
@@ -49284,7 +49892,7 @@
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
if (spreadIndex < 0 && isSpreadArgument(args[i])) {
spreadIndex = i - index;
}
@@ -49334,19 +49942,18 @@
* @param node a JSX opening-like element we are trying to figure its call signature
* @param signature a candidate signature we are trying whether it is a call signature
* @param relation a relationship to check parameter and argument type
- * @param excludeArgument
*/
- function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
// Stateless function components can have maximum of three arguments: "props", "context", and "updater".
// However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
// can be specified by users through attributes property.
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
}
- function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
if (ts.isJsxOpeningLikeElement(node)) {
- return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors);
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
}
var thisType = getThisTypeOfSignature(signature);
if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) {
@@ -49368,11 +49975,11 @@
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
+ var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
+ // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
// we obtain the regular type of any object literal arguments because we may not have inferred complete
// parameter types yet and therefore excess property checks may yield false positives (see #17041).
- var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType;
+ var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
return false;
}
@@ -49529,25 +50136,41 @@
if (argCount <= max && hasSpreadArgument) {
argCount--;
}
+ var spanArray;
var related;
+ var error = hasRestParameter || hasSpreadArgument ? hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
+ hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
+ ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1;
if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
if (paramDecl) {
related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined);
}
}
- if (hasRestParameter || hasSpreadArgument) {
- var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
- hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
- ts.Diagnostics.Expected_0_arguments_but_got_1_or_more;
- var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1;
- }
if (min < argCount && argCount < max) {
return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
}
- var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic, related) : diagnostic;
+ if (!hasSpreadArgument && argCount < min) {
+ var diagnostic_1 = ts.createDiagnosticForNode(node, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
+ }
+ if (hasRestParameter || hasSpreadArgument) {
+ spanArray = ts.createNodeArray(args);
+ if (hasSpreadArgument && argCount) {
+ var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
+ spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : max));
+ }
+ }
+ else {
+ spanArray = ts.createNodeArray(args.slice(max));
+ }
+ spanArray.pos = ts.first(spanArray).pos;
+ spanArray.end = ts.last(spanArray).end;
+ if (spanArray.end === spanArray.pos) {
+ spanArray.end++;
+ }
+ var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
}
function getTypeArgumentArityError(node, signatures, typeArguments) {
var argCount = typeArguments.length;
@@ -49577,7 +50200,7 @@
}
return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
}
- function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
+ function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */;
var isDecorator = node.kind === 152 /* Decorator */;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
@@ -49613,7 +50236,7 @@
// For a decorator, no arguments are susceptible to contextual typing due to the fact
// decorators are applied to a declaration by the emitter, and not to an expression.
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
+ var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
// The following variables are captured and modified by calls to chooseOverload.
// If overload resolution or type argument inference fails, we want to report the
// best error possible. The best error is one which says that an argument was not
@@ -49641,7 +50264,7 @@
var result;
// If we are in signature help, a trailing comma indicates that we intend to provide another argument,
// so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
- var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
// Section 4.12.1:
// if the candidate list contains one or more signatures for which the type of each argument
// expression is a subtype of each corresponding parameter type, the return type of the first
@@ -49667,12 +50290,7 @@
// skip the checkApplicableSignature check.
if (reportErrors) {
if (candidateForArgumentError) {
- // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...]
- // The importance of excludeArgument is to prevent us from typing function expression parameters
- // in arguments too early. If possible, we'd like to only type them once we know the correct
- // overload. However, this matters for the case where the call is correct. When the call is
- // an error, we don't need to exclude any arguments, although it would cause no harm to do so.
- checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true);
+ checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0 /* Normal */, /*reportErrors*/ true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
@@ -49704,7 +50322,7 @@
if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
return undefined;
}
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false)) {
candidateForArgumentError = candidate;
return undefined;
}
@@ -49728,9 +50346,10 @@
}
else {
inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
+ argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
}
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && 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)) {
@@ -49741,21 +50360,21 @@
else {
checkCandidate = candidate;
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
continue;
}
- if (excludeArgument) {
+ if (argCheckMode) {
// If one or more context sensitive arguments were excluded, we start including
// them now (and keeping do so for any subsequent candidates) and perform a second
// round of type inference and applicability checking for this particular candidate.
- excludeArgument = undefined;
+ argCheckMode = 0 /* Normal */;
if (inferenceContext) {
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && 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)) {
@@ -49763,7 +50382,7 @@
continue;
}
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
@@ -49777,20 +50396,6 @@
return undefined;
}
}
- function getExcludeArgument(args) {
- var excludeArgument;
- // We do not need to call `getEffectiveArgumentCount` here as it only
- // applies when calculating the number of arguments for a decorator.
- for (var i = 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- }
- }
- return excludeArgument;
- }
// No signature was applicable. We have already reported the errors for the invalid signature.
// If this is a type resolution session, e.g. Language Service, try to get better information than anySignature.
function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
@@ -49879,7 +50484,7 @@
}
function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
@@ -49898,7 +50503,7 @@
}
return maxParamsIndex;
}
- function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveCallExpression(node, candidatesOutArray, checkMode) {
if (node.expression.kind === 98 /* SuperKeyword */) {
var superType = checkSuperExpression(node.expression);
if (isTypeAny(superType)) {
@@ -49914,7 +50519,7 @@
var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
if (baseTypeNode) {
var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
- return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
}
}
return resolveUntypedCall(node);
@@ -49964,12 +50569,31 @@
}
return resolveErrorCall(node);
}
+ // When a call to a generic function is an argument to an outer call to a generic function for which
+ // inference is in process, we have a choice to make. If the inner call relies on inferences made from
+ // its contextual type to its return type, deferring the inner call processing allows the best possible
+ // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
+ // the inner call, the inner call should be processed early. There's no sure way to know which choice is
+ // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
+ // If no type arguments are specified in the inner call and at least one call signature is generic and
+ // 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 silentNeverType (a type that is assignable to anything and
+ // from which we never make inferences).
+ if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
+ skippedGenericFunction(node, checkMode);
+ return resolvingSignature;
+ }
// If the function is explicitly marked with `@class`, then it must be constructed.
if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
+ }
+ function isGenericFunctionReturningFunction(signature) {
+ return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
}
/**
* TS 1.0 spec: 4.12
@@ -49981,7 +50605,7 @@
return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
!numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
}
- function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveNewExpression(node, candidatesOutArray, checkMode) {
if (node.arguments && languageVersion < 1 /* ES5 */) {
var spreadIndex = getSpreadArgumentIndex(node.arguments);
if (spreadIndex >= 0) {
@@ -50029,7 +50653,7 @@
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
- return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
}
// If expressionType's apparent type is an object type with no construct signatures but
// one or more call signatures, the expression is processed as a function call. A compile-time
@@ -50037,7 +50661,7 @@
// operation is Any. It is an error to have a Void this type.
var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
if (callSignatures.length) {
- var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
if (!noImplicitAny) {
if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
@@ -50059,13 +50683,12 @@
var firstBase = baseTypes[0];
if (firstBase.flags & 2097152 /* Intersection */) {
var types = firstBase.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
var i = 0;
for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
var intersectionMember = _a[_i];
- i++;
// We want to ignore mixin ctors
- if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) {
+ if (!mixinFlags[i]) {
if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
if (intersectionMember.symbol === target) {
return true;
@@ -50075,6 +50698,7 @@
}
}
}
+ i++;
}
return false;
}
@@ -50118,7 +50742,7 @@
var diagnostic = error(node, (kind === 0 /* Call */ ?
ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures :
ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType));
- invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
+ invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
}
function invocationErrorRecovery(apparentType, kind, diagnostic) {
if (!apparentType.symbol) {
@@ -50131,10 +50755,10 @@
var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
if (!sigs || !sigs.length)
return;
- addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead));
}
}
- function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
var tagType = checkExpression(node.tag);
var apparentType = getApparentType(tagType);
if (apparentType === errorType) {
@@ -50150,7 +50774,7 @@
invocationError(node, apparentType, 0 /* Call */);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
}
/**
* Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
@@ -50175,7 +50799,7 @@
/**
* Resolves a decorator as if it were a call expression.
*/
- function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveDecorator(node, candidatesOutArray, checkMode) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
if (apparentType === errorType) {
@@ -50200,7 +50824,7 @@
invocationErrorRecovery(apparentType, 0 /* Call */, diag);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
}
function createSignatureForJSXIntrinsic(node, result) {
var namespace = getJsxNamespaceAt(node);
@@ -50219,11 +50843,11 @@
/*hasRestparameter*/ false,
/*hasLiteralTypes*/ false);
}
- function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
var fakeSignature = createSignatureForJSXIntrinsic(node, result);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes);
+ checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
return fakeSignature;
}
var exprTypes = checkExpression(node.tagName);
@@ -50240,7 +50864,7 @@
error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
return resolveErrorCall(node);
}
- return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, signatures, candidatesOutArray, checkMode);
}
/**
* Sometimes, we have a decorator that could accept zero arguments,
@@ -50254,19 +50878,19 @@
signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
- function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveSignature(node, candidatesOutArray, checkMode) {
switch (node.kind) {
case 191 /* CallExpression */:
- return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveCallExpression(node, candidatesOutArray, checkMode);
case 192 /* NewExpression */:
- return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveNewExpression(node, candidatesOutArray, checkMode);
case 193 /* TaggedTemplateExpression */:
- return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
case 152 /* Decorator */:
- return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
+ return resolveDecorator(node, candidatesOutArray, checkMode);
case 262 /* JsxOpeningElement */:
case 261 /* JsxSelfClosingElement */:
- return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp);
+ return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
}
throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
@@ -50277,8 +50901,7 @@
* the function will fill it up with appropriate candidate signatures
* @return a signature of the call-like expression or undefined if one can't be found
*/
- function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) {
- if (isForSignatureHelp === void 0) { isForSignatureHelp = false; }
+ function getResolvedSignature(node, candidatesOutArray, checkMode) {
var links = getNodeLinks(node);
// If getResolvedSignature has already been called, we will have cached the resolvedSignature.
// However, it is possible that either candidatesOutArray was not passed in the first time,
@@ -50289,11 +50912,15 @@
return cached;
}
links.resolvedSignature = resolvingSignature;
- var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
+ var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
+ // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
+ // resolution should be deferred.
+ if (result !== resolvingSignature) {
// If signature resolution originated in control flow type analysis (for example to compute the
// assigned type in a flow assignment) we don't cache the result as it may be based on temporary
// types from the control flow analysis.
links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ }
return result;
}
/**
@@ -50369,10 +50996,15 @@
* @param node The call/new expression to be checked.
* @returns On success, the expression's signature's return type. On failure, anyType.
*/
- function checkCallExpression(node) {
+ function checkCallExpression(node, checkMode) {
if (!checkGrammarTypeArguments(node, node.typeArguments))
checkGrammarArguments(node.arguments);
- var signature = getResolvedSignature(node);
+ 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 anyFunctionType.
+ return silentNeverType;
+ }
if (node.expression.kind === 98 /* SuperKeyword */) {
return voidType;
}
@@ -50472,7 +51104,7 @@
var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
anonymousSymbol.type = defaultContainingObject;
- synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject;
+ synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
}
else {
synthType.syntheticType = type;
@@ -50519,9 +51151,37 @@
function checkAssertion(node) {
return checkAssertionWorker(node, node.type, node.expression);
}
+ function isValidConstAssertionArgument(node) {
+ switch (node.kind) {
+ case 10 /* StringLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 102 /* TrueKeyword */:
+ case 87 /* FalseKeyword */:
+ case 187 /* ArrayLiteralExpression */:
+ case 188 /* ObjectLiteralExpression */:
+ return true;
+ case 195 /* ParenthesizedExpression */:
+ return isValidConstAssertionArgument(node.expression);
+ case 202 /* PrefixUnaryExpression */:
+ var op = node.operator;
+ var arg = node.operand;
+ return op === 39 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
+ op === 38 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
+ }
+ return false;
+ }
function checkAssertionWorker(errNode, type, expression, checkMode) {
- var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode)));
+ var exprType = checkExpression(expression, checkMode);
+ if (ts.isConstTypeReference(type)) {
+ if (!isValidConstAssertionArgument(expression)) {
+ error(expression, ts.Diagnostics.A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal);
+ }
+ return getRegularTypeOfLiteralType(exprType);
+ }
checkSourceElement(type);
+ exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
var targetType = getTypeFromTypeNode(type);
if (produceDiagnostics && targetType !== errorType) {
var widenedType = getWidenedType(exprType);
@@ -50560,7 +51220,7 @@
}
}
function checkImportMetaProperty(node) {
- if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
+ if (languageVersion < 7 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options);
}
var file = ts.getSourceFileOfNode(node);
@@ -50588,7 +51248,7 @@
if (isTupleType(restType)) {
var associatedNames = restType.target.associatedNames;
var index = pos - paramCount;
- return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
+ return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
}
return restParameter.escapedName;
}
@@ -50601,33 +51261,37 @@
return getTypeOfParameter(signature.parameters[pos]);
}
if (signature.hasRestParameter) {
+ // We want to return the value undefined for an out of bounds parameter position,
+ // so we need to check bounds here before calling getIndexedAccessType (which
+ // otherwise would return the type 'undefined').
var restType = getTypeOfSymbol(signature.parameters[paramCount]);
- if (isTupleType(restType)) {
- if (pos - paramCount < getLengthOfTupleType(restType)) {
- return restType.typeArguments[pos - paramCount];
- }
- return getRestTypeOfTupleType(restType);
+ var index = pos - paramCount;
+ if (!isTupleType(restType) || restType.target.hasRestElement || index < (restType.typeArguments || ts.emptyArray).length) {
+ return getIndexedAccessType(restType, getLiteralType(index));
}
- return getIndexTypeOfType(restType, 1 /* Number */);
}
return undefined;
}
function getRestTypeAtPosition(source, pos) {
var paramCount = getParameterCount(source);
var restType = getEffectiveRestType(source);
- if (restType && pos === paramCount - 1) {
+ var nonRestCount = paramCount - (restType ? 1 : 0);
+ if (restType && pos === nonRestCount) {
return restType;
}
- var start = restType ? Math.min(pos, paramCount - 1) : pos;
var types = [];
var names = [];
- for (var i = start; i < paramCount; i++) {
+ for (var i = pos; i < nonRestCount; i++) {
types.push(getTypeAtPosition(source, i));
names.push(getParameterNameAtPosition(source, i));
}
+ if (restType) {
+ types.push(getIndexedAccessType(restType, numberType));
+ names.push(getParameterNameAtPosition(source, nonRestCount));
+ }
var minArgumentCount = getMinArgumentCount(source);
- var minLength = minArgumentCount < start ? 0 : minArgumentCount - start;
- return createTupleType(types, minLength, !!restType, names);
+ var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
+ return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
}
function getParameterCount(signature) {
var length = signature.parameters.length;
@@ -50675,17 +51339,28 @@
function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
}
- function inferFromAnnotatedParameters(signature, context, mapper) {
+ function inferFromAnnotatedParameters(signature, context, inferenceContext) {
var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
for (var i = 0; i < len; i++) {
var declaration = signature.parameters[i].valueDeclaration;
if (declaration.type) {
var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
if (typeNode) {
- inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
+ inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
}
}
}
+ var restType = getEffectiveRestType(context);
+ if (restType && restType.flags & 262144 /* 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) {
signature.typeParameters = context.typeParameters;
@@ -50786,7 +51461,7 @@
var functionFlags = ts.getFunctionFlags(func);
var type;
if (func.body.kind !== 218 /* Block */) {
- type = checkExpressionCached(func.body, checkMode);
+ type = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -50964,7 +51639,7 @@
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, checkMode);
+ var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51057,7 +51732,7 @@
ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
checkNodeDeferred(node);
// The identityMapper object is used to indicate that function expressions are wildcards
- if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) {
+ if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
// Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) {
var links_1 = getNodeLinks(node);
@@ -51067,7 +51742,7 @@
var returnType = getReturnTypeFromBody(node, checkMode);
var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
- returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */;
+ returnOnlyType.objectFlags |= 524288 /* ContainsAnyFunctionType */;
return links_1.contextFreeType = returnOnlyType;
}
return anyFunctionType;
@@ -51093,12 +51768,12 @@
if (contextualSignature) {
var signature = getSignaturesOfType(type, 0 /* Call */)[0];
if (isContextSensitive(node)) {
- var contextualMapper = getContextualMapper(node);
- if (checkMode === 2 /* Inferential */) {
- inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
+ var inferenceContext = getInferenceContext(node);
+ if (checkMode && checkMode & 2 /* Inferential */) {
+ inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
}
- var instantiatedContextualSignature = contextualMapper === identityMapper ?
- contextualSignature : instantiateSignature(contextualSignature, contextualMapper);
+ var instantiatedContextualSignature = inferenceContext ?
+ instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
assignContextualParameterTypes(signature, instantiatedContextualSignature);
}
if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
@@ -51364,13 +52039,13 @@
// Return true if type might be of the given kind. A union or intersection type might be of a given
// kind if at least one constituent type is of the given kind.
function maybeTypeOfKind(type, kind) {
- if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) {
+ if (type.flags & kind & ~131072 /* GenericMappedType */ || kind & 131072 /* GenericMappedType */ && isGenericMappedType(type)) {
return true;
}
if (type.flags & 3145728 /* UnionOrIntersection */) {
var types = type.types;
- for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
- var t = types_15[_i];
+ for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
+ var t = types_16[_i];
if (maybeTypeOfKind(t, kind)) {
return true;
}
@@ -51474,7 +52149,7 @@
return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
}
else if (property.kind === 277 /* SpreadAssignment */) {
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(property, 4 /* Rest */);
}
var nonRestNames = [];
@@ -51969,7 +52644,7 @@
// Async generator functions prior to ESNext require the __await, __asyncDelegator,
// and __asyncValues helpers
if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ &&
- languageVersion < 6 /* ESNext */) {
+ languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */);
}
// Generator functions prior to ES2015 require the __values helper
@@ -52016,23 +52691,26 @@
}
return node;
}
- function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
+ function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
var context = getContextNode(node);
var saveContextualType = context.contextualType;
- var saveContextualMapper = context.contextualMapper;
+ var saveInferenceContext = context.inferenceContext;
context.contextualType = contextualType;
- context.contextualMapper = contextualMapper;
- var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ :
- contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */;
- var result = checkExpression(node, checkMode);
+ context.inferenceContext = inferenceContext;
+ var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
+ // 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 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
+ getRegularTypeOfLiteralType(type) : type;
context.contextualType = saveContextualType;
- context.contextualMapper = saveContextualMapper;
+ context.inferenceContext = saveInferenceContext;
return result;
}
function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- if (checkMode) {
+ if (checkMode && checkMode !== 0 /* Normal */) {
return checkExpression(node, checkMode);
}
// When computing a type that we're going to cache, we need to ignore any ongoing control flow
@@ -52095,13 +52773,17 @@
}
return false;
}
- function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
- if (arguments.length === 2) {
- contextualType = getContextualType(node);
+ function isConstContext(node) {
+ var parent = node.parent;
+ return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
+ (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
+ (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
}
+ function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
var type = checkExpression(node, checkMode, forceTuple);
- return isTypeAssertion(node) ? type :
- getWidenedLiteralLikeTypeForContextualType(type, contextualType);
+ return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
+ isTypeAssertion(node) ? type :
+ getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
}
function checkPropertyAssignment(node, checkMode) {
// Do not use hasDynamicName here, because that returns false for well known symbols.
@@ -52125,20 +52807,129 @@
return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
+ if (checkMode & 8 /* SkipGenericFunctions */) {
+ skippedGenericFunction(node, checkMode);
+ return anyFunctionType;
+ }
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
+ var context = getInferenceContext(node);
+ // We have an expression that is an argument of a generic function for which we are performing
+ // type argument inference. The expression is of a function type with a single generic call
+ // signature and a contextual function type with a single non-generic call signature. Now check
+ // if the outer function returns a function type with a single non-generic call signature and
+ // if some of the outer function type parameters have no inferences so far. If so, we can
+ // potentially add inferred type parameters to the outer function return type.
+ var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
+ if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
+ // Instantiate the signature with its own type parameters as type arguments, possibly
+ // renaming the type parameters to ensure they have unique names.
+ var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
+ // Infer from the parameters of the instantiated signature to the parameters of the
+ // contextual signature starting with an empty set of inference candidates.
+ var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
+ applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target, /*priority*/ 0, /*contravariant*/ true);
+ });
+ if (ts.some(inferences_2, hasInferenceCandidates)) {
+ // We have inference candidates, indicating that one or more type parameters are referenced
+ // in the parameter types of the contextual signature. Now also infer from the return type.
+ applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target);
+ });
+ // If the type parameters for which we produced candidates do not have any inferences yet,
+ // we adopt the new inference candidates and add the type parameters of the expression type
+ // to the set of inferred type parameters for the outer function return type.
+ if (!hasOverlappingInferences(context.inferences, inferences_2)) {
+ mergeInferences(context.inferences, inferences_2);
+ context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
+ return getOrCreateTypeFromSignature(instantiatedSignature);
+ }
+ }
+ }
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
}
}
}
}
return type;
}
+ function skippedGenericFunction(node, checkMode) {
+ if (checkMode & 2 /* Inferential */) {
+ // We have skipped a generic function during inferential typing. Obtain the inference context and
+ // indicate this has occurred such that we know a second pass of inference is be needed.
+ var context = getInferenceContext(node);
+ context.flags |= 4 /* SkippedGenericFunction */;
+ }
+ }
+ function hasInferenceCandidates(info) {
+ return !!(info.candidates || info.contraCandidates);
+ }
+ function hasOverlappingInferences(a, b) {
+ for (var i = 0; i < a.length; i++) {
+ if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function mergeInferences(target, source) {
+ for (var i = 0; i < target.length; i++) {
+ if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
+ target[i] = source[i];
+ }
+ }
+ }
+ function getUniqueTypeParameters(context, typeParameters) {
+ var result = [];
+ var oldTypeParameters;
+ var newTypeParameters;
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var tp = typeParameters_2[_i];
+ var name = tp.symbol.escapedName;
+ if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
+ var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
+ var symbol = createSymbol(262144 /* TypeParameter */, newName);
+ var newTypeParameter = createTypeParameter(symbol);
+ newTypeParameter.target = tp;
+ oldTypeParameters = ts.append(oldTypeParameters, tp);
+ newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
+ result.push(newTypeParameter);
+ }
+ else {
+ result.push(tp);
+ }
+ }
+ if (newTypeParameters) {
+ var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
+ for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
+ var tp = newTypeParameters_1[_a];
+ tp.mapper = mapper;
+ }
+ }
+ return result;
+ }
+ function hasTypeParameterByName(typeParameters, name) {
+ return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
+ }
+ function getUniqueTypeParameterName(typeParameters, baseName) {
+ var len = baseName.length;
+ while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
+ len--;
+ var s = baseName.slice(0, len);
+ for (var index = 1; true; index++) {
+ var augmentedName = (s + index);
+ if (!hasTypeParameterByName(typeParameters, augmentedName)) {
+ return augmentedName;
+ }
+ }
+ }
/**
* Returns the type of an expression. Unlike checkExpression, this function is simply concerned
* with computing the type and may not fully check all contained sub-expressions for errors.
@@ -52156,7 +52947,7 @@
return getReturnTypeOfSignature(signature);
}
}
- else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) {
+ else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
return getTypeFromTypeNode(expr.type);
}
// Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions
@@ -52178,27 +52969,22 @@
}
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */);
+ var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
node.contextualType = saveContextualType;
return type;
}
- // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When
- // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the
- // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in
- // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function
- // object, it serves as an indicator that all contained function and arrow expressions should be considered to
- // have the wildcard function type; this form of type check is used during overload resolution to exclude
- // contextually typed function and arrow expressions in the initial phase.
function checkExpression(node, checkMode, forceTuple) {
- var type;
- if (node.kind === 148 /* QualifiedName */) {
- type = checkQualifiedName(node);
- }
- else {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
- type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
- }
+ var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
if (isConstEnumObjectType(type)) {
+ checkConstEnumAccess(node, type);
+ }
+ currentNode = saveCurrentNode;
+ return type;
+ }
+ function checkConstEnumAccess(node, type) {
// enum object type for const enums are only permitted in:
// - 'left' in property access
// - 'object' in indexed access
@@ -52210,8 +52996,13 @@
if (!ok) {
error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query);
}
+ if (compilerOptions.isolatedModules) {
+ ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
+ var constEnumDeclaration = type.symbol.valueDeclaration;
+ if (constEnumDeclaration.flags & 4194304 /* Ambient */) {
+ error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
+ }
}
- return type;
}
function checkParenthesizedExpression(node, checkMode) {
var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
@@ -52253,6 +53044,8 @@
return checkObjectLiteral(node, checkMode);
case 189 /* PropertyAccessExpression */:
return checkPropertyAccessExpression(node);
+ case 148 /* QualifiedName */:
+ return checkQualifiedName(node);
case 190 /* ElementAccessExpression */:
return checkIndexedAccess(node);
case 191 /* CallExpression */:
@@ -52261,7 +53054,7 @@
}
/* falls through */
case 192 /* NewExpression */:
- return checkCallExpression(node);
+ return checkCallExpression(node, checkMode);
case 193 /* TaggedTemplateExpression */:
return checkTaggedTemplateExpression(node);
case 195 /* ParenthesizedExpression */:
@@ -52326,9 +53119,8 @@
checkSourceElement(node.constraint);
checkSourceElement(node.default);
var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
- if (!hasNonCircularBaseConstraint(typeParameter)) {
- error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter));
- }
+ // Resolve base constraint to reveal circularity errors
+ getBaseConstraintOfType(typeParameter);
if (!hasNonCircularTypeParameterDefault(typeParameter)) {
error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
}
@@ -52370,7 +53162,7 @@
}
// Only check rest parameter type if it's not a binding pattern. Since binding patterns are
// not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
- if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) {
+ if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) {
error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
}
}
@@ -52381,7 +53173,8 @@
error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
return;
}
- var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent));
+ var signature = getSignatureFromDeclaration(parent);
+ var typePredicate = getTypePredicateOfSignature(signature);
if (!typePredicate) {
return;
}
@@ -52392,12 +53185,12 @@
}
else {
if (typePredicate.parameterIndex >= 0) {
- if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) {
+ if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) {
error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
}
else {
var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
- checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type,
+ checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type,
/*headMessage*/ undefined, leadingError);
}
}
@@ -52464,7 +53257,7 @@
var functionFlags = ts.getFunctionFlags(node);
if (!(functionFlags & 4 /* Invalid */)) {
// Async generators prior to ESNext require the __await and __asyncGenerator helpers
- if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) {
+ if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */);
}
// Async functions prior to ES2017 require the __awaiter helper
@@ -52521,7 +53314,7 @@
checkAsyncFunctionReturnType(node, returnTypeNode);
}
}
- if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) {
+ if (node.kind !== 162 /* IndexSignature */ && node.kind !== 294 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -53200,7 +53993,7 @@
for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) {
var signature = signatures_6[_a];
if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
- error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation);
+ ts.addRelatedInfo(error(signature.declaration, ts.Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), ts.createDiagnosticForNode(bodyDeclaration, ts.Diagnostics.The_implementation_signature_is_declared_here));
break;
}
}
@@ -53277,8 +54070,8 @@
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
// A jsdoc typedef and callback are, by definition, type aliases
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return 2 /* ExportType */;
case 244 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -53287,7 +54080,7 @@
case 240 /* ClassDeclaration */:
case 243 /* EnumDeclaration */:
return 2 /* ExportType */ | 1 /* ExportValue */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
case 254 /* ExportAssignment */:
// Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
@@ -53652,8 +54445,8 @@
}
function getEntityNameForDecoratorMetadataFromTypeList(types) {
var commonEntityName;
- for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
- var typeNode = types_16[_i];
+ for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
+ var typeNode = types_17[_i];
while (typeNode.kind === 177 /* ParenthesizedType */) {
typeNode = typeNode.type; // Skip parens if need be
}
@@ -53928,7 +54721,7 @@
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
case 246 /* CaseBlock */:
@@ -54021,8 +54814,8 @@
return;
var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
var seenParentsWithEveryUnused = new ts.NodeSet();
- for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
- var typeParameter = typeParameters_2[_i];
+ for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
+ var typeParameter = typeParameters_3[_i];
if (!isTypeParameterUnused(typeParameter))
continue;
var name = ts.idText(typeParameter.name);
@@ -54275,7 +55068,7 @@
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
// If the declaration happens to be in external module, report error that require and exports are reserved keywords
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -54290,7 +55083,7 @@
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
+ if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
// If the declaration happens to be in external module, report error that Promise is a reserved identifier.
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -54347,7 +55140,7 @@
(container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) ||
container.kind === 245 /* ModuleBlock */ ||
container.kind === 244 /* ModuleDeclaration */ ||
- container.kind === 279 /* SourceFile */);
+ container.kind === 284 /* SourceFile */);
// here we know that function scoped variable is shadowed by block scoped one
// if they are defined in the same scope - binder has already reported redeclaration error
// otherwise if variable has an initializer - show error that initialization will fail
@@ -54447,7 +55240,7 @@
}
}
if (node.kind === 186 /* BindingElement */) {
- if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) {
+ if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 4 /* Rest */);
}
// check computed properties inside property names of binding elements
@@ -54458,7 +55251,7 @@
var parent = node.parent.parent;
var parentType = getTypeForBindingElementParent(parent);
var name = node.propertyName || node.name;
- if (!ts.isBindingPattern(name) && parentType) {
+ if (parentType && !ts.isBindingPattern(name)) {
var exprType = getLiteralTypeFromPropertyName(name);
if (isTypeUsableAsPropertyName(exprType)) {
var nameText = getPropertyNameFromType(exprType);
@@ -54645,7 +55438,7 @@
checkGrammarForInOrForOfStatement(node);
if (node.awaitModifier) {
var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
- if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) {
+ if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 7 /* ESNext */) {
// for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */);
}
@@ -55090,7 +55883,7 @@
// If the function has a return type, but promisedType is
// undefined, an error will be reported in checkAsyncFunctionReturnType
// so we don't need to report one here.
- checkTypeAssignableTo(awaitedType, promisedType, node);
+ checkTypeAssignableToAndOptionallyElaborate(awaitedType, promisedType, node, node.expression);
}
}
else {
@@ -55961,10 +56754,6 @@
checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
checkExportsOnMergedDeclarations(node);
computeEnumMemberValues(node);
- var enumIsConst = ts.isEnumConst(node);
- if (compilerOptions.isolatedModules && enumIsConst && node.flags & 4194304 /* Ambient */) {
- error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided);
- }
// Spec 2014 - Section 9.3:
// It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
// and when an enum type has multiple declarations, only one declaration is permitted to omit a value
@@ -55975,9 +56764,10 @@
var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
if (node === firstDeclaration) {
if (enumSymbol.declarations.length > 1) {
+ var enumIsConst_1 = ts.isEnumConst(node);
// check that const is placed\omitted on all enum declarations
ts.forEach(enumSymbol.declarations, function (decl) {
- if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) {
+ if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
}
});
@@ -56058,8 +56848,8 @@
var symbol = getSymbolOfNode(node);
// The following checks only apply on a non-ambient instantiated module declaration.
if (symbol.flags & 512 /* ValueModule */
- && symbol.declarations.length > 1
&& !inAmbientContext
+ && symbol.declarations.length > 1
&& isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
if (firstNonAmbientClassOrFunc) {
@@ -56200,7 +56990,7 @@
return false;
}
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule) {
error(moduleName, node.kind === 255 /* ExportDeclaration */ ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
@@ -56331,7 +57121,7 @@
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ &&
!node.moduleSpecifier && node.flags & 4194304 /* Ambient */;
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -56348,7 +57138,7 @@
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
+ var isInAppropriateContext = node.parent.kind === 284 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -56377,7 +57167,7 @@
// If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
return;
}
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
if (node.isExportEquals) {
error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
@@ -56470,9 +57260,14 @@
!!declaration.body;
}
function checkSourceElement(node) {
- if (!node) {
- return;
+ if (node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
+ checkSourceElementWorker(node);
+ currentNode = saveCurrentNode;
}
+ }
+ function checkSourceElementWorker(node) {
if (ts.isInJSFile(node)) {
ts.forEach(node.jsDoc, function (_a) {
var tags = _a.tags;
@@ -56542,32 +57337,32 @@
return checkInferType(node);
case 183 /* ImportType */:
return checkImportType(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return checkJSDocTypeAliasTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return checkJSDocTemplateTag(node);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return checkJSDocTypeTag(node);
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
checkJSDocFunctionType(node);
// falls through
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
- case 292 /* JSDocTypeLiteral */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
+ case 297 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 283 /* JSDocTypeExpression */:
+ case 288 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 180 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -56721,10 +57516,13 @@
}
function checkDeferredNodes(context) {
var links = getNodeLinks(context);
- if (!links.deferredNodes) {
- return;
+ if (links.deferredNodes) {
+ links.deferredNodes.forEach(checkDeferredNode);
}
- links.deferredNodes.forEach(function (node) {
+ }
+ function checkDeferredNode(node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
switch (node.kind) {
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
@@ -56746,7 +57544,7 @@
checkJsxElementDeferred(node);
break;
}
- });
+ currentNode = saveCurrentNode;
}
function checkSourceFile(node) {
ts.performance.mark("beforeCheck");
@@ -56821,7 +57619,7 @@
throwIfNonDiagnosticsProducing();
if (sourceFile) {
// Some global diagnostics are deferred until they are needed and
- // may not be reported in the firt call to getGlobalDiagnostics.
+ // may not be reported in the first call to getGlobalDiagnostics.
// We should catch these changes and report them.
var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
@@ -56872,7 +57670,7 @@
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
// falls through
@@ -57091,10 +57889,10 @@
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 299 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 304 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 308 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -57136,7 +57934,7 @@
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
var parent = node.parent;
@@ -57478,7 +58276,7 @@
}
var parentSymbol_1 = getParentOfSymbol(symbol);
if (parentSymbol_1) {
- if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) {
+ if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 284 /* SourceFile */) {
var symbolFile = parentSymbol_1.valueDeclaration;
var referenceFile = ts.getSourceFileOfNode(node);
// If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
@@ -57505,7 +58303,7 @@
return undefined;
}
function isSymbolOfDeclarationWithCollidingName(symbol) {
- if (symbol.flags & 418 /* BlockScoped */) {
+ if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
var links = getSymbolLinks(symbol);
if (links.isDeclarationWithCollidingName === undefined) {
var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
@@ -57593,7 +58391,7 @@
}
function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 284 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
// parent is not source file or it is not reference to internal module
return false;
}
@@ -58022,7 +58820,7 @@
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 284 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
return false;
}
// check that at least one declaration of top level symbol originates from type declaration file
@@ -58055,7 +58853,7 @@
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */);
+ return ts.getDeclarationOfKind(moduleSymbol, 284 /* SourceFile */);
}
function initializeTypeChecker() {
// Bind all source files and propagate errors
@@ -58169,8 +58967,8 @@
else {
// Otherwise issue top-level error since the files appear very identical in terms of what they contain
var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
- diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file)));
- diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file)));
+ diagnostics.add(ts.addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file)));
+ diagnostics.add(ts.addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file)));
}
});
amalgamatedDuplicates = undefined;
@@ -58287,7 +59085,7 @@
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128 /* Abstract */) {
@@ -58310,7 +59108,7 @@
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
else if (node.kind === 151 /* Parameter */) {
@@ -58355,7 +59153,7 @@
flags |= 1 /* Export */;
break;
case 80 /* DefaultKeyword */:
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
}
@@ -58478,7 +59276,7 @@
case 151 /* Parameter */:
return false;
default:
- if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return false;
}
switch (node.kind) {
@@ -58566,10 +59364,10 @@
var nonSimpleParameters = getNonSimpleParameters(node.parameters);
if (ts.length(nonSimpleParameters)) {
ts.forEach(nonSimpleParameters, function (parameter) {
- addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
+ ts.addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
});
var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
- addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
+ ts.addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
return true;
}
}
@@ -59006,6 +59804,11 @@
return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
}
}
+ else if (node.operator === 133 /* ReadonlyKeyword */) {
+ if (node.type.kind !== 169 /* ArrayType */ && node.type.kind !== 170 /* TupleType */) {
+ return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(139 /* SymbolKeyword */));
+ }
+ }
}
function checkGrammarForInvalidDynamicName(node, message) {
if (isNonBindableDynamicName(node)) {
@@ -59396,7 +60199,7 @@
// to prevent noisiness. So use a bit on the block to indicate if
// this has already been reported, and don't report if it has.
//
- if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
var links_2 = getNodeLinks(node.parent);
// Check if the containing block ever report this error
if (!links_2.hasReportedStatementInAmbientContext) {
@@ -59436,7 +60239,7 @@
var literalType = ts.isLiteralTypeNode(node.parent) ||
ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
if (!literalType) {
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) {
return true;
}
@@ -59601,10 +60404,11 @@
return createLiteralFromNode(value);
}
ts.createLiteral = createLiteral;
- function createNumericLiteral(value) {
+ function createNumericLiteral(value, numericLiteralFlags) {
+ if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
var node = createSynthesizedNode(8 /* NumericLiteral */);
node.text = value;
- node.numericLiteralFlags = 0;
+ node.numericLiteralFlags = numericLiteralFlags;
return node;
}
ts.createNumericLiteral = createNumericLiteral;
@@ -61449,14 +62253,14 @@
// JSDoc
/* @internal */
function createJSDocTypeExpression(type) {
- var node = createSynthesizedNode(283 /* JSDocTypeExpression */);
+ var node = createSynthesizedNode(288 /* JSDocTypeExpression */);
node.type = type;
return node;
}
ts.createJSDocTypeExpression = createJSDocTypeExpression;
/* @internal */
function createJSDocTypeTag(typeExpression, comment) {
- var tag = createJSDocTag(302 /* JSDocTypeTag */, "type");
+ var tag = createJSDocTag(307 /* JSDocTypeTag */, "type");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61464,7 +62268,7 @@
ts.createJSDocTypeTag = createJSDocTypeTag;
/* @internal */
function createJSDocReturnTag(typeExpression, comment) {
- var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns");
+ var tag = createJSDocTag(305 /* JSDocReturnTag */, "returns");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61472,7 +62276,7 @@
ts.createJSDocReturnTag = createJSDocReturnTag;
/* @internal */
function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
- var tag = createJSDocTag(299 /* JSDocParameterTag */, "param");
+ var tag = createJSDocTag(304 /* JSDocParameterTag */, "param");
tag.typeExpression = typeExpression;
tag.name = name;
tag.isBracketed = isBracketed;
@@ -61482,7 +62286,7 @@
ts.createJSDocParamTag = createJSDocParamTag;
/* @internal */
function createJSDocComment(comment, tags) {
- var node = createSynthesizedNode(291 /* JSDocComment */);
+ var node = createSynthesizedNode(296 /* JSDocComment */);
node.comment = comment;
node.tags = tags;
return node;
@@ -61563,6 +62367,28 @@
return node;
}
ts.createJsxFragment = createJsxFragment;
+ function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
+ var node = createSynthesizedNode(11 /* JsxText */);
+ node.text = text;
+ node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
+ return node;
+ }
+ ts.createJsxText = createJsxText;
+ function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
+ return node.text !== text
+ || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
+ ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
+ : node;
+ }
+ ts.updateJsxText = updateJsxText;
+ function createJsxOpeningFragment() {
+ return createSynthesizedNode(265 /* JsxOpeningFragment */);
+ }
+ ts.createJsxOpeningFragment = createJsxOpeningFragment;
+ function createJsxJsxClosingFragment() {
+ return createSynthesizedNode(266 /* JsxClosingFragment */);
+ }
+ ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
function updateJsxFragment(node, openingFragment, children, closingFragment) {
return node.openingFragment !== openingFragment
|| node.children !== children
@@ -61741,7 +62567,7 @@
(typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
(libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
(hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
- var updated = createSynthesizedNode(279 /* SourceFile */);
+ var updated = createSynthesizedNode(284 /* SourceFile */);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
@@ -61825,7 +62651,7 @@
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(307 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(312 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -61837,7 +62663,7 @@
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(316 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -61849,7 +62675,7 @@
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(310 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(315 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -61864,7 +62690,7 @@
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(313 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -61880,7 +62706,7 @@
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 309 /* CommaListExpression */) {
+ if (node.kind === 314 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
@@ -61890,7 +62716,7 @@
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(309 /* CommaListExpression */);
+ var node = createSynthesizedNode(314 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -61903,33 +62729,197 @@
ts.updateCommaList = updateCommaList;
function createBundle(sourceFiles, prepends) {
if (prepends === void 0) { prepends = ts.emptyArray; }
- var node = ts.createNode(280 /* Bundle */);
+ var node = ts.createNode(285 /* Bundle */);
node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) {
- var node = ts.createNode(281 /* UnparsedSource */);
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.spreadHelper,
+ ts.restHelper,
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.awaiterHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ function createUnparsedSource() {
+ var node = ts.createNode(286 /* UnparsedSource */);
+ node.prologues = ts.emptyArray;
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var node = createUnparsedSource();
+ var stripInternal;
+ var bundleFileInfo;
if (!ts.isString(textOrInputFiles)) {
ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal;
}
+ ts.Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
return node;
}
ts.createUnparsedSourceFile = createUnparsedSourceFile;
- function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) {
- var node = ts.createNode(282 /* InputFiles */);
+ function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var texts;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue" /* Prologue */:
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node));
+ break;
+ case "emitHelpers" /* EmitHelpers */:
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ node.hasNoDefaultLib = true;
+ break;
+ case "reference" /* Reference */:
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type" /* Type */:
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case "lib" /* Lib */:
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend" /* Prepend */:
+ var prependNode = createUnparsedNode(section, node);
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal" /* Internal */) {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
+ }
+ }
+ prependNode.texts = prependTexts || ts.emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case "internal" /* Internal */:
+ if (stripInternal)
+ break;
+ // falls through
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.prologues = prologues || ts.emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
+ }
+ function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
+ ts.Debug.assert(!!node.oldFileOfCurrentEmit);
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal" /* Internal */:
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+ // Ignore
+ case "prologue" /* Prologue */:
+ case "emitHelpers" /* EmitHelpers */:
+ case "prepend" /* Prepend */:
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.texts = texts || ts.emptyArray;
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+ function mapBundleFileSectionKindToSyntaxKind(kind) {
+ switch (kind) {
+ case "prologue" /* Prologue */: return 279 /* UnparsedPrologue */;
+ case "prepend" /* Prepend */: return 280 /* UnparsedPrepend */;
+ case "internal" /* Internal */: return 282 /* UnparsedInternalText */;
+ case "text" /* Text */: return 281 /* UnparsedText */;
+ case "emitHelpers" /* EmitHelpers */:
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ }
+ function createUnparsedNode(section, parent) {
+ var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ return node;
+ }
+ function createUnparsedSyntheticReference(section, parent) {
+ var node = ts.createNode(283 /* UnparsedSyntheticReference */, section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.createNode(287 /* InputFiles */);
if (!ts.isString(javascriptTextOrReadFileText)) {
var cache_1 = ts.createMap();
var textGetter_1 = function (path) {
@@ -61946,15 +62936,25 @@
var result = textGetter_1(path);
return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
};
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
});
}
else {
@@ -61963,7 +62963,12 @@
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -62101,10 +63106,10 @@
// To avoid holding onto transformation artifacts, we keep track of any
// parse tree node we are annotating. This allows us to clean them up after
// all transformations have completed.
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return node.emitNode = { annotatedNodes: [node] };
}
- var sourceFile = ts.getSourceFileOfNode(node);
+ var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
}
node.emitNode = {};
@@ -62402,7 +63407,7 @@
ts.nullTransformationContext = {
enableEmitNotification: ts.noop,
enableSubstitution: ts.noop,
- endLexicalEnvironment: function () { return undefined; },
+ endLexicalEnvironment: ts.returnUndefined,
getCompilerOptions: ts.notImplemented,
getEmitHost: ts.notImplemented,
getEmitResolver: ts.notImplemented,
@@ -62547,38 +63552,38 @@
return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
}
ts.getHelperName = getHelperName;
- var valuesHelper = {
+ ts.valuesHelper = {
name: "typescript:values",
scoped: false,
text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
};
function createValuesHelper(context, expression, location) {
- context.requestEmitHelper(valuesHelper);
+ context.requestEmitHelper(ts.valuesHelper);
return ts.setTextRange(ts.createCall(getHelperName("__values"),
/*typeArguments*/ undefined, [expression]), location);
}
ts.createValuesHelper = createValuesHelper;
- var readHelper = {
+ ts.readHelper = {
name: "typescript:read",
scoped: false,
text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
};
function createReadHelper(context, iteratorRecord, count, location) {
- context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(ts.readHelper);
return ts.setTextRange(ts.createCall(getHelperName("__read"),
/*typeArguments*/ undefined, count !== undefined
? [iteratorRecord, ts.createLiteral(count)]
: [iteratorRecord]), location);
}
ts.createReadHelper = createReadHelper;
- var spreadHelper = {
+ ts.spreadHelper = {
name: "typescript:spread",
scoped: false,
text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
};
function createSpreadHelper(context, argumentList, location) {
- context.requestEmitHelper(readHelper);
- context.requestEmitHelper(spreadHelper);
+ context.requestEmitHelper(ts.readHelper);
+ context.requestEmitHelper(ts.spreadHelper);
return ts.setTextRange(ts.createCall(getHelperName("__spread"),
/*typeArguments*/ undefined, argumentList), location);
}
@@ -63424,7 +64429,7 @@
case 190 /* ElementAccessExpression */:
case 189 /* PropertyAccessExpression */:
case 213 /* NonNullExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -63440,7 +64445,7 @@
ts.parenthesizeConciseBody = parenthesizeConciseBody;
function isCommaSequence(node) {
return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
- node.kind === 309 /* CommaListExpression */;
+ node.kind === 314 /* CommaListExpression */;
}
ts.isCommaSequence = isCommaSequence;
var OuterExpressionKinds;
@@ -63459,7 +64464,7 @@
case 212 /* AsExpression */:
case 213 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -63496,7 +64501,7 @@
case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -64288,12 +65293,12 @@
case 278 /* EnumMember */:
return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -64349,7 +65354,7 @@
case 220 /* EmptyStatement */:
case 210 /* OmittedExpression */:
case 236 /* DebuggerStatement */:
- case 307 /* NotEmittedStatement */:
+ case 312 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -64726,14 +65731,14 @@
result = reduceNode(node.initializer, cbNode, result);
break;
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -64747,8 +65752,8 @@
return statements;
}
return ts.isNodeArray(statements)
- ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements)
- : ts.addStatementsAfterPrologue(statements, declarations);
+ ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements)
+ : ts.insertStatementsAfterStandardPrologue(statements, declarations);
}
ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
/**
@@ -65014,7 +66019,7 @@
}
exit();
}
- function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) {
+ function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
var _a;
ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
@@ -65024,6 +66029,14 @@
var nameIndexToNewNameIndexMap;
var mappingIterator = decodeMappings(map.mappings);
for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
+ if (end && (raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+ if (start && (raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
// Then reencode all the updated mappings into the overall map
var newSourceIndex = void 0;
var newSourceLine = void 0;
@@ -65052,8 +66065,10 @@
}
}
}
- var newGeneratedLine = raw.generatedLine + generatedLine;
- var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ var newGeneratedLine = rawGeneratedLine + generatedLine;
+ var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
@@ -65536,7 +66551,7 @@
function chainBundle(transformSourceFile) {
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ return node.kind === 284 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
}
function transformBundle(node) {
return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
@@ -66012,8 +67027,8 @@
if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
if (flattenContext.level >= 1 /* ObjectRest */
- && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */))
- && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */))
+ && !(element.transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
+ && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
&& !ts.isComputedPropertyName(propertyName)) {
bindingElements = ts.append(bindingElements, element);
}
@@ -66079,7 +67094,7 @@
if (flattenContext.level >= 1 /* 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 & 262144 /* ContainsObjectRestOrSpread */) {
+ if (element.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
if (flattenContext.hoistTempVariables) {
flattenContext.context.hoistVariableDeclaration(temp);
@@ -66197,7 +67212,7 @@
function makeAssignmentElement(name) {
return name;
}
- var restHelper = {
+ ts.restHelper = {
name: "typescript:rest",
scoped: false,
text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
@@ -66206,7 +67221,7 @@
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
*/
function createRestCall(context, value, elements, computedTempVariables, location) {
- context.requestEmitHelper(restHelper);
+ context.requestEmitHelper(ts.restHelper);
var propertyNames = [];
var computedTempVariableOffset = 0;
for (var i = 0; i < elements.length - 1; i++) {
@@ -66307,14 +67322,14 @@
var pendingExpressions;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
return transformBundle(node);
}
return transformSourceFile(node);
}
function transformBundle(node) {
return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282 /* InputFiles */) {
+ if (prepend.kind === 287 /* InputFiles */) {
return ts.createUnparsedSourceFile(prepend, "js");
}
return prepend;
@@ -66363,7 +67378,7 @@
*/
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 245 /* ModuleBlock */:
case 218 /* Block */:
@@ -66407,14 +67422,9 @@
* @param node The node to visit.
*/
function visitorWorker(node) {
- if (node.transformFlags & 1 /* TypeScript */) {
- // This node is explicitly marked as TypeScript, so we should transform the node.
+ if (node.transformFlags & 1 /* ContainsTypeScript */) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2 /* ContainsTypeScript */) {
- // This node contains TypeScript, so we should visit its children.
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
/**
@@ -66448,7 +67458,7 @@
// As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
// We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
// and will trigger debug failures when debug verbosity is turned up
- if (node.transformFlags & 2 /* ContainsTypeScript */) {
+ if (node.transformFlags & 1 /* ContainsTypeScript */) {
// This node contains TypeScript, so we should visit its children.
return ts.visitEachChild(node, visitor, context);
}
@@ -66490,15 +67500,9 @@
// do not emit ES6 imports and exports since they are illegal inside a namespace
return undefined;
}
- else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
- // This node is explicitly marked as TypeScript, or is exported at the namespace
- // level, so we should transform the node.
+ else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2 /* ContainsTypeScript */) {
- // This node contains TypeScript, so we should visit its children.
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
/**
@@ -66549,7 +67553,7 @@
* @param node The node to visit.
*/
function visitTypeScript(node) {
- if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) {
+ if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
// TypeScript ambient declarations are elided, but some comments may be preserved.
// See the implementation of `getLeadingComments` in comments.ts for more details.
return ts.createNotEmittedStatement(node);
@@ -66616,7 +67620,7 @@
// See the implementation of `getLeadingComments` in comments.ts for more details.
return ts.createNotEmittedStatement(node);
case 240 /* ClassDeclaration */:
- // This is a class declaration with TypeScript syntax extensions.
+ // This may be a class declaration with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
@@ -66627,7 +67631,7 @@
// - method overload signatures
return visitClassDeclaration(node);
case 209 /* ClassExpression */:
- // This is a class expression with TypeScript syntax extensions.
+ // This may be a class expression with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
@@ -66638,7 +67642,7 @@
// - method overload signatures
return visitClassExpression(node);
case 273 /* HeritageClause */:
- // This is a heritage clause with TypeScript syntax extensions.
+ // This may be a heritage clause with TypeScript syntax extensions.
//
// TypeScript heritage clause extensions include:
// - `implements` clause
@@ -66666,7 +67670,7 @@
// TypeScript arrow functions can have modifiers and type annotations.
return visitArrowFunction(node);
case 151 /* Parameter */:
- // This is a parameter declaration with TypeScript syntax extensions.
+ // This may be a parameter declaration with TypeScript syntax extensions.
//
// TypeScript parameter declaration syntax extensions include:
// - decorators
@@ -66707,7 +67711,8 @@
// TypeScript namespace or external module import.
return visitImportEqualsDeclaration(node);
default:
- return ts.Debug.failBadSyntaxKind(node);
+ // node contains some other TypeScript syntax
+ return ts.visitEachChild(node, visitor, context);
}
}
function visitSourceFile(node) {
@@ -66756,18 +67761,19 @@
facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
return facts;
}
- /**
- * Transforms a class declaration with TypeScript syntax into compatible ES6.
- *
- * This function will only be called when one of the following conditions are met:
- * - The class has decorators.
- * - The class has property declarations with initializers.
- * - The class contains a constructor that contains parameters with accessibility modifiers.
- * - The class is an export in a TypeScript namespace.
- *
- * @param node The node to transform.
- */
+ function hasTypeScriptClassSyntax(node) {
+ return !!(node.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */);
+ }
+ function isClassLikeDeclarationWithTypeScriptSyntax(node) {
+ return ts.some(node.decorators)
+ || ts.some(node.typeParameters)
+ || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
+ || ts.some(node.members, hasTypeScriptClassSyntax);
+ }
function visitClassDeclaration(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
@@ -66820,7 +67826,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
var iife = ts.createImmediatelyInvokedArrowFunction(statements);
ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
var varStatement = ts.createVariableStatement(
@@ -66997,16 +68003,10 @@
ts.setCommentRange(statement, node);
return statement;
}
- /**
- * Transforms a class expression with TypeScript syntax into compatible ES6.
- *
- * This function will only be called when one of the following conditions are met:
- * - The class has property declarations with initializers.
- * - The class contains a constructor that contains parameters with accessibility modifiers.
- *
- * @param node The node to transform.
- */
function visitClassExpression(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
@@ -67070,7 +68070,7 @@
var constructor = ts.getFirstConstructorWithBody(node);
var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty);
var hasParameterPropertyAssignments = constructor &&
- constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ &&
+ constructor.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */ &&
ts.forEach(constructor.parameters, isParameterWithPropertyAssignment);
// If the class does not contain nodes that require a synthesized constructor,
// accept the current constructor if it exists.
@@ -67361,11 +68361,14 @@
var decorators;
if (node) {
var parameters = node.parameters;
- for (var i = 0; i < parameters.length; i++) {
- var parameter = parameters[i];
+ 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(parameters.length);
+ decorators = new Array(numParameters);
}
decorators[i] = parameter.decorators;
}
@@ -67865,8 +68868,12 @@
return serializeTypeList(node.types);
case 175 /* ConditionalType */:
return serializeTypeList([node.trueType, node.falseType]);
- case 167 /* TypeQuery */:
case 179 /* TypeOperator */:
+ if (node.operator === 133 /* ReadonlyKeyword */) {
+ return serializeTypeNode(node.type);
+ }
+ break;
+ case 167 /* TypeQuery */:
case 180 /* IndexedAccessType */:
case 181 /* MappedType */:
case 168 /* TypeLiteral */:
@@ -67884,8 +68891,8 @@
// Note when updating logic here also update getEntityNameForDecoratorMetadata
// so that aliases can be marked as referenced
var serializedUnion;
- for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
- var typeNode = types_17[_i];
+ for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
+ var typeNode = types_18[_i];
while (typeNode.kind === 177 /* ParenthesizedType */) {
typeNode = typeNode.type; // Skip parens if need be
}
@@ -68027,7 +69034,7 @@
* available.
*/
function getGlobalBigIntNameWithFallback() {
- return languageVersion < 6 /* ESNext */
+ return languageVersion < 7 /* ESNext */
? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
: ts.createIdentifier("BigInt");
}
@@ -68111,12 +69118,12 @@
* @param node The HeritageClause to transform.
*/
function visitHeritageClause(node) {
- if (node.token === 86 /* ExtendsKeyword */) {
- var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1);
- return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node);
- }
+ if (node.token === 109 /* ImplementsKeyword */) {
+ // implements clauses are elided
return undefined;
}
+ return ts.visitEachChild(node, visitor, context);
+ }
/**
* Transforms an ExpressionWithTypeArguments with TypeScript syntax.
*
@@ -68151,16 +69158,6 @@
}
return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context));
}
- /**
- * Visits a method declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is an overload
- * - The node is marked as abstract, public, private, protected, or readonly
- * - The node has a computed property name
- *
- * @param node The method node.
- */
function visitMethodDeclaration(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return undefined;
@@ -68187,15 +69184,6 @@
function shouldEmitAccessorDeclaration(node) {
return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
}
- /**
- * Visits a get accessor declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked as abstract, public, private, or protected
- * - The node has a computed property name
- *
- * @param node The get accessor node.
- */
function visitGetAccessor(node) {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
@@ -68211,15 +69199,6 @@
}
return updated;
}
- /**
- * Visits a set accessor declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked as abstract, public, private, or protected
- * - The node has a computed property name
- *
- * @param node The set accessor node.
- */
function visitSetAccessor(node) {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
@@ -68234,16 +69213,6 @@
}
return updated;
}
- /**
- * Visits a function declaration.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is an overload
- * - The node is exported from a TypeScript namespace
- * - The node has decorators
- *
- * @param node The function node.
- */
function visitFunctionDeclaration(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return ts.createNotEmittedStatement(node);
@@ -68259,14 +69228,6 @@
}
return updated;
}
- /**
- * Visits a function expression node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node has type annotations
- *
- * @param node The function expression node.
- */
function visitFunctionExpression(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return ts.createOmittedExpression();
@@ -68276,51 +69237,31 @@
/*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
return updated;
}
- /**
- * @remarks
- * This function will be called when one of the following conditions are met:
- * - The node has type annotations
- */
function visitArrowFunction(node) {
var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier),
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
/*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
return updated;
}
- /**
- * Visits a parameter declaration node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node has an accessibility modifier.
- * - The node has a questionToken.
- * - The node's kind is ThisKeyword.
- *
- * @param node The parameter declaration node.
- */
function visitParameter(node) {
if (ts.parameterIsThisKeyword(node)) {
return undefined;
}
- var parameter = ts.createParameter(
+ var updated = ts.updateParameter(node,
/*decorators*/ undefined,
/*modifiers*/ undefined, 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.setOriginalNode(parameter, node);
- ts.setTextRange(parameter, ts.moveRangePastModifiers(node));
- ts.setCommentRange(parameter, node);
- ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node));
- ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */);
- return parameter;
+ ts.setCommentRange(updated, node);
+ ts.setTextRange(updated, ts.moveRangePastModifiers(node));
+ ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
+ ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
+ }
+ return updated;
}
- /**
- * Visits a variable statement in a namespace.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is exported from a TypeScript namespace.
- */
function visitVariableStatement(node) {
if (isExportOfNamespace(node)) {
var variables = ts.getInitializedVariables(node.declarationList);
@@ -68349,12 +69290,6 @@
return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName),
/*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
}
- /**
- * Visits a parenthesized expression that contains either a type assertion or an `as`
- * expression.
- *
- * @param node The parenthesized expression node.
- */
function visitParenthesizedExpression(node) {
var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */);
if (ts.isAssertionExpression(innerExpression)) {
@@ -68491,7 +69426,7 @@
var statements = [];
startLexicalEnvironment();
var members = ts.map(node.members, transformEnumMember);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
ts.addRange(statements, members);
currentNamespaceContainerName = savedCurrentNamespaceLocalName;
return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members),
@@ -68590,7 +69525,7 @@
// enums in any other scope are emitted as a `let` declaration.
var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
- ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
+ ], currentLexicalScope.kind === 284 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
ts.setOriginalNode(statement, node);
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
@@ -68738,7 +69673,7 @@
var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
currentNamespaceContainerName = savedCurrentNamespaceContainerName;
currentNamespace = savedCurrentNamespace;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
@@ -69155,7 +70090,7 @@
// If we are nested within a namespace declaration, we may need to qualifiy
// an identifier that is exported from a merged namespace.
var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
- if (container && container.kind !== 279 /* SourceFile */) {
+ if (container && container.kind !== 284 /* SourceFile */) {
var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) ||
(applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */);
if (substitute) {
@@ -69206,39 +70141,39 @@
argumentsArray.push(descriptor);
}
}
- context.requestEmitHelper(decorateHelper);
+ context.requestEmitHelper(ts.decorateHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"),
/*typeArguments*/ undefined, argumentsArray), location);
}
- var decorateHelper = {
+ ts.decorateHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
+ context.requestEmitHelper(ts.metadataHelper);
return ts.createCall(ts.getHelperName("__metadata"),
/*typeArguments*/ undefined, [
ts.createLiteral(metadataKey),
metadataValue
]);
}
- var metadataHelper = {
+ ts.metadataHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
+ context.requestEmitHelper(ts.paramHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__param"),
/*typeArguments*/ undefined, [
ts.createLiteral(parameterOffset),
expression
]), location);
}
- var paramHelper = {
+ ts.paramHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
@@ -69293,7 +70228,7 @@
return visited;
}
function visitor(node) {
- if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) {
+ if ((node.transformFlags & 32 /* ContainsES2017 */) === 0) {
return node;
}
switch (node.kind) {
@@ -69563,22 +70498,26 @@
}
var savedCapturedSuperProperties = capturedSuperProperties;
var savedHasSuperElementAccess = hasSuperElementAccess;
+ if (!isArrowFunction) {
capturedSuperProperties = ts.createUnderscoreEscapedMap();
hasSuperElementAccess = false;
+ }
var result;
if (!isArrowFunction) {
var statements = [];
var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
if (emitSuperHelpers) {
enableSubstitutionForAsyncMethodsWithSuper();
+ if (ts.hasEntries(capturedSuperProperties)) {
var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
+ }
}
var block = ts.createBlock(statements, /*multiLine*/ true);
ts.setTextRange(block, node.body);
@@ -69605,8 +70544,10 @@
}
}
enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
+ if (!isArrowFunction) {
capturedSuperProperties = savedCapturedSuperProperties;
hasSuperElementAccess = savedHasSuperElementAccess;
+ }
return result;
}
function transformAsyncFunctionBodyWorker(body, start) {
@@ -69759,7 +70700,7 @@
/* typeParameters */ undefined,
/* parameters */ [],
/* type */ undefined,
- /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name))));
+ /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
if (hasBinding) {
getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
/* modifiers */ undefined,
@@ -69774,7 +70715,7 @@
/* initializer */ undefined)
],
/* type */ undefined,
- /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v")))));
+ /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
}
accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
});
@@ -69789,14 +70730,14 @@
], 2 /* Const */));
}
ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
- var awaiterHelper = {
+ ts.awaiterHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
};
function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
+ context.requestEmitHelper(ts.awaiterHelper);
var generatorFunc = ts.createFunctionExpression(
/*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */),
/*name*/ undefined,
@@ -69832,7 +70773,7 @@
/** Enables substitutions for async methods with `super` calls. */
ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
})(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
- function transformESNext(context) {
+ function transformES2018(context) {
var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
var resolver = context.getEmitResolver();
var compilerOptions = context.getCompilerOptions();
@@ -69872,7 +70813,7 @@
return node;
}
function visitorWorker(node, noDestructuringValue) {
- if ((node.transformFlags & 8 /* ContainsESNext */) === 0) {
+ if ((node.transformFlags & 16 /* ContainsES2018 */) === 0) {
return node;
}
switch (node.kind) {
@@ -69916,8 +70857,6 @@
return visitExpressionStatement(node);
case 195 /* ParenthesizedExpression */:
return visitParenthesizedExpression(node, noDestructuringValue);
- case 274 /* CatchClause */:
- return visitCatchClause(node);
case 189 /* PropertyAccessExpression */:
if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) {
capturedSuperProperties.set(node.name.escapedText, true);
@@ -69992,7 +70931,7 @@
return objects;
}
function visitObjectLiteralExpression(node) {
- if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.transformFlags & 8192 /* 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({a}, o, {b});
@@ -70012,19 +70951,13 @@
function visitParenthesizedExpression(node, noDestructuringValue) {
return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
}
- function visitCatchClause(node) {
- if (!node.variableDeclaration) {
- return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
- }
- return ts.visitEachChild(node, visitor, context);
- }
/**
* Visits a BinaryExpression that contains a destructuring assignment.
*
* @param node A BinaryExpression node.
*/
function visitBinaryExpression(node, noDestructuringValue) {
- if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
}
else if (node.operatorToken.kind === 27 /* CommaToken */) {
@@ -70039,7 +70972,7 @@
*/
function visitVariableDeclaration(node) {
// 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 & 262144 /* ContainsObjectRestOrSpread */) {
+ if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */);
}
return ts.visitEachChild(node, visitor, context);
@@ -70056,7 +70989,7 @@
* @param node A ForOfStatement.
*/
function visitForOfStatement(node, outermostLabeledStatement) {
- if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.initializer.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
node = transformForOfStatementWithObjectRest(node);
}
if (node.awaitModifier) {
@@ -70153,7 +71086,7 @@
]));
}
function visitParameter(node) {
- if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
// Binding patterns are converted into a generated name and are
// evaluated inside the function body.
return ts.updateParameter(node,
@@ -70266,10 +71199,10 @@
enableSubstitutionForAsyncMethodsWithSuper();
var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
}
statements.push(returnStatement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.updateBlock(node.body, statements);
if (emitSuperHelpers && hasSuperElementAccess) {
if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
@@ -70295,7 +71228,7 @@
var leadingStatements = endLexicalEnvironment();
if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
- ts.addStatementsAfterPrologue(statements, leadingStatements);
+ ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
ts.addRange(statements, block.statements.slice(statementOffset));
return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
}
@@ -70304,7 +71237,7 @@
function appendObjectRestAssignmentsIfNeeded(statements, node) {
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
- if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (parameter.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
var temp = ts.getGeneratedNameForNode(parameter);
var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp,
/*doNotRecordTempVariablesInLine*/ false,
@@ -70435,8 +71368,8 @@
}
}
}
- ts.transformESNext = transformESNext;
- var assignHelper = {
+ ts.transformES2018 = transformES2018;
+ ts.assignHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -70447,28 +71380,28 @@
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined, attributesSegments);
}
- context.requestEmitHelper(assignHelper);
+ context.requestEmitHelper(ts.assignHelper);
return ts.createCall(ts.getHelperName("__assign"),
/*typeArguments*/ undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
- var awaitHelper = {
+ ts.awaitHelper = {
name: "typescript:await",
scoped: false,
text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
};
function createAwaitHelper(context, expression) {
- context.requestEmitHelper(awaitHelper);
+ context.requestEmitHelper(ts.awaitHelper);
return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
- var asyncGeneratorHelper = {
+ ts.asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncGeneratorHelper);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
return ts.createCall(ts.getHelperName("__asyncGenerator"),
@@ -70478,24 +71411,24 @@
generatorFunc
]);
}
- var asyncDelegator = {
+ ts.asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncDelegator);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"),
/*typeArguments*/ undefined, [expression]), location);
}
- var asyncValues = {
+ ts.asyncValues = {
name: "typescript:asyncValues",
scoped: false,
text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
- context.requestEmitHelper(asyncValues);
+ context.requestEmitHelper(ts.asyncValues);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"),
/*typeArguments*/ undefined, [expression]), location);
}
@@ -70503,6 +71436,60 @@
/*@internal*/
var ts;
(function (ts) {
+ function transformES2019(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 8 /* ContainsES2019 */) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ case 274 /* CatchClause */:
+ return visitCatchClause(node);
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ function visitCatchClause(node) {
+ if (!node.variableDeclaration) {
+ return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ ts.transformES2019 = transformES2019;
+})(ts || (ts = {}));
+/*@internal*/
+var ts;
+(function (ts) {
+ function transformESNext(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ }
+ ts.transformESNext = transformESNext;
+})(ts || (ts = {}));
+/*@internal*/
+var ts;
+(function (ts) {
function transformJsx(context) {
var compilerOptions = context.getCompilerOptions();
var currentSourceFile;
@@ -70522,7 +71509,7 @@
return visited;
}
function visitor(node) {
- if (node.transformFlags & 4 /* ContainsJsx */) {
+ if (node.transformFlags & 2 /* ContainsJsx */) {
return visitorWorker(node);
}
else {
@@ -70639,7 +71626,7 @@
}
}
function visitJsxText(node) {
- var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true));
+ var fixed = fixupWhitespaceAndDecodeEntities(node.text);
return fixed === undefined ? undefined : ts.createLiteral(fixed);
}
/**
@@ -71024,7 +72011,7 @@
return ts.visitEachChild(node, visitor, context);
}
function visitor(node) {
- if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) {
+ if ((node.transformFlags & 64 /* ContainsES2016 */) === 0) {
return node;
}
switch (node.kind) {
@@ -71104,30 +72091,6 @@
Jump[Jump["Continue"] = 4] = "Continue";
Jump[Jump["Return"] = 8] = "Return";
})(Jump || (Jump = {}));
- var SuperCaptureResult;
- (function (SuperCaptureResult) {
- /**
- * A capture may have been added for calls to 'super', but
- * the caller should emit subsequent statements normally.
- */
- SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement";
- /**
- * A call to 'super()' got replaced with a capturing statement like:
- *
- * var _this = _super.call(...) || this;
- *
- * Callers should skip the current statement.
- */
- SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture";
- /**
- * A call to 'super()' got replaced with a capturing statement like:
- *
- * return _super.call(...) || this;
- *
- * Callers should skip the current statement and avoid any returns of '_this'.
- */
- SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn";
- })(SuperCaptureResult || (SuperCaptureResult = {}));
// Facts we track as we traverse the tree
var HierarchyFacts;
(function (HierarchyFacts) {
@@ -71148,12 +72111,12 @@
HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement";
HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement";
HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper";
- HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName";
// NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
+ // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
//
// Ancestor masks
//
- HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
+ HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 8191] = "AncestorFactsMask";
// We are always in *some* kind of block scope, but only specific block-scope containers are
// top-level or Blocks.
HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
@@ -71163,16 +72126,16 @@
HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes";
// Functions, methods, and accessors are both new lexical scopes and new block scopes.
HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
- HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
+ HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 8094] = "FunctionExcludes";
HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
- HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
+ HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 8086] = "AsyncFunctionBodyExcludes";
// Arrow functions are lexically scoped to their container, but are new block scopes.
HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
- HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes";
+ HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 8064] = "ArrowFunctionExcludes";
// Constructors are both new lexical scopes and new block scopes. Constructors are also
// always considered non-static members of a class.
HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
- HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
+ HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 8086] = "ConstructorExcludes";
// 'do' and 'while' statements are not block scopes. We track that the subtree is contained
// within an IterationStatement to indicate whether the embedded statement is an
// IterationStatementBlock.
@@ -71190,19 +72153,17 @@
HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes";
HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes";
- // Computed property names track subtree flags differently than their containing members.
- HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes";
- HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes";
//
// Subtree facts
//
- HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
- HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName";
+ HierarchyFacts[HierarchyFacts["NewTarget"] = 8192] = "NewTarget";
+ HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 16384] = "CapturedLexicalThis";
//
// Subtree masks
//
- HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
- HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask";
+ HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -8192] = "SubtreeFactsMask";
+ HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
+ HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 24576] = "FunctionSubtreeExcludes";
})(HierarchyFacts || (HierarchyFacts = {}));
function transformES2015(context) {
var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
@@ -71251,7 +72212,7 @@
*/
function enterSubtree(excludeFacts, includeFacts) {
var ancestorFacts = hierarchyFacts;
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191 /* AncestorFactsMask */;
return ancestorFacts;
}
/**
@@ -71262,7 +72223,7 @@
* @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
*/
function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 /* SubtreeFactsMask */ | ancestorFacts;
}
function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0
@@ -71284,12 +72245,6 @@
return node;
}
}
- function functionBodyVisitor(node) {
- if (shouldVisitNode(node)) {
- return visitBlock(node, /*isFunctionBody*/ true);
- }
- return node;
- }
function callExpressionVisitor(node) {
if (node.kind === 98 /* SuperKeyword */) {
return visitSuperKeyword(/*isExpressionOfCall*/ true);
@@ -71396,18 +72351,19 @@
}
function visitSourceFile(node) {
var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
+ var prologue = [];
var statements = [];
startLexicalEnvironment();
- var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false);
- addCaptureThisForNodeIfNeeded(statements, node);
- statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor);
+ var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
+ statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
if (taggedTemplateStringDeclarations) {
statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureThisForNodeIfNeeded(prologue, node);
exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
- return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
+ return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
}
function visitSwitchStatement(node) {
if (convertedLoopState !== undefined) {
@@ -71447,6 +72403,9 @@
return ts.visitEachChild(node, visitor, context);
}
function visitThisKeyword(node) {
+ if (hierarchyFacts & 2 /* ArrowFunction */) {
+ hierarchyFacts |= 16384 /* CapturedLexicalThis */;
+ }
if (convertedLoopState) {
if (hierarchyFacts & 2 /* ArrowFunction */) {
// if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
@@ -71660,7 +72619,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
ts.setEmitFlags(block, 1536 /* NoComments */);
return block;
@@ -71688,7 +72647,7 @@
function addConstructor(statements, node, extendsClauseElement) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
+ var ancestorFacts = enterSubtree(8086 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
var constructor = ts.getFirstConstructorWithBody(node);
var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
var constructorFunction = ts.createFunctionDeclaration(
@@ -71702,7 +72661,7 @@
ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
}
statements.push(constructorFunction);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
}
/**
@@ -71721,6 +72680,24 @@
return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
|| [];
}
+ function createDefaultConstructorBody(node, isDerivedClass) {
+ // We must be here because the user didn't write a constructor
+ // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
+ // If that's the case we can just immediately return the result of a 'super()' call.
+ var statements = [];
+ resumeLexicalEnvironment();
+ ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
+ if (isDerivedClass) {
+ // return _super !== null && _super.apply(this, arguments) || this;
+ statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
+ }
+ var statementsArray = ts.createNodeArray(statements);
+ ts.setTextRange(statementsArray, node.members);
+ var block = ts.createBlock(statementsArray, /*multiLine*/ true);
+ ts.setTextRange(block, node);
+ ts.setEmitFlags(block, 1536 /* NoComments */);
+ return block;
+ }
/**
* Transforms the body of a constructor declaration of a class.
*
@@ -71731,59 +72708,137 @@
* synthesized `super` call.
*/
function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
+ // determine whether the class is known syntactically to be a derived class (e.g. a
+ // class that extends a value that is not syntactically known to be `null`).
+ var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */;
+ // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
+ // representation:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base { }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // return _super.apply(this, arguments) || this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ if (!constructor)
+ return createDefaultConstructorBody(node, isDerivedClass);
+ // The prologue will contain all leading standard and custom prologue statements added by this transform
+ var prologue = [];
var statements = [];
resumeLexicalEnvironment();
- var statementOffset = -1;
- if (hasSynthesizedSuper) {
// If a super call has already been synthesized,
// we're going to assume that we should just transform everything after that.
// The assumption is that no prior step in the pipeline has added any prologue directives.
- statementOffset = 0;
- }
- else if (constructor) {
- statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false);
- }
- if (constructor) {
+ var statementOffset = 0;
+ if (!hasSynthesizedSuper)
+ statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
addDefaultValueAssignmentsIfNeeded(statements, constructor);
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
- if (!hasSynthesizedSuper) {
- // If no super call has been synthesized, emit custom prologue directives.
+ if (!hasSynthesizedSuper)
statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
+ // If the first statement is a call to `super()`, visit the statement directly
+ var superCallExpression;
+ if (hasSynthesizedSuper) {
+ superCallExpression = createDefaultSuperCallOrThis();
}
- ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!");
+ else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
+ var firstStatement = constructor.body.statements[statementOffset];
+ if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
+ superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
}
- // determine whether the class is known syntactically to be a derived class (e.g. a
- // class that extends a value that is not syntactically known to be `null`).
- var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */;
- var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset);
- // The last statement expression was replaced. Skip it.
- if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) {
- statementOffset++;
}
- if (constructor) {
- if (superCaptureStatus === 1 /* ReplaceSuperCapture */) {
+ if (superCallExpression) {
hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */;
+ statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
}
+ // visit the remaining statements
ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
+ if (isDerivedClass) {
+ if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048 /* ContainsLexicalThis */)) {
+ // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
+ // following representation:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base {
+ // constructor() {
+ // super("foo");
+ // }
+ // }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // return _super.call(this, "foo") || this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
+ var returnStatement = ts.createReturn(superCallExpression);
+ ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
+ ts.setEmitFlags(superCall, 1536 /* NoComments */);
+ statements.push(returnStatement);
}
- // Return `_this` unless we're sure enough that it would be pointless to add a return statement.
- // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return.
- if (isDerivedClass
- && superCaptureStatus !== 2 /* ReplaceWithReturn */
- && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
+ else {
+ // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base {
+ // constructor() {
+ // super("foo");
+ // this.x = 1;
+ // }
+ // }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // var _this = _super.call(this, "foo") || this;
+ // _this.x = 1;
+ // return _this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ // Since the `super()` call was the first statement, we insert the `this` capturing call to
+ // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
+ insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
+ if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
- if (constructor) {
- prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false);
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements),
- /*location*/ constructor ? constructor.body.statements : node.members),
- /*multiLine*/ true);
- ts.setTextRange(block, constructor ? constructor.body : node);
- if (!constructor) {
- ts.setEmitFlags(block, 1536 /* NoComments */);
}
+ else {
+ // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
+ // captured when necessitated by an arrow function capturing the lexical `this`:
+ //
+ // ```
+ // // es2015
+ // class C {}
+ //
+ // // es5
+ // var C = (function () {
+ // function C() {
+ // }
+ // return C;
+ // })();
+ // ```
+ insertCaptureThisForNodeIfNeeded(prologue, constructor);
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)),
+ /*location*/ constructor.body.statements),
+ /*multiLine*/ true);
+ ts.setTextRange(block, constructor.body);
return block;
}
/**
@@ -71813,83 +72868,6 @@
}
return false;
}
- /**
- * Declares a `_this` variable for derived classes and for when arrow functions capture `this`.
- *
- * @returns The new statement offset into the `statements` array.
- */
- function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) {
- // If this isn't a derived class, just capture 'this' for arrow functions if necessary.
- if (!isDerivedClass) {
- if (ctor) {
- addCaptureThisForNodeIfNeeded(statements, ctor);
- }
- return 0 /* NoReplacement */;
- }
- // We must be here because the user didn't write a constructor
- // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
- // If that's the case we can just immediately return the result of a 'super()' call.
- if (!ctor) {
- statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
- return 2 /* ReplaceWithReturn */;
- }
- // The constructor exists, but it and the 'super()' call it contains were generated
- // for something like property initializers.
- // Create a captured '_this' variable and assume it will subsequently be used.
- if (hasSynthesizedSuper) {
- captureThisForNode(statements, ctor, createDefaultSuperCallOrThis());
- enableSubstitutionsForCapturedThis();
- return 1 /* ReplaceSuperCapture */;
- }
- // Most of the time, a 'super' call will be the first real statement in a constructor body.
- // In these cases, we'd like to transform these into a *single* statement instead of a declaration
- // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer,
- // we'd get:
- //
- // var _this;
- // _this = _super.call(...) || this;
- //
- // instead of
- //
- // var _this = _super.call(...) || this;
- //
- // Additionally, if the 'super()' call is the last statement, we should just avoid capturing
- // entirely and immediately return the result like so:
- //
- // return _super.call(...) || this;
- //
- var firstStatement;
- var superCallExpression;
- var ctorStatements = ctor.body.statements;
- if (statementOffset < ctorStatements.length) {
- firstStatement = ctorStatements[statementOffset];
- if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) {
- superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
- }
- }
- // Return the result if we have an immediate super() call on the last statement,
- // but only if the constructor itself doesn't use 'this' elsewhere.
- if (superCallExpression
- && statementOffset === ctorStatements.length - 1
- && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) {
- var returnStatement = ts.createReturn(superCallExpression);
- if (superCallExpression.kind !== 204 /* BinaryExpression */
- || superCallExpression.left.kind !== 191 /* CallExpression */) {
- ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'.");
- }
- // Shift comments from the original super call to the return statement.
- ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */)));
- statements.push(returnStatement);
- return 2 /* ReplaceWithReturn */;
- }
- // Perform the capture.
- captureThisForNode(statements, ctor, superCallExpression || createActualThis());
- // If we're actually replacing the original statement, we need to signal this to the caller.
- if (superCallExpression) {
- return 1 /* ReplaceSuperCapture */;
- }
- return 0 /* NoReplacement */;
- }
function createActualThis() {
return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
}
@@ -71935,14 +72913,9 @@
return node;
}
}
- /**
- * Gets a value indicating whether we need to add default value assignments for a
- * function-like node.
- *
- * @param node A function-like node.
- */
- function shouldAddDefaultValueAssignments(node) {
- return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0;
+ function hasDefaultValueOrBindingPattern(node) {
+ return node.initializer !== undefined
+ || ts.isBindingPattern(node.name);
}
/**
* Adds statements to the body of a function-like node if it contains parameters with
@@ -71952,9 +72925,10 @@
* @param node A function-like node.
*/
function addDefaultValueAssignmentsIfNeeded(statements, node) {
- if (!shouldAddDefaultValueAssignments(node)) {
- return;
+ if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
+ return false;
}
+ var added = false;
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
@@ -71964,12 +72938,14 @@
continue;
}
if (ts.isBindingPattern(name)) {
- addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer);
+ added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
}
else if (initializer) {
- addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ added = true;
}
}
+ return added;
}
/**
* Adds statements to the body of a function-like node for parameters with binding patterns
@@ -71979,18 +72955,20 @@
* @param name The name of the parameter.
* @param initializer The initializer for the parameter.
*/
- function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
- var temp = ts.getGeneratedNameForNode(parameter);
+ function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
// In cases where a binding pattern is simply '[]' or '{}',
// we usually don't want to emit a var declaration; however, in the presence
// of an initializer, we must emit that expression to preserve side effects.
if (name.elements.length > 0) {
- statements.push(ts.setEmitFlags(ts.createVariableStatement(
- /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
+ return true;
}
else if (initializer) {
- statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
+ return true;
}
+ return false;
}
/**
* Adds statements to the body of a function-like node for parameters with initializers.
@@ -72000,7 +72978,7 @@
* @param name The name of the parameter.
* @param initializer The initializer for the parameter.
*/
- function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
+ function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
initializer = ts.visitNode(initializer, visitor, ts.isExpression);
var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
@@ -72008,7 +72986,7 @@
ts.startOnNewLine(statement);
ts.setTextRange(statement, parameter);
ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
- statements.push(statement);
+ ts.insertStatementAfterCustomPrologue(statements, statement);
}
/**
* Gets a value indicating whether we need to add statements to handle a rest parameter.
@@ -72031,9 +73009,10 @@
* synthesized call to `super`
*/
function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
+ var prologueStatements = [];
var parameter = ts.lastOrUndefined(node.parameters);
if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
- return;
+ return false;
}
// `declarationName` is the name of the local declaration for the parameter.
var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
@@ -72043,7 +73022,7 @@
var restIndex = node.parameters.length - 1;
var temp = ts.createLoopVariable();
// var param = [];
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
ts.createVariableDeclaration(declarationName,
/*type*/ undefined, ts.createArrayLiteral([]))
@@ -72062,25 +73041,30 @@
]));
ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
ts.startOnNewLine(forStatement);
- statements.push(forStatement);
+ prologueStatements.push(forStatement);
if (parameter.name.kind !== 72 /* Identifier */) {
// do the actual destructuring of the rest parameter if necessary
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
}
+ ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
+ return true;
}
/**
* Adds a statement to capture the `this` of a function declaration if it is needed.
+ * NOTE: This must be executed *after* the subtree has been visited.
*
* @param statements The statements for the new function body.
* @param node A node.
*/
- function addCaptureThisForNodeIfNeeded(statements, node) {
- if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) {
- captureThisForNode(statements, node, ts.createThis());
+ function insertCaptureThisForNodeIfNeeded(statements, node) {
+ if (hierarchyFacts & 16384 /* CapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) {
+ insertCaptureThisForNode(statements, node, ts.createThis());
+ return true;
}
+ return false;
}
- function captureThisForNode(statements, node, initializer) {
+ function insertCaptureThisForNode(statements, node, initializer) {
enableSubstitutionsForCapturedThis();
var captureThisStatement = ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
@@ -72089,10 +73073,10 @@
]));
ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
ts.setSourceMapRange(captureThisStatement, node);
- statements.push(captureThisStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
}
- function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
- if (hierarchyFacts & 16384 /* NewTarget */) {
+ function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
+ if (hierarchyFacts & 8192 /* NewTarget */) {
var newTarget = void 0;
switch (node.kind) {
case 197 /* ArrowFunction */:
@@ -72123,10 +73107,11 @@
ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"),
/*type*/ undefined, newTarget)
]));
+ ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
if (copyOnWrite) {
- return [captureNewTargetStatement].concat(statements);
+ statements = statements.slice();
}
- statements.unshift(captureNewTargetStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
}
return statements;
}
@@ -72178,7 +73163,6 @@
* @param member The MethodDeclaration node.
*/
function transformClassMethodDeclarationToStatement(receiver, member, container) {
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
var commentRange = ts.getCommentRange(member);
var sourceMapRange = ts.getSourceMapRange(member);
var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name);
@@ -72193,7 +73177,6 @@
// No source map should be emitted for this statement to align with the
// old emitter.
ts.setEmitFlags(statement, 48 /* NoSourceMap */);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return statement;
}
/**
@@ -72219,7 +73202,6 @@
*/
function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
// To align with source maps in the old emitter, the receiver and property name
// arguments are both mapped contiguously to the accessor name.
var target = ts.getMutableClone(receiver);
@@ -72255,7 +73237,6 @@
if (startsOnNewLine) {
ts.startOnNewLine(call);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return call;
}
/**
@@ -72264,12 +73245,12 @@
* @param node An ArrowFunction node.
*/
function visitArrowFunction(node) {
- if (node.transformFlags & 8192 /* ContainsLexicalThis */) {
- enableSubstitutionsForCapturedThis();
+ if (node.transformFlags & 2048 /* ContainsLexicalThis */) {
+ hierarchyFacts |= 16384 /* CapturedLexicalThis */;
}
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
+ var ancestorFacts = enterSubtree(8064 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
var func = ts.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
@@ -72279,7 +73260,11 @@
ts.setTextRange(func, node);
ts.setOriginalNode(func, node);
ts.setEmitFlags(func, 8 /* CapturesThis */);
- exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ if (hierarchyFacts & 16384 /* CapturedLexicalThis */) {
+ enableSubstitutionsForCapturedThis();
+ }
+ // If an arrow function contains
+ exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return func;
}
@@ -72290,18 +73275,16 @@
*/
function visitFunctionExpression(node) {
var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
- ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
- : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ ? enterSubtree(8086 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
+ : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64 /* ES2015 */
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384 /* NewTarget */
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192 /* NewTarget */
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionExpression(node,
/*modifiers*/ undefined, node.asteriskToken, name,
@@ -72316,15 +73299,13 @@
function visitFunctionDeclaration(node) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64 /* ES2015 */
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384 /* NewTarget */
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192 /* NewTarget */
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionDeclaration(node,
/*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name,
@@ -72342,14 +73323,14 @@
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
- ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
- : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ ? enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
+ : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
var body = transformFunctionBody(node);
- if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) {
+ if (hierarchyFacts & 8192 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) {
name = ts.getGeneratedNameForNode(node);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
/*modifiers*/ undefined, node.asteriskToken, name,
@@ -72367,7 +73348,7 @@
var singleLine = false; // indicates whether the block *may* be emitted as a single line
var statementsLocation;
var closeBraceLocation;
- var leadingStatements = [];
+ var prologue = [];
var statements = [];
var body = node.body;
var statementOffset;
@@ -72375,14 +73356,13 @@
if (ts.isBlock(body)) {
// ensureUseStrict is false because no new prologue-directive should be added.
// addStandardPrologue will put already-existing directives at the beginning of the target statement-array
- statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false);
+ statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
}
- addCaptureThisForNodeIfNeeded(leadingStatements, node);
- addDefaultValueAssignmentsIfNeeded(leadingStatements, node);
- addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false);
+ multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
+ multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
if (ts.isBlock(body)) {
// addCustomPrologue puts already-existing directives at the beginning of the target statement-array
- statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor);
+ statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
statementsLocation = body.statements;
ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
// If the original body was a multi-line block, this must be a multi-line block.
@@ -72416,14 +73396,19 @@
// source map location for the close brace.
closeBraceLocation = body;
}
- var lexicalEnvironment = context.endLexicalEnvironment();
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
- prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false);
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
+ insertCaptureThisForNodeIfNeeded(prologue, node);
// If we added any final generated statements, this must be a multi-line block
- if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) {
+ if (ts.some(prologue)) {
multiLine = true;
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine);
+ statements.unshift.apply(statements, prologue);
+ if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
+ // no changes were made, preserve the tree
+ return body;
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
ts.setTextRange(block, node.body);
if (!multiLine && singleLine) {
ts.setEmitFlags(block, 1 /* SingleLine */);
@@ -72434,11 +73419,6 @@
ts.setOriginalNode(block, node.body);
return block;
}
- function visitFunctionBodyDownLevel(node) {
- var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context);
- return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)),
- /*location*/ updated.statements));
- }
function visitBlock(node, isFunctionBody) {
if (isFunctionBody) {
// A function body is not a block scope.
@@ -72543,7 +73523,7 @@
* @param node A VariableDeclarationList node.
*/
function visitVariableDeclarationList(node) {
- if (node.transformFlags & 64 /* ES2015 */) {
+ if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 65536 /* ContainsBindingPattern */) {
if (node.flags & 3 /* BlockScoped */) {
enableSubstitutionsForBlockScopedBindings();
}
@@ -72556,7 +73536,7 @@
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 & 2097152 /* ContainsBindingPattern */
+ if (node.transformFlags & 65536 /* ContainsBindingPattern */
&& (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
}
@@ -72878,7 +73858,7 @@
var numInitialPropertiesWithoutYield = numProperties;
for (var i = 0; i < numProperties; i++) {
var property = properties[i];
- if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
+ if ((property.transformFlags & 131072 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
&& i < numInitialPropertiesWithoutYield) {
numInitialPropertiesWithoutYield = i;
}
@@ -73154,7 +74134,7 @@
*/
function createFunctionForInitializerOfForStatement(node, currentState) {
var functionName = ts.createUniqueName("_loop_init");
- var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ var containsYield = (node.initializer.transformFlags & 131072 /* ContainsYield */) !== 0;
var emitFlags = 0 /* None */;
if (currentState.containsLexicalThis)
emitFlags |= 8 /* CapturesThis */;
@@ -73259,11 +74239,11 @@
statements.push(statement);
}
copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
+ ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
var loopBody = ts.createBlock(statements, /*multiLine*/ true);
if (ts.isBlock(statement))
ts.setOriginalNode(loopBody, statement);
- var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ var containsYield = (node.statement.transformFlags & 131072 /* ContainsYield */) !== 0;
var emitFlags = 0;
if (currentState.containsLexicalThis)
emitFlags |= 8 /* CapturesThis */;
@@ -73495,13 +74475,11 @@
* @param receiver The receiver for the assignment.
*/
function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
ts.setTextRange(expression, method);
if (startsOnNewLine) {
ts.startOnNewLine(expression);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return expression;
}
function visitCatchClause(node) {
@@ -73553,19 +74531,17 @@
ts.Debug.assert(!ts.isComputedPropertyName(node.name));
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var updated;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */)
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
+ var body = transformFunctionBody(node);
if (node.kind === 158 /* GetAccessor */) {
updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
}
else {
updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return updated;
}
@@ -73579,10 +74555,7 @@
/*location*/ node);
}
function visitComputedPropertyName(node) {
- var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */);
- var updated = ts.visitEachChild(node, visitor, context);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */);
- return updated;
+ return ts.visitEachChild(node, visitor, context);
}
/**
* Visits a YieldExpression node.
@@ -73599,7 +74572,7 @@
* @param node An ArrayLiteralExpression node.
*/
function visitArrayLiteralExpression(node) {
- if (node.transformFlags & 64 /* ES2015 */) {
+ if (ts.some(node.elements, ts.isSpreadElement)) {
// We are here because we contain a SpreadElementExpression.
return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
}
@@ -73614,7 +74587,10 @@
if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
return visitTypeScriptClassWrapper(node);
}
- if (node.transformFlags & 64 /* ES2015 */) {
+ var expression = ts.skipOuterExpressions(node.expression);
+ if (expression.kind === 98 /* SuperKeyword */ ||
+ ts.isSuperProperty(expression) ||
+ ts.some(node.arguments, ts.isSpreadElement)) {
return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
}
return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression),
@@ -73735,7 +74711,7 @@
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 & 131072 /* ContainsRestOrSpread */ ||
+ if (node.transformFlags & 4096 /* ContainsRestOrSpread */ ||
node.expression.kind === 98 /* SuperKeyword */ ||
ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
@@ -73743,7 +74719,7 @@
ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
}
var resultingCall = void 0;
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */) {
+ if (node.transformFlags & 4096 /* ContainsRestOrSpread */) {
// [source]
// f(...a, b)
// x.m(...a, b)
@@ -73757,7 +74733,7 @@
// _super.apply(this, a.concat([b]))
// _super.m.apply(this, a.concat([b]))
// _super.prototype.m.apply(this, a.concat([b]))
- resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
+ resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
}
else {
// [source]
@@ -73769,13 +74745,11 @@
// _super.call(this, a)
// _super.m.call(this, a)
// _super.prototype.m.call(this, a)
- resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
+ resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
/*location*/ node);
}
if (node.expression.kind === 98 /* SuperKeyword */) {
- var actualThis = ts.createThis();
- ts.setEmitFlags(actualThis, 4 /* NoSubstitution */);
- var initializer = ts.createLogicalOr(resultingCall, actualThis);
+ var initializer = ts.createLogicalOr(resultingCall, createActualThis());
resultingCall = assignToCapturedThis
? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
: initializer;
@@ -73790,7 +74764,7 @@
* @param node A NewExpression node.
*/
function visitNewExpression(node) {
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */) {
+ if (ts.some(node.arguments, ts.isSpreadElement)) {
// We are here because we contain a SpreadElementExpression.
// [source]
// new C(...a)
@@ -74053,12 +75027,7 @@
}
function visitMetaProperty(node) {
if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") {
- if (hierarchyFacts & 8192 /* ComputedPropertyName */) {
- hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */;
- }
- else {
- hierarchyFacts |= 16384 /* NewTarget */;
- }
+ hierarchyFacts |= 8192 /* NewTarget */;
return ts.createFileLevelUniqueName("_newTarget");
}
return node;
@@ -74073,7 +75042,7 @@
function onEmitNode(hint, node, emitCallback) {
if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
// If we are tracking a captured `this`, keep track of the enclosing function.
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
: 65 /* FunctionIncludes */);
previousOnEmitNode(hint, node, emitCallback);
@@ -74253,7 +75222,7 @@
}
ts.transformES2015 = transformES2015;
function createExtendsHelper(context, name) {
- context.requestEmitHelper(extendsHelper);
+ context.requestEmitHelper(ts.extendsHelper);
return ts.createCall(ts.getHelperName("__extends"),
/*typeArguments*/ undefined, [
name,
@@ -74261,20 +75230,20 @@
]);
}
function createTemplateObjectHelper(context, cooked, raw) {
- context.requestEmitHelper(templateObjectHelper);
+ context.requestEmitHelper(ts.templateObjectHelper);
return ts.createCall(ts.getHelperName("__makeTemplateObject"),
/*typeArguments*/ undefined, [
cooked,
raw
]);
}
- var extendsHelper = {
+ ts.extendsHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
};
- var templateObjectHelper = {
+ ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
@@ -74621,7 +75590,7 @@
var withBlockStack; // A stack containing `with` blocks.
return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
- if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
+ if (node.isDeclarationFile || (node.transformFlags & 256 /* ContainsGenerator */) === 0) {
return node;
}
var visited = ts.visitEachChild(node, visitor, context);
@@ -74641,10 +75610,10 @@
else if (inGeneratorFunctionBody) {
return visitJavaScriptInGeneratorFunctionBody(node);
}
- else if (transformFlags & 256 /* Generator */) {
+ else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
return visitGenerator(node);
}
- else if (transformFlags & 512 /* ContainsGenerator */) {
+ else if (transformFlags & 256 /* ContainsGenerator */) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -74697,10 +75666,10 @@
case 230 /* ReturnStatement */:
return visitReturnStatement(node);
default:
- if (node.transformFlags & 4194304 /* ContainsYield */) {
+ if (node.transformFlags & 131072 /* ContainsYield */) {
return visitJavaScriptContainingYield(node);
}
- else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) {
+ else if (node.transformFlags & (256 /* ContainsGenerator */ | 262144 /* ContainsHoistedDeclarationOrCompletion */)) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -74876,7 +75845,7 @@
var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
var buildResult = build();
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
statements.push(ts.createReturn(buildResult));
// Restore previous generator state
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
@@ -74903,7 +75872,7 @@
* @param node The node to visit.
*/
function visitVariableStatement(node) {
- if (node.transformFlags & 4194304 /* ContainsYield */) {
+ if (node.transformFlags & 131072 /* ContainsYield */) {
transformAndEmitVariableDeclarationList(node.declarationList);
return undefined;
}
@@ -75961,7 +76930,7 @@
}
}
function containsYield(node) {
- return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ return !!node && (node.transformFlags & 131072 /* ContainsYield */) !== 0;
}
function countInitialNodesWithoutYield(nodes) {
var numNodes = nodes.length;
@@ -76968,7 +77937,7 @@
}
ts.transformGenerators = transformGenerators;
function createGeneratorHelper(context, body) {
- context.requestEmitHelper(generatorHelper);
+ context.requestEmitHelper(ts.generatorHelper);
return ts.createCall(ts.getHelperName("__generator"),
/*typeArguments*/ undefined, [ts.createThis(), body]);
}
@@ -77031,7 +78000,7 @@
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
- var generatorHelper = {
+ ts.generatorHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
@@ -77064,7 +78033,7 @@
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var currentSourceFile; // The current file.
@@ -77080,7 +78049,7 @@
function transformSourceFile(node) {
if (node.isDeclarationFile ||
!(ts.isEffectiveExternalModule(node, compilerOptions) ||
- node.transformFlags & 16777216 /* ContainsDynamicImport */ ||
+ node.transformFlags & 524288 /* ContainsDynamicImport */ ||
(ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
return node;
}
@@ -77117,7 +78086,7 @@
ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -77343,7 +78312,7 @@
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
// End the lexical environment for the module body
// and merge any new lexical declarations.
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var body = ts.createBlock(statements, /*multiLine*/ true);
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -77406,9 +78375,9 @@
return visitFunctionDeclaration(node);
case 240 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
@@ -77417,13 +78386,13 @@
function moduleExpressionElementVisitor(node) {
// This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
// as export/import statements are only transformed at the top level of a file.
- if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) {
+ if (!(node.transformFlags & 524288 /* ContainsDynamicImport */) && !(node.transformFlags & 512 /* ContainsDestructuringAssignment */)) {
return node;
}
if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) {
+ else if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else {
@@ -77484,7 +78453,7 @@
}
function visitImportCallExpression(node) {
var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
- var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */);
+ var containsLexicalThis = !!(node.transformFlags & 2048 /* ContainsLexicalThis */);
switch (compilerOptions.module) {
case ts.ModuleKind.AMD:
return createImportCallExpressionAMD(argument, containsLexicalThis);
@@ -77566,7 +78535,7 @@
}
var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]);
}
return promise;
@@ -77580,7 +78549,7 @@
var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
}
var func;
@@ -77614,11 +78583,11 @@
return innerExpr;
}
if (ts.getImportNeedsImportStarHelper(node)) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
}
if (ts.getImportNeedsImportDefaultHelper(node)) {
- context.requestEmitHelper(importDefaultHelper);
+ context.requestEmitHelper(ts.importDefaultHelper);
return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
}
return innerExpr;
@@ -78187,7 +79156,7 @@
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -78275,7 +79244,7 @@
}
if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
/*location*/ node);
}
@@ -78401,13 +79370,13 @@
text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
};
// emit helper for `import * as Name from "foo"`
- var importStarHelper = {
+ ts.importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
- var importDefaultHelper = {
+ ts.importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
@@ -78430,7 +79399,7 @@
context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols.
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var exportFunctionsMap = []; // The export function associated with a source file.
@@ -78449,7 +79418,7 @@
* @param node The SourceFile node.
*/
function transformSourceFile(node) {
- if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) {
+ if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288 /* ContainsDynamicImport */)) {
return node;
}
var id = ts.getOriginalNodeId(node);
@@ -78615,7 +79584,7 @@
// We emit hoisted variables early to align roughly with our previous emit output.
// Two key differences in this approach are:
// - Temporary variables will appear at the top rather than at the bottom of the file
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
var moduleObject = ts.createObjectLiteral([
ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
@@ -79000,7 +79969,7 @@
function shouldHoistVariableDeclarationList(node) {
// hoist only non-block scoped declarations or block scoped declarations parented by source file
return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
- && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */
+ && (enclosingBlockScopedContainer.kind === 284 /* SourceFile */
|| (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
}
/**
@@ -79343,9 +80312,9 @@
return visitCatchClause(node);
case 218 /* Block */:
return visitBlock(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -79527,14 +80496,13 @@
* @param node The node to visit.
*/
function destructuringAndImportCallVisitor(node) {
- if (node.transformFlags & 1024 /* DestructuringAssignment */
- && node.kind === 204 /* BinaryExpression */) {
+ if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) {
+ else if ((node.transformFlags & 512 /* ContainsDestructuringAssignment */) || (node.transformFlags & 524288 /* ContainsDynamicImport */)) {
return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
}
else {
@@ -79593,7 +80561,7 @@
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 279 /* SourceFile */;
+ return container !== undefined && container.kind === 284 /* SourceFile */;
}
else {
return false;
@@ -79626,7 +80594,7 @@
* @param emitCallback A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -79835,7 +80803,7 @@
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -79874,7 +80842,7 @@
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(279 /* SourceFile */);
+ context.enableEmitNotification(284 /* SourceFile */);
context.enableSubstitution(72 /* Identifier */);
var currentSourceFile;
return ts.chainBundle(transformSourceFile);
@@ -79984,7 +80952,8 @@
ts.isImportEqualsDeclaration(node) ||
ts.isTypeAliasDeclaration(node) ||
ts.isConstructorDeclaration(node) ||
- ts.isIndexSignatureDeclaration(node);
+ ts.isIndexSignatureDeclaration(node) ||
+ ts.isPropertyAccessExpression(node);
}
ts.canProduceDiagnostics = canProduceDiagnostics;
function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
@@ -80058,7 +81027,7 @@
}
ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
function createGetSymbolAccessibilityDiagnosticForNode(node) {
- if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
+ if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
return getVariableDeclarationTypeVisibilityError;
}
else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
@@ -80098,7 +81067,7 @@
}
// This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
// The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
- else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ ||
+ else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 189 /* PropertyAccessExpression */ || node.kind === 153 /* PropertySignature */ ||
(node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
// TODO(jfreeman): Deal with computed properties in error reporting.
if (ts.hasModifier(node, 32 /* Static */)) {
@@ -80303,6 +81272,9 @@
case 241 /* InterfaceDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
+ case 181 /* MappedType */:
+ diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
+ break;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
@@ -80386,6 +81358,31 @@
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
+ function hasInternalAnnotation(range, currentSourceFile) {
+ var comment = currentSourceFile.text.substring(range.pos, range.end);
+ return ts.stringContains(comment, "@internal");
+ }
+ function isInternalDeclaration(node, currentSourceFile) {
+ var parseTreeNode = ts.getParseTreeNode(node);
+ if (parseTreeNode && parseTreeNode.kind === 151 /* Parameter */) {
+ var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
+ var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
+ var text = currentSourceFile.text;
+ var commentRanges = previousSibling
+ ? ts.concatenate(
+ // to handle
+ // ... parameters, /* @internal */
+ // public param: string
+ ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
+ : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
+ return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
+ }
+ var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!ts.forEach(leadingCommentRanges, function (range) {
+ return hasInternalAnnotation(range, currentSourceFile);
+ });
+ }
+ ts.isInternalDeclaration = isInternalDeclaration;
var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
2048 /* WriteClassExpressionAsTypeLiteral */ |
4096 /* UseTypeOfFunction */ |
@@ -80514,10 +81511,10 @@
}
}
function transformRoot(node) {
- if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
+ if (node.kind === 284 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
}
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
isBundledEmit = true;
refs = ts.createMap();
libs = ts.createMap();
@@ -80547,9 +81544,15 @@
var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
}), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282 /* InputFiles */) {
- return ts.createUnparsedSourceFile(prepend, "dts");
+ if (prepend.kind === 287 /* InputFiles */) {
+ var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
}
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -80641,7 +81644,7 @@
}
}
function collectReferences(sourceFile, ret) {
- if (noResolve || ts.isSourceFileJS(sourceFile))
+ if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
return ret;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
@@ -81188,7 +82191,9 @@
if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
return undefined;
}
+ getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker);
+ getSymbolAccessibilityDiagnostic = oldDiag;
var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
});
@@ -81231,7 +82236,7 @@
if (ctor) {
var oldDiag_1 = getSymbolAccessibilityDiagnostic;
parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
- if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */))
+ if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
return;
getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
if (param.name.kind === 72 /* Identifier */) {
@@ -81367,18 +82372,8 @@
}
errorNameNode = undefined;
}
- function hasInternalAnnotation(range) {
- var comment = currentSourceFile.text.substring(range.pos, range.end);
- return ts.stringContains(comment, "@internal");
- }
function shouldStripInternal(node) {
- if (stripInternal && node) {
- var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
- if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node) {
return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
@@ -81400,7 +82395,7 @@
function ensureModifierFlags(node, privateDeclaration) {
var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
- var parentIsFile = node.parent.kind === 279 /* SourceFile */;
+ var parentIsFile = node.parent.kind === 284 /* SourceFile */;
if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */);
additions = 0 /* None */;
@@ -81569,9 +82564,15 @@
if (jsx === 2 /* React */) {
transformers.push(ts.transformJsx);
}
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
transformers.push(ts.transformESNext);
}
+ if (languageVersion < 6 /* ES2019 */) {
+ transformers.push(ts.transformES2019);
+ }
+ if (languageVersion < 5 /* ES2018 */) {
+ transformers.push(ts.transformES2018);
+ }
if (languageVersion < 4 /* ES2017 */) {
transformers.push(ts.transformES2017);
}
@@ -81611,7 +82612,7 @@
* @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
*/
function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
- var enabledSyntaxKindFeatures = new Array(312 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(317 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -81871,10 +82872,14 @@
})(ts || (ts = {}));
var ts;
(function (ts) {
- var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
var syntheticParent = { pos: -1, end: -1 };
/*@internal*/
+ function isBuildInfoFile(file) {
+ return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
+ }
+ ts.isBuildInfoFile = isBuildInfoFile;
+ /*@internal*/
/**
* Iterates over the source files that are expected to have an emit output.
*
@@ -81884,13 +82889,14 @@
* If an array, the full list of source files to emit.
* Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
*/
- function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
+ var prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ var bundle = ts.createBundle(sourceFiles, prepends);
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -81898,6 +82904,7 @@
}
}
else {
+ if (!onlyBuildInfo) {
for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
var sourceFile = sourceFiles_1[_a];
var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
@@ -81906,23 +82913,52 @@
}
}
}
+ if (includeBuildInfo) {
+ var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath)
+ return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
+ }
+ }
}
ts.forEachEmittedFile = forEachEmittedFile;
/*@internal*/
+ function getOutputPathForBuildInfo(options) {
+ var configFile = options.configFilePath;
+ if (!configFile || !ts.isIncrementalCompilation(options))
+ return undefined;
+ if (options.tsBuildInfoFile)
+ return options.tsBuildInfoFile;
+ var outPath = options.outFile || options.out;
+ var buildInfoExtensionLess;
+ if (outPath) {
+ buildInfoExtensionLess = ts.removeFileExtension(outPath);
+ }
+ else {
+ var configFileExtensionLess = ts.removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
+ ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
+ }
+ ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
+ /*@internal*/
function getOutputPathsForBundle(options, forceDtsPaths) {
var outPath = options.outFile || options.out;
var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath };
+ var buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
}
ts.getOutputPathsForBundle = getOutputPathsForBundle;
/*@internal*/
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
var options = host.getCompilerOptions();
- if (sourceFile.kind === 280 /* Bundle */) {
+ if (sourceFile.kind === 285 /* Bundle */) {
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
@@ -81936,19 +82972,13 @@
var isJs = ts.isSourceFileJS(sourceFile);
var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo() {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
@@ -81971,9 +83001,91 @@
return ".js" /* Js */;
}
ts.getOutputExtension = getOutputExtension;
+ function rootDirOfOptions(configFile) {
+ return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.assertDefined(configFile.options.configFilePath));
+ }
+ function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
+ return outputDir ?
+ ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
+ inputFileName;
+ }
+ /* @internal */
+ function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
+ ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(inputFileName));
+ return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
+ }
+ ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
+ function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
+ var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
+ var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
+ ".json" /* Json */ :
+ ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
+ ".jsx" /* Jsx */ :
+ ".js" /* Js */);
+ return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.assertDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
+ outputFileName :
+ undefined;
+ }
+ /*@internal*/
+ function getAllProjectOutputs(configFile, ignoreCase) {
+ var outputs;
+ var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
+ if (configFile.options.outFile || configFile.options.out) {
+ var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ addOutput(buildInfoPath);
+ }
+ else {
+ for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
+ var inputFileName = _c[_b];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
+ continue;
+ var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ addOutput(js);
+ if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
+ continue;
+ if (configFile.options.sourceMap) {
+ addOutput(js + ".map");
+ }
+ if (ts.getEmitDeclarations(configFile.options) && ts.hasTSFileExtension(inputFileName)) {
+ var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
+ addOutput(dts);
+ if (configFile.options.declarationMap) {
+ addOutput(dts + ".map");
+ }
+ }
+ }
+ addOutput(getOutputPathForBuildInfo(configFile.options));
+ }
+ return outputs || ts.emptyArray;
+ }
+ ts.getAllProjectOutputs = getAllProjectOutputs;
+ /*@internal*/
+ function getFirstProjectOutput(configFile, ignoreCase) {
+ if (configFile.options.outFile || configFile.options.out) {
+ var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
+ return ts.Debug.assertDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
+ var inputFileName = _b[_a];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
+ continue;
+ var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ if (jsFilePath)
+ return jsFilePath;
+ }
+ var buildInfoPath = getOutputPathForBuildInfo(configFile.options);
+ if (buildInfoPath)
+ return buildInfoPath;
+ return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ ts.getFirstProjectOutput = getFirstProjectOutput;
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -81981,12 +83093,12 @@
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
var writer = ts.createTextWriter(newLine);
var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
- var bundleInfo = createDefaultBundleInfo();
+ var bundleBuildInfo;
var emitSkipped = false;
var exportedModulesFromDeclarationEmit;
// Emit each output file
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
return {
emitSkipped: emitSkipped,
@@ -81996,9 +83108,16 @@
exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
@@ -82007,8 +83126,8 @@
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -82019,8 +83138,21 @@
}
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle, buildInfoPath) {
+ // Write build information if applicable
+ if (!buildInfoPath || targetSourceFile || emitSkipped)
+ return;
+ var program = host.getProgramBuildInfo();
+ if (!bundle && !program)
+ return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), /*writeByteOrderMark*/ false);
+ }
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
// Make sure not to write js file and source map file if any of them cannot be written
@@ -82040,6 +83172,7 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
// Create a printer to print the nodes
var printer = createPrinter(printerOptions, {
@@ -82050,12 +83183,14 @@
substituteNode: transform.substituteNode,
});
ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
// Clean up emit nodes on parse tree
transform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.js = printer.bundleFileInfo;
}
function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
- if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
return;
}
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -82084,6 +83219,8 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
var declarationPrinter = createPrinter(printerOptions, {
// resolver hooks
@@ -82096,18 +83233,20 @@
emitSkipped = emitSkipped || declBlocked;
if (!declBlocked || emitOnlyDtsFiles) {
ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
- printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, {
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
sourceMap: compilerOptions.declarationMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
- if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) {
+ if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284 /* SourceFile */) {
var sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node) {
if (ts.isExportAssignment(node)) {
@@ -82122,16 +83261,16 @@
}
ts.forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) {
- var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined;
- var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined;
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
+ var bundle = sourceFileOrBundle.kind === 285 /* Bundle */ ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 284 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
var sourceMapGenerator;
if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile, writer, sourceMapGenerator);
@@ -82160,18 +83299,12 @@
}
// Write the output file
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- // Write bundled offset information if applicable
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
- }
// Reset state
writer.clear();
- bundleInfo = createDefaultBundleInfo();
}
function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
- && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
+ && (sourceFileOrBundle.kind !== 284 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
}
function getSourceRoot(mapOptions) {
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
@@ -82228,6 +83361,167 @@
}
}
ts.emitFiles = emitFiles;
+ /*@internal*/
+ function getBuildInfoText(buildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+ ts.getBuildInfoText = getBuildInfoText;
+ /*@internal*/
+ function getBuildInfo(buildInfoText) {
+ return JSON.parse(buildInfoText);
+ }
+ ts.getBuildInfo = getBuildInfo;
+ /*@internal*/
+ ts.notImplementedResolver = {
+ hasGlobalName: ts.notImplemented,
+ getReferencedExportContainer: ts.notImplemented,
+ getReferencedImportDeclaration: ts.notImplemented,
+ getReferencedDeclarationWithCollidingName: ts.notImplemented,
+ isDeclarationWithCollidingName: ts.notImplemented,
+ isValueAliasDeclaration: ts.notImplemented,
+ isReferencedAliasDeclaration: ts.notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
+ getNodeCheckFlags: ts.notImplemented,
+ isDeclarationVisible: ts.notImplemented,
+ isLateBound: function (_node) { return false; },
+ collectLinkedAliases: ts.notImplemented,
+ isImplementationOfOverload: ts.notImplemented,
+ isRequiredInitializedParameter: ts.notImplemented,
+ isOptionalUninitializedParameterProperty: ts.notImplemented,
+ isExpandoFunctionDeclaration: ts.notImplemented,
+ getPropertiesOfContainerFunction: ts.notImplemented,
+ createTypeOfDeclaration: ts.notImplemented,
+ createReturnTypeOfSignatureDeclaration: ts.notImplemented,
+ createTypeOfExpression: ts.notImplemented,
+ createLiteralConstValue: ts.notImplemented,
+ isSymbolAccessible: ts.notImplemented,
+ isEntityNameVisible: ts.notImplemented,
+ // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
+ getConstantValue: ts.notImplemented,
+ getReferencedValueDeclaration: ts.notImplemented,
+ getTypeReferenceSerializationKind: ts.notImplemented,
+ isOptionalParameter: ts.notImplemented,
+ moduleExportsSomeValue: ts.notImplemented,
+ isArgumentsLocalBinding: ts.notImplemented,
+ getExternalModuleFileFromDeclaration: ts.notImplemented,
+ getTypeReferenceDirectivesForEntityName: ts.notImplemented,
+ getTypeReferenceDirectivesForSymbol: ts.notImplemented,
+ isLiteralConstDeclaration: ts.notImplemented,
+ getJsxFactoryEntity: ts.notImplemented,
+ getAllAccessorDeclarations: ts.notImplemented,
+ getSymbolOfExternalModuleSpecifier: ts.notImplemented,
+ isBindingCapturedByNode: ts.notImplemented,
+ };
+ function createSourceFilesFromBundleBuildInfo(bundle) {
+ var sourceFiles = bundle.sourceFiles.map(function (fileName) {
+ var sourceFile = ts.createNode(284 /* SourceFile */, 0, 0);
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = ts.createNodeArray();
+ return sourceFile;
+ });
+ var jsBundle = ts.Debug.assertDefined(bundle.js);
+ ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
+ var sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
+ var statement = ts.createNode(221 /* ExpressionStatement */, directive.pos, directive.end);
+ statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+ /*@internal*/
+ function emitUsingBuildInfo(config, host, getCommandLine) {
+ 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.assertDefined(buildInfoPath));
+ if (!buildInfoText)
+ return buildInfoPath;
+ var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
+ if (!jsFileText)
+ 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";
+ // read declaration text
+ var declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText)
+ 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;
+ 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);
+ var emitHost = {
+ getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
+ getCompilerOptions: function () { return config.options; },
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ getNewLine: function () { return host.getNewLine(); },
+ getSourceFile: ts.returnUndefined,
+ getSourceFileByPath: ts.returnUndefined,
+ getSourceFiles: function () { return sourceFilesForJsEmit; },
+ getLibFileFromReference: ts.notImplemented,
+ isSourceFileFromExternalLibrary: ts.returnFalse,
+ getResolvedProjectReferenceToRedirect: ts.returnUndefined,
+ writeFile: function (name, text, writeByteOrderMark) {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text)
+ return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text)
+ return;
+ break;
+ case buildInfoPath:
+ var newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ // Update sourceFileInfo
+ var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
+ newBuildInfo.bundle.js.sources = js.sources;
+ if (dts) {
+ newBuildInfo.bundle.dts.sources = dts.sources;
+ }
+ newBuildInfo.bundle.sourceFiles = sourceFiles;
+ outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text)
+ return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text)
+ return;
+ break;
+ default:
+ ts.Debug.fail("Unexpected path: " + name);
+ }
+ outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
+ },
+ isEmitBlocked: ts.returnFalse,
+ readFile: function (f) { return host.readFile(f); },
+ fileExists: function (f) { return host.fileExists(f); },
+ directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
+ useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getProgramBuildInfo: ts.returnUndefined
+ };
+ emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, ts.getTransformers(config.options));
+ return outputFiles;
+ }
+ ts.emitUsingBuildInfo = emitUsingBuildInfo;
var PipelinePhase;
(function (PipelinePhase) {
PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
@@ -82256,6 +83550,10 @@
var ownWriter; // Reusable `EmitTextWriter` for basic printing.
var write = writeBase;
var isOwnFileEmit;
+ var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
+ var recordInternalSection = printerOptions.recordInternalSection;
+ var sourceFileTextPos = 0;
+ var sourceFileTextKind = "text" /* Text */;
// Source Maps
var sourceMapsDisabled = true;
var sourceMapGenerator;
@@ -82281,7 +83579,8 @@
writeNode: writeNode,
writeList: writeList,
writeFile: writeFile,
- writeBundle: writeBundle
+ writeBundle: writeBundle,
+ bundleFileInfo: bundleFileInfo
};
function printNode(hint, node, sourceFile) {
switch (hint) {
@@ -82296,9 +83595,9 @@
break;
}
switch (node.kind) {
- case 279 /* SourceFile */: return printFile(node);
- case 280 /* Bundle */: return printBundle(node);
- case 281 /* UnparsedSource */: return printUnparsedSource(node);
+ case 284 /* SourceFile */: return printFile(node);
+ case 285 /* Bundle */: return printBundle(node);
+ case 286 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -82308,7 +83607,7 @@
return endPrint();
}
function printBundle(bundle) {
- writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined);
+ writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
return endPrint();
}
function printFile(sourceFile) {
@@ -82336,7 +83635,49 @@
reset();
writer = previousWriter;
}
- function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+ function updateOrPushBundleFileTextLike(pos, end, kind) {
+ var last = ts.lastOrUndefined(bundleFileInfo.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
+ }
+ }
+ function recordBundleFileInternalSectionStart(node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
+ ts.isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== "internal" /* Internal */) {
+ var prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = "internal" /* Internal */;
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+ function recordBundleFileTextLikeSection(end) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+ function writeBundle(bundle, output, sourceMapGenerator) {
+ var _a;
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -82344,18 +83685,49 @@
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
- var prepend = _b[_a];
+ for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
+ var prepend = _c[_b];
writeLine();
+ var pos = writer.getTextPos();
+ var savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections)
+ bundleFileInfo.sections = [];
print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ if (bundleFileInfo) {
+ var newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections;
+ if (prepend.oldFileOfCurrentEmit)
+ (_a = bundleFileInfo.sections).push.apply(_a, newSections);
+ else {
+ newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend" /* Prepend */, data: prepend.fileName, texts: newSections });
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
}
- for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
- var sourceFile = _d[_c];
+ }
+ sourceFileTextPos = getTextPosWithWriteLine();
+ for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
+ var sourceFile = _e[_d];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ var end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ // Store prologues
+ var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+ // Store helpes
+ var helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
reset();
writer = previousWriter;
}
@@ -82425,8 +83797,10 @@
function emit(node) {
if (node === undefined)
return;
+ var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
pipelinePhase(4 /* Unspecified */, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node) {
if (node === undefined)
@@ -82453,12 +83827,12 @@
}
// falls through
case 2 /* Comments */:
- if (!commentsDisabled && node.kind !== 279 /* SourceFile */) {
+ if (!commentsDisabled && node.kind !== 284 /* SourceFile */) {
return pipelineEmitWithComments;
}
// falls through
case 3 /* SourceMaps */:
- if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) {
+ if (!sourceMapsDisabled && node.kind !== 284 /* SourceFile */ && !ts.isInJsonFile(node)) {
return pipelineEmitWithSourceMap;
}
// falls through
@@ -82495,8 +83869,16 @@
case 16 /* TemplateMiddle */:
case 17 /* TemplateTail */:
return emitLiteral(node);
- case 281 /* UnparsedSource */:
- return emitUnparsedSource(node);
+ case 286 /* UnparsedSource */:
+ case 280 /* UnparsedPrepend */:
+ return emitUnparsedSourceOrPrepend(node);
+ case 279 /* UnparsedPrologue */:
+ return writeUnparsedNode(node);
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return emitUnparsedTextLike(node);
+ case 283 /* UnparsedSyntheticReference */:
+ return emitUnparsedSyntheticReference(node);
// Identifiers
case 72 /* Identifier */:
return emitIdentifier(node);
@@ -82540,7 +83922,7 @@
return emitTypeReference(node);
case 165 /* FunctionType */:
return emitFunctionType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return emitJSDocFunctionType(node);
case 166 /* ConstructorType */:
return emitConstructorType(node);
@@ -82578,20 +83960,20 @@
return emitLiteralType(node);
case 183 /* ImportType */:
return emitImportTypeNode(node);
- case 284 /* JSDocAllType */:
+ case 289 /* JSDocAllType */:
writePunctuation("*");
return;
- case 285 /* JSDocUnknownType */:
+ case 290 /* JSDocUnknownType */:
writePunctuation("?");
return;
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return emitJSDocNullableType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return emitJSDocNonNullableType(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return emitJSDocOptionalType(node);
case 172 /* RestType */:
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return emitRestOrJSDocVariadicType(node);
// Binding patterns
case 184 /* ObjectBindingPattern */:
@@ -82729,30 +84111,30 @@
case 278 /* EnumMember */:
return emitEnumMember(node);
// JSDoc nodes (only used in codefixes currently)
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return emitJSDocPropertyLikeTag(node);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return emitJSDocSimpleTypedTag(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return emitJSDocAugmentsTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return emitJSDocTemplateTag(node);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return emitJSDocTypedefTag(node);
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return emitJSDocCallbackTag(node);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return emitJSDocSignature(node);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return emitJSDocTypeLiteral(node);
- case 296 /* JSDocClassTag */:
- case 294 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
return emitJSDocSimpleTag(node);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return emitJSDoc(node);
// Transformation nodes (ignored)
}
@@ -82851,9 +84233,9 @@
case 264 /* JsxFragment */:
return emitJsxFragment(node);
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return emitPartiallyEmittedExpression(node);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return emitCommaList(node);
}
}
@@ -82869,22 +84251,45 @@
var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node);
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle) {
+ var result;
+ if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ var bundledHelpers = ts.createMap();
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
+ var helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers)
+ continue;
+ for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
+ var helper = helpers_3[_c];
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+ return result;
+ }
function emitHelpers(node) {
var helpersEmitted = false;
- var bundle = node.kind === 280 /* Bundle */ ? node : undefined;
+ var bundle = node.kind === 285 /* Bundle */ ? node : undefined;
if (bundle && moduleKind === ts.ModuleKind.None) {
return;
}
- var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ var numPrepends = bundle ? bundle.prepends.length : 0;
+ var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (var i = 0; i < numNodes; i++) {
- var currentNode = bundle ? bundle.sourceFiles[i] : node;
- var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
- var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
- var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
- var helpers = ts.getEmitHelpers(currentNode);
+ var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
+ var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
+ for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
+ var helper = helpers_4[_a];
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
@@ -82904,18 +84309,25 @@
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
+ var pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
+ function getSortedEmitHelpers(node) {
+ var helpers = ts.getEmitHelpers(node);
+ return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
+ }
//
// Literals/Pseudo-literals
//
@@ -82942,8 +84354,42 @@
}
}
// SyntaxKind.UnparsedSource
- function emitUnparsedSource(unparsed) {
- writer.rawWrite(unparsed.text);
+ // SyntaxKind.UnparsedPrepend
+ function emitUnparsedSourceOrPrepend(unparsed) {
+ for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
+ var text = _b[_a];
+ writeLine();
+ emit(text);
+ }
+ }
+ // SyntaxKind.UnparsedPrologue
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ // SyntaxKind.UnparsedSyntheticReference
+ function writeUnparsedNode(unparsed) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ function emitUnparsedTextLike(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 /* UnparsedText */ ?
+ "text" /* Text */ :
+ "internal" /* Internal */);
+ }
+ }
+ // SyntaxKind.UnparsedSyntheticReference
+ function emitUnparsedSyntheticReference(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ var section = ts.clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
//
// Identifiers
@@ -82998,7 +84444,7 @@
emit(node.dotDotDotToken);
emitNodeWithWriter(node.name, writeParameter);
emit(node.questionToken);
- if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) {
+ if (node.parent && node.parent.kind === 294 /* JSDocFunctionType */ && !node.name) {
emit(node.type);
}
else {
@@ -83878,7 +85324,7 @@
}
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
// Emit all the prologue directives (like "use strict").
- var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
+ var statementOffset = emitPrologueDirectives(body.statements);
var pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -84138,7 +85584,7 @@
writePunctuation(">");
}
function emitJsxText(node) {
- writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true));
+ writer.writeLiteral(node.text);
}
function emitJsxClosingElementOrFragment(node) {
writePunctuation("</");
@@ -84283,7 +85729,7 @@
}
}
if (node.tags) {
- if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) {
+ if (node.tags.length === 1 && node.tags[0].kind === 307 /* JSDocTypeTag */ && !node.comment) {
writeSpace();
emit(node.tags[0]);
}
@@ -84317,7 +85763,7 @@
function emitJSDocTypedefTag(tag) {
emitJSDocTagName(tag.tagName);
if (tag.typeExpression) {
- if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
emitJSDocTypeExpression(tag.typeExpression);
}
else {
@@ -84336,7 +85782,7 @@
emit(tag.fullName);
}
emitJSDocComment(tag.comment);
- if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) {
+ if (tag.typeExpression && tag.typeExpression.kind === 297 /* JSDocTypeLiteral */) {
emitJSDocTypeLiteral(tag.typeExpression);
}
}
@@ -84423,6 +85869,16 @@
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
@@ -84430,7 +85886,10 @@
}
function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
+ var pos = writer.getTextPos();
writeComment("/// <reference no-default-lib=\"true\"/>");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -84451,17 +85910,26 @@
}
for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
var directive = files_1[_c];
+ var pos = writer.getTextPos();
writeComment("/// <reference path=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
writeLine();
}
- for (var _d = 0, types_18 = types; _d < types_18.length; _d++) {
- var directive = types_18[_d];
+ for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
+ var directive = types_19[_d];
+ var pos = writer.getTextPos();
writeComment("/// <reference types=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
writeLine();
}
for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
var directive = libs_1[_e];
+ var pos = writer.getTextPos();
writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
writeLine();
}
}
@@ -84486,16 +85954,22 @@
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
- function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
+ function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
+ var needsToSetSourceFile = !!sourceFile;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (ts.isPrologueDirective(statement)) {
var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile);
}
+ writeLine();
+ var pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -84508,23 +85982,70 @@
}
return statements.length;
}
+ function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
+ for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
+ var prologue = prologues_1[_a];
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ var pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
if (ts.isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
var seenPrologueDirectives = ts.createMap();
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
}
setSourceFile(undefined);
}
}
+ function getPrologueDirectivesFromBundledSourceFiles(bundle) {
+ var seenPrologueDirectives = ts.createMap();
+ var prologues;
+ for (var index = 0; index < bundle.sourceFiles.length; index++) {
+ var sourceFile = bundle.sourceFiles[index];
+ var directives = void 0;
+ var end = 0;
+ for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
+ var statement = _b[_a];
+ if (!ts.isPrologueDirective(statement))
+ break;
+ if (seenPrologueDirectives.has(statement.expression.text))
+ continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives)
+ (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
+ }
+ return prologues;
+ }
function emitShebangIfNeeded(sourceFileOrBundle) {
- if (ts.isSourceFile(sourceFileOrBundle)) {
+ if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
var shebang = ts.getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -84533,11 +86054,18 @@
}
}
else {
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ ts.Debug.assertNode(prepend, ts.isUnparsedSource);
+ if (emitShebangIfNeeded(prepend)) {
+ return true;
+ }
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
// Emit only the first encountered shebang
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -84740,6 +86268,7 @@
}
// 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];
@@ -84760,6 +86289,7 @@
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write either a line terminator or whitespace to separate the elements.
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
// If a synthesized node in a single-line list starts on a new
@@ -84776,6 +86306,7 @@
}
}
// Emit this child.
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
var commentRange = ts.getCommentRange(child);
@@ -84810,6 +86341,7 @@
if (format & 128 /* Indented */) {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write the closing line terminator or closing whitespace.
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
writeLine();
@@ -84911,7 +86443,6 @@
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -85425,7 +86956,7 @@
hasWrittenComment = false;
var emitFlags = ts.getEmitFlags(node);
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 312 /* NotEmittedStatement */;
// We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
// It is expensive to walk entire tree just to set one kind of node to have no comments.
var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
@@ -85685,19 +87216,28 @@
return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
}
// Source Maps
+ function getParsedSourceMap(node) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
function pipelineEmitWithSourceMap(hint, node) {
var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node);
- if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
- var parsed = ts.tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath);
+ if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (ts.isUnparsedNode(node)) {
+ var parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
}
pipelinePhase(hint, node);
}
else {
var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
var emitFlags = ts.getEmitFlags(node);
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitSourcePos(source, skipSourceTrivia(source, pos));
@@ -85710,7 +87250,7 @@
else {
pipelinePhase(hint, node);
}
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitSourcePos(source, end);
@@ -85838,7 +87378,8 @@
writeFile: host.writeFile && writeFile,
addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
addOrDeleteFile: addOrDeleteFile,
- clearCache: clearCache
+ clearCache: clearCache,
+ realpath: host.realpath && realpath
};
function toPath(fileName) {
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
@@ -85935,7 +87476,7 @@
var rootDirPath = toPath(rootDir);
var result = tryReadDirectory(rootDir, rootDirPath);
if (result) {
- return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries);
+ return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
}
return host.readDirectory(rootDir, extensions, excludes, includes, depth);
function getFileSystemEntries(dir) {
@@ -85946,6 +87487,9 @@
return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
}
}
+ function realpath(s) {
+ return host.realpath ? host.realpath(s) : s;
+ }
function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
if (existingResult) {
@@ -86216,11 +87760,7 @@
function createCompilerHostWorker(options, setParentNodes, system) {
if (system === void 0) { system = ts.sys; }
var existingDirectories = ts.createMap();
- function getCanonicalFileName(fileName) {
- // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
- // otherwise use toLowerCase as a canonical form.
- return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
- }
+ var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
function getSourceFile(fileName, languageVersion, onError) {
var text;
try {
@@ -86345,20 +87885,21 @@
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value || undefined;
+ return value !== false ? value : undefined;
return setReadFileCache(key, fileName);
};
var setReadFileCache = function (key, fileName) {
var newValue = originalReadFile.call(host, fileName);
- readFileCache.set(key, newValue || false);
+ readFileCache.set(key, newValue !== undefined ? newValue : false);
return newValue;
};
host.readFile = function (fileName) {
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value; // could be .d.ts from output
- if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ return value !== false ? value : undefined; // could be .d.ts from output
+ // Cache json or buildInfo
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
@@ -86389,7 +87930,7 @@
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -86835,11 +88376,18 @@
if (rootNames.length) {
for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
var parsedRef = resolvedProjectReferences_1[_i];
- if (parsedRef) {
+ if (!parsedRef)
+ continue;
var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
if (out) {
- var dtsOutfile = ts.changeExtension(out, ".d.ts");
- processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ }
+ else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
+ for (var _a = 0, _b = parsedRef.commandLine.fileNames; _a < _b.length; _a++) {
+ var fileName = _b[_a];
+ if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(fileName)) {
+ processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ }
}
}
}
@@ -86887,8 +88435,8 @@
// not part of the new program.
if (oldProgram && host.onReleaseOldSourceFile) {
var oldSourceFiles = oldProgram.getSourceFiles();
- for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) {
- var oldSourceFile = oldSourceFiles_1[_a];
+ for (var _c = 0, oldSourceFiles_1 = oldSourceFiles; _c < oldSourceFiles_1.length; _c++) {
+ var oldSourceFile = oldSourceFiles_1[_c];
var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
if (shouldCreateNewSourceFile || !newFile ||
// old file wasnt redirect but new file is
@@ -86944,7 +88492,8 @@
getProjectReferenceRedirect: getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference: forEachResolvedProjectReference
+ forEachResolvedProjectReference: forEachResolvedProjectReference,
+ emitBuildInfo: emitBuildInfo
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -86973,7 +88522,7 @@
}
function getCommonSourceDirectory() {
if (commonSourceDirectory === undefined) {
- var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); });
+ var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
// If a rootDir is specified use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
@@ -87362,7 +88911,8 @@
}
function getEmitHost(writeFileCallback) {
return __assign({ getPrependNodes: getPrependNodes,
- getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) {
+ getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
+ getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) {
// Use local caches
var path = toPath(f);
if (getSourceFileByPath(path))
@@ -87371,7 +88921,20 @@
return false;
// Before falling back to the host
return host.fileExists(f);
- } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } });
+ } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
+ }
+ function emitBuildInfo(writeFileCallback) {
+ ts.Debug.assert(!options.out && !options.outFile);
+ ts.performance.mark("beforeEmit");
+ var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
+ /*targetSourceFile*/ undefined,
+ /*emitOnlyDtsFiles*/ false,
+ /*transformers*/ undefined,
+ /*declaraitonTransformers*/ undefined,
+ /*onlyBuildInfo*/ true);
+ ts.performance.mark("afterEmit");
+ ts.performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
}
function getResolvedProjectReferences() {
return resolvedProjectReferences;
@@ -87380,28 +88943,11 @@
return projectReferences;
}
function getPrependNodes() {
- if (!projectReferences) {
- return ts.emptyArray;
- }
- var nodes = [];
- for (var i = 0; i < projectReferences.length; i++) {
- var ref = projectReferences[i];
- var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
- if (!out)
- continue;
- var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- var node = ts.createInputFiles(function (fileName) {
+ return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
var path = toPath(fileName);
var sourceFile = getSourceFileByPath(path);
return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath);
- nodes.push(node);
- }
- }
- return nodes;
+ });
}
function isSourceFileFromExternalLibrary(file) {
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
@@ -87473,8 +89019,7 @@
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
ts.performance.mark("beforeEmit");
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217
- emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -88086,7 +89631,6 @@
if (refFile) {
var redirect = getProjectReferenceRedirect(fileName);
if (redirect) {
- (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName);
fileName = redirect;
// Once we start redirecting to a file, we can potentially come back to it
// via a back-reference from another file in the .d.ts folder. If that happens we'll
@@ -88183,7 +89727,7 @@
var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
return out ?
ts.changeExtension(out, ".d.ts" /* Dts */) :
- ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine);
+ ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
}
/**
* Get the referenced project if the file is input file from that reference project
@@ -88476,18 +90020,29 @@
if (options.declaration === false) {
createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+ if (options.tsBuildInfoFile) {
+ if (!ts.isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
// List of collected files is complete; validate exhautiveness if this is a project with a file list
if (options.composite) {
- var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; });
- if (rootNames.length < sourceFiles.length) {
- var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
- for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) {
- var file = _a[_i];
- if (normalizedRootNames.indexOf(file) === -1) {
- programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file));
- }
+ var rootPaths = rootNames.map(toPath);
+ for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
+ var file = files_3[_i];
+ // Ignore declaration files
+ if (file.isDeclarationFile)
+ continue;
+ // Ignore json file thats from project reference
+ if (ts.isJsonSourceFile(file) && getResolvedProjectReferenceToRedirect(file.fileName))
+ continue;
+ if (rootPaths.indexOf(file.path) === -1) {
+ programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file.fileName));
}
}
}
@@ -88670,6 +90225,7 @@
}
}
function verifyProjectReferences() {
+ var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
var parentFile = parent && parent.sourceFile;
@@ -88696,6 +90252,10 @@
createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
@@ -88840,11 +90400,32 @@
readFile: function (f) { return directoryStructureHost.readFile(f); },
useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
getCurrentDirectory: function () { return host.getCurrentDirectory(); },
- onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }),
+ onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
trace: host.trace ? function (s) { return host.trace(s); } : undefined
};
}
ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
+ /* @internal */
+ function createPrependNodes(projectReferences, getCommandLine, readFile) {
+ if (!projectReferences)
+ return ts.emptyArray;
+ var nodes;
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!out)
+ continue;
+ var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || ts.emptyArray;
+ }
+ ts.createPrependNodes = createPrependNodes;
function resolveProjectReferencePath(hostOrRef, ref) {
var passedInRef = ref ? ref : hostOrRef;
return ts.resolveConfigFileProjectName(passedInRef.path);
@@ -89041,7 +90622,7 @@
// Create the reference map, and set the file infos
for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- var version_1 = sourceFile.version;
+ var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined;
if (referencedMap) {
var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
@@ -89096,9 +90677,9 @@
*/
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 commited once it is safe to use them
+ // 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 commited only after the iteration through the result is complete
+ // In the other cases the affected files signatures are committed only after the iteration through the result is complete
var signatureCache = cacheToUpdateSignature || ts.createMap();
var sourceFile = programOfThisState.getSourceFileByPath(path);
if (!sourceFile) {
@@ -89388,11 +90969,14 @@
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(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ 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
- ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
+ if (changedFilesSet) {
+ ts.copyEntries(changedFilesSet, state.changedFilesSet);
+ }
if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
@@ -89430,7 +91014,7 @@
// Unchanged file copy diagnostics
var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = ts.createMap();
}
@@ -89438,8 +91022,45 @@
}
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ // Add all files to affectedFilesPendingEmit since emit changed
+ state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ ts.Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = ts.createMap();
+ }
return state;
}
+ function convertToDiagnostics(diagnostics, newProgram) {
+ if (!diagnostics.length)
+ return ts.emptyArray;
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram) });
+ }
+ function convertToDiagnosticMessageChain(diagnostic, newProgram) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
+ }
/**
* Releases program and other related not needed properties
*/
@@ -89659,8 +91280,11 @@
* This is called after completing operation on the next affected file.
* The operations here are postponed to ensure that cancellation during the iteration is handled correctly
*/
- function doneWithAffectedFile(state, affected, isPendingEmit) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -89677,8 +91301,8 @@
/**
* Returns the result with affected file
*/
- function toAffectedFileResult(state, result, affected, isPendingEmit) {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result: result, affected: affected };
}
/**
@@ -89701,6 +91325,77 @@
}
return diagnostics;
}
+ /**
+ * Gets the program information to be emitted in buildInfo so that we can use it to create new program
+ */
+ function getProgramBuildInfo(state) {
+ if (state.compilerOptions.outFile || state.compilerOptions.out)
+ return undefined;
+ var fileInfos = {};
+ state.fileInfos.forEach(function (value, key) {
+ var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
+ });
+ var result = { fileInfos: fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ var referencedMap_1 = {};
+ state.referencedMap.forEach(function (value, key) {
+ referencedMap_1[key] = ts.arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap_1;
+ }
+ if (state.exportedModulesMap) {
+ var exportedModulesMap_1 = {};
+ state.exportedModulesMap.forEach(function (value, key) {
+ var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ // Not in temporary cache, use existing value
+ if (newValue === undefined)
+ exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
+ // Value in cache and has updated value map, use that
+ else if (newValue)
+ exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap_1;
+ }
+ if (state.semanticDiagnosticsPerFile) {
+ var semanticDiagnosticsPerFile_1 = [];
+ // Currently not recording actual errors since those mean no emit for tsc --build
+ state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value :
+ convertToReusableDiagnostics(value)
+ ] :
+ key); });
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
+ }
+ return result;
+ }
+ function convertToReusableDiagnostics(diagnostics) {
+ ts.Debug.assert(!!diagnostics.length);
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToReusableDiagnosticRelatedInformation(diagnostic) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText) });
+ }
+ function convertToReusableDiagnosticMessageChain(diagnostic) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
+ }
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
@@ -89757,6 +91452,7 @@
var computeHash = host.createHash || ts.generateDjb2Hash;
var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
var backupState;
+ newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined; // TODO: GH#18217
oldProgram = undefined;
@@ -89800,8 +91496,17 @@
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
+ if (state.emittedBuildInfo) {
return undefined;
}
+ var affected_1 = ts.Debug.assertDefined(state.program);
+ return toAffectedFileResult(state,
+ // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
+ // Otherwise just affected file
+ affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1,
+ /*isPendingEmitFile*/ false,
+ /*isBuildInfoEmit*/ true);
+ }
isPendingEmitFile = true;
}
else {
@@ -89926,13 +91631,60 @@
}
var diagnostics;
for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile_2 = _a[_i];
- diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken));
+ var sourceFile_1 = _a[_i];
+ diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
}
return diagnostics || ts.emptyArray;
}
}
ts.createBuilderProgram = createBuilderProgram;
+ function getMapOfReferencedSet(mapLike) {
+ if (!mapLike)
+ return undefined;
+ var map = ts.createMap();
+ // Copies keys/values from template. Note that for..in will not throw if
+ // template is undefined, and instead will just exit the loop.
+ for (var key in mapLike) {
+ if (ts.hasProperty(mapLike, key)) {
+ map.set(key, ts.arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+ function createBuildProgramUsingProgramBuildInfo(program) {
+ var fileInfos = ts.createMapFromTemplate(program.fileInfos);
+ var state = {
+ fileInfos: fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: function () { return state; },
+ backupState: ts.noop,
+ restoreState: ts.noop,
+ getProgram: ts.notImplemented,
+ getProgramOrUndefined: ts.returnUndefined,
+ releaseProgram: ts.noop,
+ getCompilerOptions: function () { return state.compilerOptions; },
+ getSourceFile: ts.notImplemented,
+ getSourceFiles: ts.notImplemented,
+ getOptionsDiagnostics: ts.notImplemented,
+ getGlobalDiagnostics: ts.notImplemented,
+ getConfigFileParsingDiagnostics: ts.notImplemented,
+ getSyntacticDiagnostics: ts.notImplemented,
+ getDeclarationDiagnostics: ts.notImplemented,
+ getSemanticDiagnostics: ts.notImplemented,
+ emit: ts.notImplemented,
+ getAllDependencies: ts.notImplemented,
+ getCurrentDirectory: ts.notImplemented,
+ emitNextAffectedFile: ts.notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
+ };
+ }
+ ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
@@ -89952,7 +91704,7 @@
getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
getAllDependencies: ts.notImplemented,
- getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }
+ getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
};
function getProgram() {
return ts.Debug.assertDefined(state.program);
@@ -89978,10 +91730,10 @@
/*@internal*/
var ts;
(function (ts) {
- function isPathInNodeModulesStartingWithDot(path) {
- return ts.stringContains(path, "/node_modules/.");
+ function isPathIgnored(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
}
- ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot;
+ ts.isPathIgnored = isPathIgnored;
ts.maxNumberOfFilesToIterateForInvalidation = 256;
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
@@ -90503,7 +92255,7 @@
}
else {
// If something to do with folder/file starting with "." in node_modules folder, skip it
- if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (isPathIgnored(fileOrDirectoryPath))
return false;
// Some file or directory in the watching directory is created
// Return early if it does not have any of the watching extension or not the custom failed lookup path
@@ -90980,6 +92732,8 @@
case ".jsx" /* Jsx */:
case ".json" /* Json */:
return ext;
+ case ".tsbuildinfo" /* TsBuildInfo */:
+ return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
@@ -91100,22 +92854,18 @@
var diagnostics = program.getConfigFileParsingDiagnostics().slice();
var configFileParsingDiagnosticsLength = diagnostics.length;
ts.addRange(diagnostics, program.getSyntacticDiagnostics());
- var reportSemanticDiagnostics = false;
// If we didn't have any syntactic errors, then also try getting the global and
// semantic errors.
if (diagnostics.length === configFileParsingDiagnosticsLength) {
ts.addRange(diagnostics, program.getOptionsDiagnostics());
ts.addRange(diagnostics, program.getGlobalDiagnostics());
if (diagnostics.length === configFileParsingDiagnosticsLength) {
- reportSemanticDiagnostics = true;
+ ts.addRange(diagnostics, program.getSemanticDiagnostics());
}
}
// Emit and report any errors we ran into.
var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics;
ts.addRange(diagnostics, emitDiagnostics);
- if (reportSemanticDiagnostics) {
- ts.addRange(diagnostics, program.getSemanticDiagnostics());
- }
ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic);
if (writeFileName) {
var currentDir_1 = program.getCurrentDirectory();
@@ -91236,6 +92986,22 @@
}
}
ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
+ function setGetSourceFileAsHashVersioned(compilerHost, host) {
+ var originalGetSourceFile = compilerHost.getSourceFile;
+ var computeHash = host.createHash || ts.generateDjb2Hash;
+ compilerHost.getSourceFile = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+ }
+ ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
/**
* Creates the watch compiler host that can be extended with config file or root file names and options host
*/
@@ -91261,7 +93027,7 @@
writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
createHash: ts.maybeBind(system, system.createHash),
- createProgram: createProgram
+ createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
@@ -91271,7 +93037,7 @@
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram);
+ var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
@@ -91310,6 +93076,49 @@
return host;
}
ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
+ function readBuilderProgram(compilerOptions, readFile) {
+ if (compilerOptions.out || compilerOptions.outFile)
+ return undefined;
+ var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions);
+ if (!buildInfoPath)
+ return undefined;
+ var content = readFile(buildInfoPath);
+ if (!content)
+ return undefined;
+ var buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.version !== ts.version)
+ return undefined;
+ if (!buildInfo.program)
+ return undefined;
+ return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
+ }
+ ts.readBuilderProgram = readBuilderProgram;
+ function createIncrementalCompilerHost(options, system) {
+ if (system === void 0) { system = ts.sys; }
+ var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
+ host.createHash = ts.maybeBind(system, system.createHash);
+ setGetSourceFileAsHashVersioned(host, system);
+ ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
+ return host;
+ }
+ ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
+ function createIncrementalProgram(_a) {
+ var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
+ host = host || createIncrementalCompilerHost(options);
+ createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
+ var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); });
+ return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
+ }
+ function performIncrementalCompilation(input) {
+ var system = input.system || ts.sys;
+ var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system));
+ var builderProgram = createIncrementalProgram(input);
+ var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined);
+ if (input.afterProgramEmitAndDiagnostics)
+ input.afterProgramEmitAndDiagnostics(builderProgram);
+ return exitStatus;
+ }
+ ts.performIncrementalCompilation = performIncrementalCompilation;
})(ts || (ts = {}));
(function (ts) {
function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) {
@@ -91321,7 +93130,6 @@
}
}
ts.createWatchCompilerHost = createWatchCompilerHost;
- var initialVersion = 1;
function createWatchProgram(host) {
var builderProgram;
var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
@@ -91362,10 +93170,12 @@
var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
+ var configFileWatcher;
if (configFileName) {
- watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */);
+ configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */);
}
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
// Members for CompilerHost
var getNewSourceFile = compilerHost.getSourceFile;
compilerHost.getSourceFile = function (fileName) {
@@ -91406,21 +93216,43 @@
(function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) :
(function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
+ builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); });
synchronizeProgram();
// Update the wild card directory watch
watchConfigFileWildCardDirectories();
return configFileName ?
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } :
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames };
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } :
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close };
+ function close() {
+ resolutionCache.clear();
+ ts.clearMap(sourceFilesCache, function (value) {
+ if (value && value.fileWatcher) {
+ value.fileWatcher.close();
+ value.fileWatcher = undefined;
+ }
+ });
+ if (configFileWatcher) {
+ configFileWatcher.close();
+ configFileWatcher = undefined;
+ }
+ if (watchedWildcardDirectories) {
+ ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
+ watchedWildcardDirectories = undefined;
+ }
+ if (missingFilesMap) {
+ ts.clearMap(missingFilesMap, ts.closeFileWatcher);
+ missingFilesMap = undefined;
+ }
+ }
function getCurrentBuilderProgram() {
return builderProgram;
}
function getCurrentProgram() {
- return builderProgram && builderProgram.getProgram();
+ return builderProgram && builderProgram.getProgramOrUndefined();
}
function synchronizeProgram() {
writeLog("Synchronizing program");
- var program = getCurrentProgram();
+ var program = getCurrentBuilderProgram();
if (hasChangedCompilerOptions) {
newLine = updateNewLine();
if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
@@ -91436,19 +93268,19 @@
}
}
else {
- createNewProgram(program, hasInvalidatedResolution);
+ createNewProgram(hasInvalidatedResolution);
}
if (host.afterProgramCreate) {
host.afterProgramCreate(builderProgram);
}
return builderProgram;
}
- function createNewProgram(program, hasInvalidatedResolution) {
+ function createNewProgram(hasInvalidatedResolution) {
// Compile the program
writeLog("CreatingProgramWith::");
writeLog(" roots: " + JSON.stringify(rootFileNames));
writeLog(" options: " + JSON.stringify(compilerOptions));
- var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program;
+ var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
hasChangedCompilerOptions = false;
hasChangedConfigFileParsingErrors = false;
resolutionCache.startCachingPerDirectoryResolution();
@@ -91488,10 +93320,10 @@
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
}
function isFileMissingOnHost(hostSourceFile) {
- return typeof hostSourceFile === "number";
+ return typeof hostSourceFile === "boolean";
}
- function isFilePresentOnHost(hostSourceFile) {
- return !!hostSourceFile.sourceFile;
+ function isFilePresenceUnknownOnHost(hostSourceFile) {
+ return typeof hostSourceFile.version === "boolean";
}
function fileExists(fileName) {
var path = toPath(fileName);
@@ -91509,36 +93341,32 @@
return undefined;
}
// Create new source file if requested or the versions dont match
- if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) {
+ if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
if (hostSourceFile) {
- if (shouldCreateNewSourceFile) {
- hostSourceFile.version++;
- }
if (sourceFile) {
// Set the source file and create file watcher now that file was present on the disk
hostSourceFile.sourceFile = sourceFile;
- sourceFile.version = hostSourceFile.version.toString();
+ hostSourceFile.version = sourceFile.version;
if (!hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
}
}
else {
// There is no source file on host any more, close the watch, missing file paths will track it
- if (isFilePresentOnHost(hostSourceFile)) {
+ if (hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher.close();
}
- sourceFilesCache.set(path, hostSourceFile.version);
+ sourceFilesCache.set(path, false);
}
}
else {
if (sourceFile) {
- sourceFile.version = initialVersion.toString();
var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
- sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher });
+ sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
}
else {
- sourceFilesCache.set(path, initialVersion);
+ sourceFilesCache.set(path, false);
}
}
return sourceFile;
@@ -91550,16 +93378,16 @@
if (hostSourceFile !== undefined) {
if (isFileMissingOnHost(hostSourceFile)) {
// The next version, lets set it as presence unknown file
- sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 });
+ sourceFilesCache.set(path, { version: false });
}
else {
- hostSourceFile.version++;
+ hostSourceFile.version = false;
}
}
}
function getSourceVersion(path) {
var hostSourceFile = sourceFilesCache.get(path);
- return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString();
+ return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
}
function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
@@ -91567,7 +93395,7 @@
// remove the cached entry.
// Note we arent deleting entry if file became missing in new program or
// there was version update and new source file was created.
- if (hostSourceFileInfo) {
+ if (hostSourceFileInfo !== undefined) {
// record the missing file paths so they can be removed later if watchers arent tracking them
if (isFileMissingOnHost(hostSourceFileInfo)) {
(missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
@@ -91656,7 +93484,7 @@
function onSourceFileChange(fileName, eventKind, path) {
updateCachedSystemWithFile(fileName, path, eventKind);
// Update the source file cache
- if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) {
+ if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
resolutionCache.invalidateResolutionOfFile(path);
}
resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
@@ -91700,7 +93528,7 @@
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
// If the the added or created file or directory is not supported file name, ignore the file
// But when watched directory is added/removed, we need to reload the file list
@@ -91754,16 +93582,23 @@
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
*/
UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
- UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
- UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
- UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
- UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
+ /**
+ * The project appears out of date because its upstream inputs are newer than its outputs,
+ * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
+ * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
+ */
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
+ 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";
/**
* Projects with no outputs (i.e. "solution" files)
*/
- UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
+ UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
})(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
function createFileMap(toPath) {
// tslint:disable-next-line:no-null-keyword
@@ -91811,61 +93646,6 @@
function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
}
- function getOutputDeclarationFileName(inputFileName, configFile) {
- var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true);
- var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath);
- return ts.changeExtension(outputPath, ".d.ts" /* Dts */);
- }
- ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
- function getOutputJSFileName(inputFileName, configFile) {
- var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true);
- var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath);
- var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ :
- ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
- return ts.changeExtension(outputPath, newExtension);
- }
- function getOutputFileNames(inputFileName, configFile) {
- // outFile is handled elsewhere; .d.ts files don't generate outputs
- if (configFile.options.outFile || configFile.options.out || ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */)) {
- return ts.emptyArray;
- }
- var outputs = [];
- var js = getOutputJSFileName(inputFileName, configFile);
- outputs.push(js);
- if (configFile.options.sourceMap) {
- outputs.push(js + ".map");
- }
- if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) {
- var dts = getOutputDeclarationFileName(inputFileName, configFile);
- outputs.push(dts);
- if (configFile.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
- }
- function getOutFileOutputs(project) {
- var out = project.options.outFile || project.options.out;
- if (!out) {
- return ts.Debug.fail("outFile must be set");
- }
- var outputs = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(out + ".map");
- }
- if (ts.getEmitDeclarations(project.options)) {
- var dts = ts.changeExtension(out, ".d.ts" /* Dts */);
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
- }
- function rootDirOfOptions(opts, configFileName) {
- return opts.rootDir || ts.getDirectoryPath(configFileName);
- }
function newer(date1, date2) {
return date2 > date1 ? date2 : date1;
}
@@ -91885,7 +93665,7 @@
ts.createBuilderStatusReporter = createBuilderStatusReporter;
function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
var host = ts.createProgramHost(system, createProgram);
- host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; };
+ host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
@@ -91894,14 +93674,14 @@
}
function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
host.reportErrorSummary = reportErrorSummary;
return host;
}
ts.createSolutionBuilderHost = createSolutionBuilderHost;
function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
var watchHost = ts.createWatchHost(system, reportWatchStatus);
ts.copyProperties(host, watchHost);
return host;
@@ -91933,9 +93713,8 @@
var readFileWithCache = function (f) { return host.readFile(f); };
var projectCompilerOptions = baseCompilerOptions;
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
- var originalGetSourceFile = compilerHost.getSourceFile;
- var computeHash = host.createHash || ts.generateDjb2Hash;
- updateGetSourceFile();
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
+ var buildInfoChecked = createFileMap(toPath);
// Watch state
var builderPrograms = createFileMap(toPath);
var diagnostics = createFileMap(toPath);
@@ -91973,6 +93752,7 @@
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
projectErrorsReported.clear();
@@ -91987,29 +93767,6 @@
ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry) {
return !!entry.options;
@@ -92160,13 +93917,14 @@
newestInputFileTime = inputTime;
}
}
- // Collect the expected outputs of this project
- var outputs = getAllProjectOutputs(project);
- if (outputs.length === 0) {
+ // Container if no files are specified in the project
+ if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
return {
type: 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;
@@ -92241,6 +93999,8 @@
upstreamProjectName: ref.path
};
}
+ // Check oldest output file name only if there is no missing output file name
+ if (!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) {
@@ -92262,6 +94022,7 @@
};
}
}
+ }
if (missingOutputFileName !== undefined) {
return {
type: UpToDateStatusType.OutputMissing,
@@ -92275,9 +94036,33 @@
newerInputFileName: newestInputFileName
};
}
+ else {
+ // Check tsconfig time
+ var configStatus = checkConfigFileUpToDateStatus(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(configFile, oldestOutputFileTime, oldestOutputFileName); });
+ if (extendedConfigStatus)
+ return extendedConfigStatus;
+ }
+ if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
+ buildInfoChecked.setValue(project.options.configFilePath, true);
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ var value = readFileWithCache(buildInfoPath);
+ var buildInfo = value && ts.getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== ts.version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject
};
@@ -92293,6 +94078,17 @@
oldestOutputFileName: oldestOutputFileName
};
}
+ function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) {
+ // Check tsconfig time
+ var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
+ if (oldestOutputFileTime < tsconfigTime) {
+ return {
+ type: UpToDateStatusType.OutOfDateWithSelf,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerInputFileName: configFile
+ };
+ }
+ }
function invalidateProject(configFileName, reloadLevel) {
invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel);
}
@@ -92411,7 +94207,9 @@
updateOutputTimestamps(proj);
return;
}
- var buildResult = buildSingleProject(resolved);
+ var buildResult = needsBuild(status, resolved) ?
+ buildSingleProject(resolved) : // Actual build
+ updateBundle(resolved); // Fake that files have been built by manipulating prepend and existing output
if (buildResult & BuildResultFlags.AnyErrors)
return;
var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
@@ -92427,18 +94225,27 @@
// If declaration output is changed, build the project
// otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
var status_1 = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status_1.oldestOutputFileName,
+ outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status_1.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
}
+ }
addProjToQueue(project);
}
}
@@ -92494,8 +94301,7 @@
}
if (options.verbose)
reportStatus(ts.Diagnostics.Building_project_0, proj);
- var resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
var configFile = parseConfigFile(proj);
if (!configFile) {
// Failed to read the config file
@@ -92511,8 +94317,7 @@
}
// TODO: handle resolve module name to cache result in project reference redirect
projectCompilerOptions = configFile.options;
- var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences);
- projectCompilerOptions = baseCompilerOptions;
+ var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
@@ -92568,17 +94373,19 @@
var status = {
type: UpToDateStatusType.UpToDate,
newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime,
- oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile)
+ oldestOutputFileName: outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(configFile, !host.useCaseSensitiveFileNames())
};
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -92591,15 +94398,71 @@
builderPrograms.setValue(proj, program);
}
}
+ function getOldProgram(proj, parsed) {
+ if (options.force)
+ return undefined;
+ var value = builderPrograms.getValue(proj);
+ if (value)
+ return value;
+ return ts.readBuilderProgram(parsed.options, readFileWithCache);
+ }
+ function updateBundle(proj) {
+ if (options.dry) {
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+ if (options.verbose)
+ reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
+ // Update js, and source map
+ var config = ts.Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
+ if (ts.isString(outputFiles)) {
+ reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+ // Actual Emit
+ ts.Debug.assert(!!outputFiles.length);
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ var emittedOutputs = createFileMap(toPath);
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
+ emittedOutputs.setValue(name, true);
+ ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+ // Update timestamps for dts
+ var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
function updateOutputTimestamps(proj) {
if (options.dry) {
- return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
}
var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
- projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
+ oldestOutputFileName: ts.getFirstProjectOutput(proj, !host.useCaseSensitiveFileNames())
+ };
+ projectStatus.setValue(proj.options.configFilePath, status);
}
function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
- var outputs = getAllProjectOutputs(proj);
+ var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
if (!skipOutputs || outputs.length !== skipOutputs.getSize()) {
if (options.verbose) {
reportStatus(verboseMessage, proj.options.configFilePath);
@@ -92633,7 +94496,7 @@
reportParseConfigFileDiagnostic(proj);
continue;
}
- var outputs = getAllProjectOutputs(parsed);
+ var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) {
var output = outputs_3[_b];
if (host.fileExists(output)) {
@@ -92720,7 +94583,9 @@
// Do nothing
continue;
}
- var buildResult = buildSingleProject(next);
+ var buildResult = needsBuild(status, next) ?
+ buildSingleProject(next) : // Actual build
+ updateBundle(next); // Fake that files have been built by manipulating prepend and existing output
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -92733,6 +94598,15 @@
readFileWithCache = savedReadFileWithCache;
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
+ function needsBuild(status, configFile) {
+ if (status.type !== UpToDateStatusType.OutOfDateWithPrepend || options.force)
+ return true;
+ var config = parseConfigFile(configFile);
+ return !config ||
+ config.fileNames.length === 0 ||
+ !!config.errors.length ||
+ !ts.isIncrementalCompilation(config.options);
+ }
function reportParseConfigFileDiagnostic(proj) {
reportAndStoreErrors(proj, [configFileCache.getValue(proj)]);
}
@@ -92772,33 +94646,6 @@
return ts.combinePaths(project, "tsconfig.json");
}
ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
- function getAllProjectOutputs(project) {
- if (project.options.outFile || project.options.out) {
- return getOutFileOutputs(project);
- }
- else {
- var outputs = [];
- for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
- var inputFile = _a[_i];
- outputs.push.apply(outputs, getOutputFileNames(inputFile, project));
- }
- return outputs;
- }
- }
- ts.getAllProjectOutputs = getAllProjectOutputs;
- function getFirstProjectOutput(project) {
- if (project.options.outFile || project.options.out) {
- return ts.first(getOutFileOutputs(project));
- }
- for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
- var inputFile = _a[_i];
- var outputs = getOutputFileNames(inputFile, project);
- if (outputs.length) {
- return ts.first(outputs);
- }
- }
- return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output");
- }
function formatUpToDateStatus(configFileName, status, relName, formatMessage) {
switch (status.type) {
case UpToDateStatusType.OutOfDateWithSelf:
@@ -92813,6 +94660,8 @@
}
// Don't report anything for "up to date because it was already built" -- too verbose
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
case UpToDateStatusType.UpToDateWithUpstreamTypes:
return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName));
case UpToDateStatusType.UpstreamOutOfDate:
@@ -92821,6 +94670,8 @@
return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName));
case UpToDateStatusType.Unbuildable:
return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason);
+ case UpToDateStatusType.TsVersionOutputOfDate:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
case UpToDateStatusType.ContainerOnly:
// Don't report status on "solution" projects
case UpToDateStatusType.ComputingUpstream:
@@ -92970,32 +94821,6 @@
}
}
})(ts || (ts = {}));
-//# sourceMappingURL=compiler.js.map
-"use strict";
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-var __extends = (this && this.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
-})();
var ts;
(function (ts) {
var ScriptSnapshot;
@@ -93278,7 +95103,7 @@
/* @internal */
var ts;
(function (ts) {
- ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
+ ts.scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true);
var SemanticMeaning;
(function (SemanticMeaning) {
SemanticMeaning[SemanticMeaning["None"] = 0] = "None";
@@ -93313,7 +95138,7 @@
case 242 /* TypeAliasDeclaration */:
case 168 /* TypeLiteral */:
return 2 /* Type */;
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
// If it has no name node, it shares the name with the value declaration below it.
return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */;
case 278 /* EnumMember */:
@@ -93338,14 +95163,14 @@
case 255 /* ExportDeclaration */:
return 7 /* All */;
// An external module can be a Value
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 4 /* Namespace */ | 1 /* Value */;
}
return 7 /* All */;
}
ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
function getMeaningFromLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return 1 /* Value */;
}
else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) {
@@ -93551,7 +95376,7 @@
return undefined;
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 239 /* FunctionDeclaration */:
@@ -93569,7 +95394,7 @@
ts.getContainerNode = getContainerNode;
function getNodeKind(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
case 244 /* ModuleDeclaration */:
return "module" /* moduleElement */;
@@ -93578,8 +95403,8 @@
return "class" /* classElement */;
case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
case 242 /* TypeAliasDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return "type" /* typeElement */;
case 243 /* EnumDeclaration */: return "enum" /* enumElement */;
case 237 /* VariableDeclaration */:
@@ -94005,7 +95830,7 @@
}
}
}
- ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
+ ts.Debug.assert(startNode !== undefined || n.kind === 284 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
// Here we know that none of child token nodes embrace the position,
// the only known case is when position is at the end of the file.
// Try to find the rightmost token in the file without filtering.
@@ -94092,7 +95917,7 @@
}
ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute;
function isWhiteSpaceOnlyJsxText(node) {
- return ts.isJsxText(node) && node.containsOnlyWhiteSpaces;
+ return ts.isJsxText(node) && node.containsOnlyTriviaWhiteSpaces;
}
function isInTemplateString(sourceFile, position) {
var token = getTokenAtPosition(sourceFile, position);
@@ -94852,6 +96677,17 @@
return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName));
}
ts.getScriptKind = getScriptKind;
+ function getSymbolTarget(symbol) {
+ var next = symbol;
+ while (isTransientSymbol(next) && next.target) {
+ next = next.target;
+ }
+ return next;
+ }
+ ts.getSymbolTarget = getSymbolTarget;
+ function isTransientSymbol(symbol) {
+ return (symbol.flags & 33554432 /* Transient */) !== 0;
+ }
function getUniqueSymbolId(symbol, checker) {
return ts.getSymbolId(ts.skipAlias(symbol, checker));
}
@@ -95003,8 +96839,27 @@
return lastPos;
}
ts.getRenameLocation = getRenameLocation;
- function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
- ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
+ function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyLeadingComments = copyLeadingComments;
+ function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment));
+ }
+ ts.copyTrailingComments = copyTrailingComments;
+ /**
+ * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`.
+ * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the
+ * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.:
+ * `function foo(\* not leading comment for a *\ a: string) {}`
+ * The comment refers to `a` but belongs to the `(` token, but we might want to copy it.
+ */
+ function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyTrailingAsLeadingComments = copyTrailingAsLeadingComments;
+ function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
+ return function (pos, end, kind, htnl) {
if (kind === 3 /* MultiLineCommentTrivia */) {
// Remove leading /*
pos += 2;
@@ -95015,10 +96870,9 @@
// Remove leading //
pos += 2;
}
- ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
- });
+ cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
+ };
}
- ts.copyComments = copyComments;
function indexInTextChange(change, name) {
if (ts.startsWith(change, name))
return 0;
@@ -95099,11 +96953,35 @@
return checker.getTypeAtLocation(caseClause.parent.parent.expression);
}
ts.getSwitchedType = getSwitchedType;
+ function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
+ var checker = program.getTypeChecker();
+ var typeIsAccessible = true;
+ var notAccessible = function () { typeIsAccessible = false; };
+ var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
+ trackSymbol: function (symbol, declaration, meaning) {
+ // TODO: GH#18217
+ typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
+ },
+ reportInaccessibleThisError: notAccessible,
+ reportPrivateInBaseOfClassExpression: notAccessible,
+ reportInaccessibleUniqueSymbolError: notAccessible,
+ moduleResolverHost: {
+ readFile: host.readFile,
+ fileExists: host.fileExists,
+ directoryExists: host.directoryExists,
+ getSourceFiles: program.getSourceFiles,
+ getCurrentDirectory: program.getCurrentDirectory,
+ getCommonSourceDirectory: program.getCommonSourceDirectory,
+ }
+ });
+ return typeIsAccessible ? res : undefined;
+ }
+ ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible;
})(ts || (ts = {}));
var ts;
(function (ts) {
function createClassifier() {
- var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false);
+ var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false);
function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) {
return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text);
}
@@ -95657,8 +97535,8 @@
var spanStart = span.start;
var spanLength = span.length;
// Make a scanner we can get trivia from.
- var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
- var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
+ var triviaScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
+ var mergeConflictScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
var result = [];
processElement(sourceFile);
return { spans: result, endOfLineState: 0 /* None */ };
@@ -95750,18 +97628,18 @@
pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
pos = tag.tagName.end;
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
pos = tag.end;
break;
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
@@ -96014,7 +97892,7 @@
return convertPathCompletions(completion.paths);
case 1 /* Properties */: {
var entries = [];
- Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
+ Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 7 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries };
}
case 2 /* Types */: {
@@ -96065,6 +97943,7 @@
case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */;
case ".ts" /* Ts */: return ".ts" /* tsModifier */;
case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */;
+ case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported.");
case undefined: return "" /* none */;
default:
return ts.Debug.assertNever(extension);
@@ -96592,7 +98471,7 @@
var offset = index !== -1 ? index + 1 : 0;
// If the range is an identifier, span is unnecessary.
var length = text.length - offset;
- return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
+ return length === 0 || ts.isIdentifierText(text.substr(offset, length), 7 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
}
// Returns true if the path is explicitly relative to the script (i.e. relative to . or ..)
function isPathRelativeToScript(path) {
@@ -96677,6 +98556,7 @@
KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords";
KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords";
KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords";
+ KeywordCompletionFilters[KeywordCompletionFilters["Last"] = 6] = "Last";
})(KeywordCompletionFilters || (KeywordCompletionFilters = {}));
var GlobalsSearch;
(function (GlobalsSearch) {
@@ -96722,7 +98602,7 @@
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
}
function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) {
- var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer;
+ var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression;
if (location && location.parent && ts.isJsxClosingElement(location.parent)) {
// In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag,
// instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element.
@@ -96753,7 +98633,7 @@
}
if (keywordFilters !== 0 /* None */) {
var entryNames = ts.arrayToSet(entries, function (e) { return e.name; });
- for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) {
var keywordEntry = _a[_i];
if (!entryNames.has(keywordEntry.name)) {
entries.push(keywordEntry);
@@ -97089,7 +98969,7 @@
return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
}
function isModuleSymbol(symbol) {
- return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; });
+ return symbol.declarations.some(function (d) { return d.kind === 284 /* SourceFile */; });
}
function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) {
var typeChecker = program.getTypeChecker();
@@ -97140,11 +99020,11 @@
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
currentToken = ts.getTokenAtPosition(sourceFile, position);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 310 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -97197,6 +99077,14 @@
case 189 /* PropertyAccessExpression */:
propertyAccessToConvert = parent;
node = propertyAccessToConvert.expression;
+ if (node.end === contextToken.pos &&
+ ts.isCallExpression(node) &&
+ node.getChildCount(sourceFile) &&
+ ts.last(node.getChildren(sourceFile)).kind !== 21 /* CloseParenToken */) {
+ // This is likely dot from incorrectly parsed call expression and user is starting to write spread
+ // eg: Math.min(./**/)
+ return undefined;
+ }
break;
case 148 /* QualifiedName */:
node = parent.left;
@@ -97312,14 +99200,29 @@
var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker);
var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; });
var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker);
- return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
+ return {
+ kind: 0 /* Data */,
+ symbols: symbols,
+ completionKind: completionKind,
+ isInSnippetScope: isInSnippetScope,
+ propertyAccessToConvert: propertyAccessToConvert,
+ isNewIdentifierLocation: isNewIdentifierLocation,
+ location: location,
+ keywordFilters: keywordFilters,
+ literals: literals,
+ symbolToOriginInfoMap: symbolToOriginInfoMap,
+ recommendedCompletion: recommendedCompletion,
+ previousToken: previousToken,
+ isJsxInitializer: isJsxInitializer,
+ insideJsDocTagTypeExpression: insideJsDocTagTypeExpression
+ };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 304 /* JSDocTypedefTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 309 /* JSDocTypedefTag */:
return true;
default:
return false;
@@ -97359,7 +99262,9 @@
}
}
// If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods).
- if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
+ if (!isTypeLocation &&
+ symbol.declarations &&
+ symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node));
}
return;
@@ -97492,8 +99397,8 @@
var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
- if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) {
- var thisType = typeChecker.tryGetThisTypeAt(scopeNode);
+ if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 284 /* SourceFile */) {
+ var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false);
if (thisType) {
for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) {
var symbol = _a[_i];
@@ -97525,7 +99430,7 @@
}
function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 206 /* TemplateExpression */:
case 270 /* JsxExpression */:
case 218 /* Block */:
@@ -97584,6 +99489,8 @@
return parentKind === 242 /* TypeAliasDeclaration */;
case 119 /* AsKeyword */:
return parentKind === 212 /* AsExpression */;
+ case 86 /* ExtendsKeyword */:
+ return parentKind === 150 /* TypeParameter */;
}
}
return false;
@@ -98280,7 +100187,15 @@
}
return res;
});
- function getKeywordCompletions(keywordFilter) {
+ function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) {
+ if (!filterOutTsOnlyKeywords)
+ return getTypescriptKeywordCompletions(keywordFilter);
+ var index = keywordFilter + 6 /* Last */ + 1;
+ return _keywordCompletions[index] ||
+ (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter)
+ .filter(function (entry) { return !isTypeScriptOnlyKeyword(ts.stringToToken(entry.name)); }));
+ }
+ function getTypescriptKeywordCompletions(keywordFilter) {
return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) {
var kind = ts.stringToToken(entry.name);
switch (keywordFilter) {
@@ -98304,6 +100219,39 @@
}
}));
}
+ function isTypeScriptOnlyKeyword(kind) {
+ switch (kind) {
+ case 118 /* AbstractKeyword */:
+ case 120 /* AnyKeyword */:
+ case 146 /* BigIntKeyword */:
+ case 123 /* BooleanKeyword */:
+ case 125 /* DeclareKeyword */:
+ case 84 /* EnumKeyword */:
+ case 145 /* GlobalKeyword */:
+ case 109 /* ImplementsKeyword */:
+ case 127 /* InferKeyword */:
+ case 110 /* InterfaceKeyword */:
+ case 128 /* IsKeyword */:
+ case 129 /* KeyOfKeyword */:
+ case 130 /* ModuleKeyword */:
+ case 131 /* NamespaceKeyword */:
+ case 132 /* NeverKeyword */:
+ case 135 /* NumberKeyword */:
+ case 136 /* ObjectKeyword */:
+ case 113 /* PrivateKeyword */:
+ case 114 /* ProtectedKeyword */:
+ case 115 /* PublicKeyword */:
+ case 133 /* ReadonlyKeyword */:
+ case 138 /* StringKeyword */:
+ case 139 /* SymbolKeyword */:
+ case 140 /* TypeKeyword */:
+ case 142 /* UniqueKeyword */:
+ case 143 /* UnknownKeyword */:
+ return true;
+ default:
+ return false;
+ }
+ }
function isInterfaceOrTypeLiteralCompletionKeyword(kind) {
return kind === 133 /* ReadonlyKeyword */;
}
@@ -98357,7 +100305,7 @@
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 306 /* SyntaxList */:
+ case 311 /* SyntaxList */:
return ts.tryCast(location.parent, ts.isObjectTypeDeclaration);
case 1 /* EndOfFileToken */:
var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration);
@@ -98542,7 +100490,7 @@
var child = throwStatement;
while (child.parent) {
var parent = child.parent;
- if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) {
+ if (ts.isFunctionBlock(parent) || parent.kind === 284 /* SourceFile */) {
return parent;
}
// A throw-statement is only owned by a try-statement if the try-statement has
@@ -98600,7 +100548,7 @@
var container = declaration.parent;
switch (container.kind) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 271 /* CaseClause */:
case 272 /* DefaultClause */:
@@ -99098,7 +101046,7 @@
}
else if (!isAvailableThroughGlobal) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
- ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
+ ts.Debug.assert(sourceFileLike.kind === 284 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
addIndirectUsers(sourceFileLike);
}
@@ -99207,7 +101155,7 @@
}
}
/**
- * `import x = require("./x") or `import * as x from "./x"`.
+ * `import x = require("./x")` or `import * as x from "./x"`.
* An `export =` may be imported by this syntax, so it may be a direct import.
* If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here.
*/
@@ -99267,7 +101215,7 @@
for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
var referencingFile = sourceFiles_1[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
- if (searchSourceFile.kind === 279 /* SourceFile */) {
+ if (searchSourceFile.kind === 284 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
var ref = _b[_a];
if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
@@ -99315,7 +101263,7 @@
}
/** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */
function forEachPossibleImportOrExportStatement(sourceFileLike, action) {
- return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
+ return ts.forEach(sourceFileLike.kind === 284 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
});
}
@@ -99539,7 +101487,7 @@
return node.getSourceFile();
}
var parent = node.parent;
- if (parent.kind === 279 /* SourceFile */) {
+ if (parent.kind === 284 /* SourceFile */) {
return parent;
}
ts.Debug.assert(parent.kind === 245 /* ModuleBlock */);
@@ -99601,7 +101549,7 @@
}
FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return undefined;
}
var checker = program.getTypeChecker();
@@ -99821,8 +101769,8 @@
case 248 /* ImportEqualsDeclaration */:
case 253 /* ImportSpecifier */:
case 241 /* InterfaceDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
case 267 /* JsxAttribute */:
case 244 /* ModuleDeclaration */:
case 247 /* NamespaceExportDeclaration */:
@@ -99847,8 +101795,8 @@
return !!decl.initializer || ts.isCatchClause(decl.parent);
case 155 /* MethodSignature */:
case 153 /* PropertySignature */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
return false;
default:
return ts.Debug.failBadSyntaxKind(decl);
@@ -100008,7 +101956,7 @@
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
switch (decl.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.)
break;
case 244 /* ModuleDeclaration */:
@@ -100081,11 +102029,16 @@
}
else {
var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] });
+ getReferencesInContainerOrFiles(symbol, state, search);
+ }
+ return result;
+ }
+ function getReferencesInContainerOrFiles(symbol, state, search) {
// Try to get the smallest valid scope that we can limit our search to;
// otherwise we'll need to search globally (i.e. include each file).
var scope = getSymbolScope(symbol);
if (scope) {
- getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope)));
+ getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(state.sourceFiles, scope)));
}
else {
// Global search
@@ -100096,8 +102049,6 @@
}
}
}
- return result;
- }
function getSpecialSearchKind(node) {
switch (node.kind) {
case 124 /* ConstructorKeyword */:
@@ -100149,9 +102100,7 @@
* Unlike `Search`, there is only one `State`.
*/
var State = /** @class */ (function () {
- function State(sourceFiles, sourceFilesSet,
- /** True if we're searching for constructor references. */
- specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
+ function State(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
this.sourceFiles = sourceFiles;
this.sourceFilesSet = sourceFilesSet;
this.specialSearchKind = specialSearchKind;
@@ -100379,7 +102328,7 @@
// Different declarations have different containers, bail out
return undefined;
}
- if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
+ if (!container || container.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
// This is a global variable and not an external module, any declaration defined
// within this scope is visible outside the file
return undefined;
@@ -100466,8 +102415,8 @@
// We found a match. Make sure it's not part of a larger word (i.e. the char
// before and after it have to be a non-identifier char).
var endPosition = position + symbolNameLength;
- if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) &&
- (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) {
+ if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 7 /* Latest */)) &&
+ (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 7 /* Latest */))) {
// Found a real match. Keep searching.
positions.push(position);
}
@@ -100616,7 +102565,9 @@
}
// For `export { foo as bar }`, rename `foo`, but not `bar`.
if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) {
- var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */;
+ var isDefaultExport = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */
+ || exportSpecifier.name.originalKeywordKind === 80 /* DefaultKeyword */;
+ var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */;
var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol);
var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker));
searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
@@ -100703,6 +102654,7 @@
var classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
if (classExtending) {
findSuperConstructorAccesses(classExtending, pusher());
+ findInheritedConstructorReferences(classExtending, state);
}
}
}
@@ -100735,12 +102687,16 @@
* Reference the constructor and all calls to `new this()`.
*/
function findOwnConstructorReferences(classSymbol, sourceFile, addNode) {
- for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) {
+ var constructorSymbol = getClassConstructorSymbol(classSymbol);
+ if (constructorSymbol) {
+ for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile);
ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword);
addNode(ctrKeyword);
}
+ }
+ if (classSymbol.exports) {
classSymbol.exports.forEach(function (member) {
var decl = member.valueDeclaration;
if (decl && decl.kind === 156 /* MethodDeclaration */) {
@@ -100755,13 +102711,17 @@
}
});
}
+ }
+ function getClassConstructorSymbol(classSymbol) {
+ return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */);
+ }
/** Find references to `super` in the constructor of an extending class. */
- function findSuperConstructorAccesses(cls, addNode) {
- var ctr = cls.symbol.members.get("__constructor" /* Constructor */);
- if (!ctr) {
+ function findSuperConstructorAccesses(classDeclaration, addNode) {
+ var constructor = getClassConstructorSymbol(classDeclaration.symbol);
+ if (!constructor) {
return;
}
- for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) {
+ for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
ts.Debug.assert(decl.kind === 157 /* Constructor */);
var body = decl.body;
@@ -100774,6 +102734,16 @@
}
}
}
+ function hasOwnConstructor(classDeclaration) {
+ return !!getClassConstructorSymbol(classDeclaration.symbol);
+ }
+ function findInheritedConstructorReferences(classDeclaration, state) {
+ if (hasOwnConstructor(classDeclaration))
+ return;
+ var classSymbol = classDeclaration.symbol;
+ var search = state.createSearch(/*location*/ undefined, classSymbol, /*comingFrom*/ undefined);
+ getReferencesInContainerOrFiles(classSymbol, state, search);
+ }
function addImplementationReferences(refNode, addReference, state) {
// Check if we found a function/propertyAssignment/method with an implementation or initializer
if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) {
@@ -100938,7 +102908,7 @@
staticFlag &= ts.getModifierFlags(searchSpaceNode);
searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
return undefined;
}
@@ -100951,7 +102921,7 @@
default:
return undefined;
}
- var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
+ var references = ts.flatMap(searchSpaceNode.kind === 284 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
if (!ts.isThis(node)) {
@@ -100970,8 +102940,8 @@
// Make sure the container belongs to the same class
// and has the appropriate static modifier from the original container.
return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag;
- case 279 /* SourceFile */:
- return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
+ case 284 /* SourceFile */:
+ return container.kind === 284 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
}
});
}).map(function (n) { return FindAllReferences.nodeEntry(n); });
@@ -101825,11 +103795,11 @@
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return [declaration];
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return [declaration, declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
@@ -101850,16 +103820,16 @@
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -102070,7 +104040,7 @@
: undefined;
return { commentOwner: commentOwner, parameters: parameters_1 };
}
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return "quit";
case 244 /* ModuleDeclaration */:
// If in walking up the tree, we hit a a nested namespace declaration,
@@ -102630,7 +104600,7 @@
}
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var sourceFile = node;
return ts.isExternalModule(sourceFile)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
@@ -102682,10 +104652,10 @@
case 243 /* EnumDeclaration */:
case 241 /* InterfaceDeclaration */:
case 244 /* ModuleDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 242 /* TypeAliasDeclaration */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return true;
case 157 /* Constructor */:
case 156 /* MethodDeclaration */:
@@ -102706,7 +104676,7 @@
}
switch (navigationBarNodeKind(item.parent)) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
return true;
@@ -102791,7 +104761,7 @@
return !member.name || member.name.kind === 149 /* ComputedPropertyName */;
}
function getNodeSpan(node) {
- return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
+ return node.kind === 284 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
}
function getModifiers(node) {
if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) {
@@ -102912,8 +104882,8 @@
else {
// Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: false,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include,
suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
});
}
@@ -102927,7 +104897,7 @@
function removeUnusedImports(oldImports, sourceFile, program) {
var typeChecker = program.getTypeChecker();
var jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
- var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */);
+ var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */);
var usedImports = [];
for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
var importDecl = oldImports_1[_i];
@@ -103638,7 +105608,7 @@
if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
return true;
}
- if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) {
+ if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 7 /* Latest */)) {
return false;
}
// TODO: find a way to determine this for any unicode characters in a
@@ -103651,7 +105621,7 @@
if (ch >= 97 /* a */ && ch <= 122 /* z */) {
return true;
}
- if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) {
+ if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 7 /* Latest */)) {
return false;
}
// TODO: find a way to determine this for any unicode characters in a
@@ -104768,13 +106738,13 @@
var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); });
var parameterParts = ts.mapToDisplayParts(function (writer) {
var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : [];
- var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); })));
+ var params = ts.createNodeArray(thisParameter.concat(checker.getExpandedParameters(candidateSignature).map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); })));
printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer);
});
return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) };
}
function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
- var isVariadic = candidateSignature.hasRestParameter;
+ var isVariadic = checker.hasEffectiveRestParameter(candidateSignature);
var printer = ts.createPrinter({ removeComments: true });
var typeParameterParts = ts.mapToDisplayParts(function (writer) {
if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
@@ -104782,7 +106752,7 @@
printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer);
}
});
- var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
+ var parameters = checker.getExpandedParameters(candidateSignature).map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] };
}
function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) {
@@ -104971,8 +106941,8 @@
var name = importNameForConvertToDefaultImport(importNode);
if (!name)
continue;
- var module_1 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module_1 && program.getSourceFile(module_1.resolvedFileName);
+ var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
}
@@ -105425,7 +107395,7 @@
displayParts.push(ts.spacePart());
addFullSymbolName(symbol);
}
- if (symbolFlags & 1536 /* Module */) {
+ if (symbolFlags & 1536 /* Module */ && !isThisExpression) {
prefixNextMeaning();
var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */);
var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */;
@@ -105609,7 +107579,7 @@
// For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo`
// there documentation comments might be attached to the right hand side symbol of their declarations.
// The pattern of such special property access is that the parent symbol is the symbol of the file.
- if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) {
+ if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 284 /* SourceFile */; })) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) {
@@ -105734,7 +107704,7 @@
// If the parent is not sourceFile or module block it is local variable
for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) {
// Reached source file or module block
- if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
+ if (parent.kind === 284 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
return false;
}
}
@@ -105963,8 +107933,8 @@
(function (ts) {
var formatting;
(function (formatting) {
- var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
- var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
+ var standardScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
+ var jsxScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
var ScanAction;
(function (ScanAction) {
ScanAction[ScanAction["Scan"] = 0] = "Scan";
@@ -106558,7 +108528,7 @@
case 226 /* ForInStatement */:
// "in" keyword in [P in keyof T]: T[P]
case 150 /* TypeParameter */:
- return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */;
+ return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */ || context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */;
// Technically, "of" is not a binary operator, but format it the same way as "in"
case 227 /* ForOfStatement */:
return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */;
@@ -107059,7 +109029,7 @@
case 244 /* ModuleDeclaration */:
var body = parent.body;
return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 245 /* ModuleBlock */:
return ts.rangeContainsRange(parent.statements, node);
@@ -108178,7 +110148,7 @@
// - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually
// - parent and child are not on the same line
var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) &&
- (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine);
+ (parent.kind === 284 /* SourceFile */ || !parentAndChildShareLine);
if (!useActualIndentation) {
return -1 /* Unknown */;
}
@@ -108266,7 +110236,7 @@
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return getList(node.typeParameters);
case 192 /* NewExpression */:
case 191 /* CallExpression */:
@@ -108515,11 +110485,23 @@
ts.Debug.assert(typeof end === "number");
n.__end = end;
}
- var Position;
- (function (Position) {
- Position[Position["FullStart"] = 0] = "FullStart";
- Position[Position["Start"] = 1] = "Start";
- })(Position = textChanges_3.Position || (textChanges_3.Position = {}));
+ var LeadingTriviaOption;
+ (function (LeadingTriviaOption) {
+ /** Exclude all leading trivia (use getStart()) */
+ LeadingTriviaOption[LeadingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include leading trivia and,
+ * if there are no line breaks between the node and the previous token,
+ * include all trivia between the node and the previous token
+ */
+ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll";
+ })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {}));
+ var TrailingTriviaOption;
+ (function (TrailingTriviaOption) {
+ /** Exclude all trailing trivia (use getEnd()) */
+ TrailingTriviaOption[TrailingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include trailing trivia */
+ TrailingTriviaOption[TrailingTriviaOption["Include"] = 1] = "Include";
+ })(TrailingTriviaOption = textChanges_3.TrailingTriviaOption || (textChanges_3.TrailingTriviaOption = {}));
function skipWhitespacesAndLineBreaks(text, start) {
return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
@@ -108535,9 +110517,9 @@
}
return false;
}
- textChanges_3.useNonAdjustedPositions = {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: true,
+ var useNonAdjustedPositions = {
+ leadingTriviaOption: LeadingTriviaOption.Exclude,
+ trailingTriviaOption: TrailingTriviaOption.Exclude,
};
var ChangeKind;
(function (ChangeKind) {
@@ -108547,10 +110529,11 @@
ChangeKind[ChangeKind["Text"] = 3] = "Text";
})(ChangeKind || (ChangeKind = {}));
function getAdjustedRange(sourceFile, startNode, endNode, options) {
- return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) };
+ return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
}
- function getAdjustedStartPosition(sourceFile, node, options, position) {
- if (options.useNonAdjustedStartPosition) {
+ function getAdjustedStartPosition(sourceFile, node, options) {
+ var leadingTriviaOption = options.leadingTriviaOption;
+ if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
return node.getStart(sourceFile);
}
var fullStart = node.getFullStart();
@@ -108568,7 +110551,7 @@
// fullstart
// when b is replaced - we usually want to keep the leading trvia
// when b is deleted - we delete it
- return position === Position.Start ? start : fullStart;
+ return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
}
// get start position of the line following the line that contains fullstart position
// (but only if the fullstart isn't the very beginning of the file)
@@ -108580,11 +110563,12 @@
}
function getAdjustedEndPosition(sourceFile, node, options) {
var end = node.end;
- if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
+ var trailingTriviaOption = options.trailingTriviaOption;
+ if (trailingTriviaOption === TrailingTriviaOption.Exclude || (ts.isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) {
return end;
}
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
- return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
+ return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
? newEnd
: end;
}
@@ -108629,15 +110613,15 @@
this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) });
};
ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
- var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
+ var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
@@ -108645,11 +110629,11 @@
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
};
ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
};
ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
};
ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
@@ -108657,14 +110641,14 @@
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
};
ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
};
ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
- this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text);
+ this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
};
ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
@@ -108692,7 +110676,7 @@
};
ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) {
if (blankLineBetween === void 0) { blankLineBetween = false; }
- this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
+ this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
};
ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
var pos = before.getStart(sourceFile);
@@ -108799,7 +110783,7 @@
this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true));
};
ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) {
- var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start);
+ var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
this.insertNodeAt(sourceFile, pos, newNode, {
prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
suffix: this.newLineCharacter
@@ -109089,7 +111073,7 @@
textChanges_3.ChangeTracker = ChangeTracker;
// find first non-whitespace position in the leading trivia of the node
function startPositionToDeleteNodeInList(sourceFile, node) {
- return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
function getClassOrObjectBraceEnds(cls, sourceFile) {
return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end];
@@ -109133,7 +111117,7 @@
function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) {
// TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this
var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
- var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind);
+ var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 7 /* ESNext */, /*setParentNodes*/ true, scriptKind);
var changes = ts.formatting.formatDocument(sourceFile, formatContext);
return applyChanges(nonFormattedText, changes) + newLineCharacter;
}
@@ -109426,7 +111410,7 @@
case 249 /* ImportDeclaration */:
deleteNode(changes, sourceFile, node,
// For first import, leave header comment in place
- node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined);
+ node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined);
break;
case 186 /* BindingElement */:
var pattern = node.parent;
@@ -109464,7 +111448,7 @@
deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
}
else {
- deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined);
+ deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined);
}
}
}
@@ -109535,8 +111519,8 @@
/** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */
// Exported for tests only! (TODO: improve tests to not need this)
function deleteNode(changes, sourceFile, node, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, node, options);
var endPosition = getAdjustedEndPosition(sourceFile, node, options);
changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
}
@@ -109829,18 +111813,18 @@
}
function transformJSDocType(node) {
switch (node.kind) {
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 164 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -109864,7 +111848,7 @@
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
+ var isRest = node.type.kind === 295 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
var name = node.name || (isRest ? "rest" : "arg" + index);
var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken;
return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
@@ -110020,7 +112004,7 @@
}
if (ts.isPropertyAccessExpression(parent)) {
var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken);
- var typeNode = getTypeNodeIfAccessible(type, parent, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host);
if (typeNode) {
// Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags
var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ "");
@@ -110124,7 +112108,7 @@
}
}
function annotate(changes, sourceFile, declaration, type, program, host) {
- var typeNode = getTypeNodeIfAccessible(type, declaration, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host);
if (typeNode) {
if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) {
var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration;
@@ -110150,7 +112134,7 @@
// only infer parameters that have (1) no type and (2) an accessible inferred type
if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name))
return;
- var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host);
+ var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host);
var name = ts.getSynthesizedClone(param.name);
ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), "");
@@ -110167,47 +112151,33 @@
return !!merged;
}); });
var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags)));
- changes.insertJsdocCommentBefore(sourceFile, parent, tag);
+ var jsDocNode = parent.kind === 197 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent;
+ jsDocNode.jsDoc = parent.jsDoc;
+ jsDocNode.jsDocCache = parent.jsDocCache;
+ changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag);
+ }
+ function getJsDocNodeForArrowFunction(signature) {
+ if (signature.parent.kind === 154 /* PropertyDeclaration */) {
+ return signature.parent;
+ }
+ return signature.parent.parent;
}
function tryMergeJsdocTags(oldTag, newTag) {
if (oldTag.kind !== newTag.kind) {
return undefined;
}
switch (oldTag.kind) {
- case 299 /* JSDocParameterTag */: {
+ case 304 /* JSDocParameterTag */: {
var oldParam = oldTag;
var newParam = newTag;
return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment)
: undefined;
}
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment);
}
}
- function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
- var checker = program.getTypeChecker();
- var typeIsAccessible = true;
- var notAccessible = function () { typeIsAccessible = false; };
- var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
- trackSymbol: function (symbol, declaration, meaning) {
- // TODO: GH#18217
- typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
- },
- reportInaccessibleThisError: notAccessible,
- reportPrivateInBaseOfClassExpression: notAccessible,
- reportInaccessibleUniqueSymbolError: notAccessible,
- moduleResolverHost: {
- readFile: host.readFile,
- fileExists: host.fileExists,
- directoryExists: host.directoryExists,
- getSourceFiles: program.getSourceFiles,
- getCurrentDirectory: program.getCurrentDirectory,
- getCommonSourceDirectory: program.getCommonSourceDirectory,
- }
- });
- return typeIsAccessible ? res : undefined;
- }
function getReferences(token, program, cancellationToken) {
// Position shouldn't matter since token is not a SourceFile.
return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) {
@@ -110720,7 +112690,7 @@
precedingNode = ctorDeclaration.parent.parent;
newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
if (ctorDeclaration.parent.declarations.length === 1) {
- ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
+ ts.copyLeadingComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
changes.delete(sourceFile, precedingNode);
}
else {
@@ -110731,7 +112701,7 @@
if (!newClassDeclaration) {
return undefined;
}
- ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile);
+ ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile);
// Because the preceding node could be touched, we need to insert nodes before delete nodes.
changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
function createClassElementsFromSymbol(symbol) {
@@ -110784,7 +112754,7 @@
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
case 197 /* ArrowFunction */: {
@@ -110802,7 +112772,7 @@
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
default: {
@@ -110812,7 +112782,7 @@
}
var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
/*type*/ undefined, assignmentBinaryExpression.right);
- ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
return prop;
}
}
@@ -113561,7 +115531,7 @@
var typeNode = info.typeNode, type = info.type;
var original = typeNode.getText(sourceFile);
var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)];
- if (typeNode.kind === 286 /* JSDocNullableType */) {
+ if (typeNode.kind === 291 /* JSDocNullableType */) {
// for nullable types, suggest the flow-compatible `T | null | undefined`
// in addition to the jsdoc/closure-compatible `T | null`
actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -113581,7 +115551,7 @@
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 291 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -113878,7 +115848,7 @@
ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined;
});
var contextualType = checker.getContextualType(call);
- var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker) || ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ var returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker);
return ts.createMethod(
/*decorators*/ undefined,
/*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined,
@@ -114213,6 +116183,7 @@
return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings));
}
ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText;
+ /* @internal */
var OutputKind;
(function (OutputKind) {
OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals";
@@ -114347,7 +116318,7 @@
}
}
function toPropertyName(name) {
- return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name);
+ return ts.isIdentifierText(name, 7 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name);
}
// Parses assignments to "this.x" in the constructor into class property declarations
function getConstructorFunctionInstanceProperties(fnAst, members) {
@@ -114391,7 +116362,7 @@
}
function parseExpression(expr) {
var text = "const _ = " + expr;
- var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true);
+ var srcFile = ts.createSourceFile("test.ts", text, 7 /* Latest */, /*setParentNodes*/ true);
return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer;
}
function inferParameterType(_fn, _param) {
@@ -114408,7 +116379,7 @@
}
function isValidIdentifier(name) {
var keyword = ts.stringToToken(name);
- return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */);
+ return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 7 /* ESNext */);
}
function addComment(node, comment) {
if (comment !== undefined)
@@ -114863,7 +116834,7 @@
function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) {
var importDecl = toConvert.parent.parent;
var moduleSpecifier = importDecl.moduleSpecifier;
- var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 6 /* ESNext */) : "module";
+ var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 7 /* ESNext */) : "module";
var namespaceNameConflicts = toConvert.elements.some(function (element) {
return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true);
@@ -115380,7 +117351,7 @@
// * Module/namespace or source file
if (isScope(current)) {
scopes.push(current);
- if (current.kind === 279 /* SourceFile */) {
+ if (current.kind === 284 /* SourceFile */) {
return scopes;
}
}
@@ -116394,7 +118365,7 @@
function isBlockLike(node) {
switch (node.kind) {
case 218 /* Block */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 245 /* ModuleBlock */:
case 271 /* CaseClause */:
return true;
@@ -116758,7 +118729,7 @@
}
}
function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) {
- var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */);
+ var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 7 /* ESNext */);
var needUniqueName = false;
var toChange = [];
ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) {
@@ -116856,9 +118827,9 @@
if (isTopLevelDeclarationStatement(statement) &&
!isExported(sourceFile, statement, useEs6Exports) &&
forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
- var exports_1 = addExport(statement, useEs6Exports);
- if (exports_1)
- return exports_1;
+ var exports = addExport(statement, useEs6Exports);
+ if (exports)
+ return exports;
}
return statement;
});
@@ -116984,7 +118955,7 @@
var movedSymbols = new SymbolSet();
var oldImportsNeededByNewFile = new SymbolSet();
var newFileImportsFromOldFile = new SymbolSet();
- var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 4 /* ContainsJsx */); });
+ var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 2 /* ContainsJsx */); });
var jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx);
if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code)
oldImportsNeededByNewFile.add(jsxNamespaceSymbol);
@@ -117018,7 +118989,7 @@
if (ts.contains(toMove, statement))
continue;
// jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile.
- if (jsxNamespaceSymbol && !!(statement.transformFlags & 4 /* ContainsJsx */)) {
+ if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) {
unusedImportsFromOldFile.delete(jsxNamespaceSymbol);
}
forEachReference(statement, checker, function (symbol) {
@@ -117333,13 +119304,13 @@
var returnStatement_1 = ts.createReturn(expression);
body = ts.createBlock([returnStatement_1], /* multiLine */ true);
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
+ ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
}
else if (actionName === removeBracesActionName && returnStatement) {
var actualExpression = expression || ts.createVoidZero();
body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression;
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
+ ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
}
else {
ts.Debug.fail("invalid action");
@@ -117378,6 +119349,459 @@
})(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var convertParamsToDestructuredObject;
+ (function (convertParamsToDestructuredObject) {
+ var refactorName = "Convert parameters to destructured object";
+ var minimumParameterLength = 2;
+ refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ function getAvailableActions(context) {
+ var file = context.file, startPosition = context.startPosition;
+ var isJSFile = ts.isSourceFileJS(file);
+ if (isJSFile)
+ return ts.emptyArray; // TODO: GH#30113
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
+ if (!functionDeclaration)
+ return ts.emptyArray;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object);
+ return [{
+ name: refactorName,
+ description: description,
+ actions: [{
+ name: refactorName,
+ description: description
+ }]
+ }];
+ }
+ function getEditsForAction(context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host;
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
+ if (!functionDeclaration || !cancellationToken)
+ return undefined;
+ var groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
+ if (groupedReferences.valid) {
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(file, program, host, t, functionDeclaration, groupedReferences); });
+ return { renameFilename: undefined, renameLocation: undefined, edits: edits };
+ }
+ return { edits: [] }; // TODO: GH#30113
+ }
+ function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
+ var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
+ changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ",
+ // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
+ indentation: 0,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
+ });
+ var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); });
+ for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) {
+ var call = functionCalls_1[_i];
+ if (call.arguments && call.arguments.length) {
+ var newArgument = ts.getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true);
+ changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include });
+ }
+ }
+ }
+ function getGroupedReferences(functionDeclaration, program, cancellationToken) {
+ var functionNames = getFunctionNames(functionDeclaration);
+ var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
+ var names = ts.deduplicate(functionNames.concat(classNames), ts.equateValues);
+ var checker = program.getTypeChecker();
+ var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); });
+ var groupedReferences = groupReferences(references);
+ if (!ts.every(groupedReferences.declarations, /*callback*/ function (/*callback*/ decl) { return ts.contains(names, decl); })) {
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ function groupReferences(referenceEntries) {
+ var classReferences = { accessExpressions: [], typeUsages: [] };
+ var groupedReferences = { functionCalls: [], declarations: [], classReferences: classReferences, valid: true };
+ var functionSymbols = ts.map(functionNames, checker.getSymbolAtLocation);
+ var classSymbols = ts.map(classNames, checker.getSymbolAtLocation);
+ var isConstructor = ts.isConstructorDeclaration(functionDeclaration);
+ for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
+ var entry = referenceEntries_1[_i];
+ if (entry.kind !== 1 /* Node */) {
+ groupedReferences.valid = false;
+ continue;
+ }
+ /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function.
+ Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test:
+ class A { foo(a: number, b: number) { return a + b; } }
+ class B { foo(c: number, d: number) { return c + d; } }
+ declare const ab: A | B;
+ ab.foo(1, 2);
+ Find all references will return `ab.foo(1, 2)` as a reference to A's `foo` but we could be calling B's `foo`.
+ When looking for constructor calls, however, the symbol on the constructor call reference is going to be the corresponding class symbol.
+ So we need to add a special case for this because when calling a constructor of a class through one of its subclasses,
+ the symbols are going to be different.
+ */
+ if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer) || ts.isNewExpressionTarget(entry.node)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var call = entryToFunctionCall(entry);
+ if (call) {
+ groupedReferences.functionCalls.push(call);
+ continue;
+ }
+ }
+ // if the refactored function is a constructor, we must also check if the references to its class are valid
+ if (isConstructor && ts.contains(classSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var accessExpression = entryToAccessExpression(entry);
+ if (accessExpression) {
+ classReferences.accessExpressions.push(accessExpression);
+ continue;
+ }
+ // Only class declarations are allowed to be used as a type (in a heritage clause),
+ // otherwise `findAllReferences` might not be able to track constructor calls.
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ var type = entryToType(entry);
+ if (type) {
+ classReferences.typeUsages.push(type);
+ continue;
+ }
+ }
+ }
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ }
+ }
+ function symbolComparer(a, b) {
+ return ts.getSymbolTarget(a) === ts.getSymbolTarget(b);
+ }
+ function entryToDeclaration(entry) {
+ if (ts.isDeclaration(entry.node.parent)) {
+ return entry.node;
+ }
+ return undefined;
+ }
+ function entryToFunctionCall(entry) {
+ if (entry.node.parent) {
+ var functionReference = entry.node;
+ var parent = functionReference.parent;
+ switch (parent.kind) {
+ // Function call (foo(...) or super(...))
+ case 191 /* CallExpression */:
+ var callExpression = ts.tryCast(parent, ts.isCallExpression);
+ if (callExpression && callExpression.expression === functionReference) {
+ return callExpression;
+ }
+ break;
+ // Constructor call (new Foo(...))
+ case 192 /* NewExpression */:
+ var newExpression = ts.tryCast(parent, ts.isNewExpression);
+ if (newExpression && newExpression.expression === functionReference) {
+ return newExpression;
+ }
+ break;
+ // Method call (x.foo(...))
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
+ var callExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_1 && callExpression_1.expression === propertyAccessExpression) {
+ return callExpression_1;
+ }
+ }
+ break;
+ // Method call (x["foo"](...))
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
+ var callExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_2 && callExpression_2.expression === elementAccessExpression) {
+ return callExpression_2;
+ }
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToAccessExpression(entry) {
+ if (entry.node.parent) {
+ var reference = entry.node;
+ var parent = reference.parent;
+ switch (parent.kind) {
+ // `C.foo`
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
+ return propertyAccessExpression;
+ }
+ break;
+ // `C["foo"]`
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.expression === reference) {
+ return elementAccessExpression;
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToType(entry) {
+ var reference = entry.node;
+ if (ts.getMeaningFromLocation(reference) === 2 /* Type */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
+ return reference;
+ }
+ return undefined;
+ }
+ function getFunctionDeclarationAtPosition(file, startPosition, checker) {
+ var node = ts.getTouchingToken(file, startPosition);
+ var functionDeclaration = ts.getContainingFunction(node);
+ // don't offer refactor on top-level JSDoc
+ if (isTopLevelJSDoc(node))
+ return undefined;
+ if (functionDeclaration
+ && isValidFunctionDeclaration(functionDeclaration, checker)
+ && ts.rangeContainsRange(functionDeclaration, node)
+ && !(functionDeclaration.body && ts.rangeContainsRange(functionDeclaration.body, node)))
+ return functionDeclaration;
+ return undefined;
+ }
+ function isTopLevelJSDoc(node) {
+ var containingJSDoc = ts.findAncestor(node, ts.isJSDocNode);
+ if (containingJSDoc) {
+ var containingNonJSDoc = ts.findAncestor(containingJSDoc, function (n) { return !ts.isJSDocNode(n); });
+ return !!containingNonJSDoc && ts.isFunctionLikeDeclaration(containingNonJSDoc);
+ }
+ return false;
+ }
+ function isValidFunctionDeclaration(functionDeclaration, checker) {
+ if (!isValidParameterNodeArray(functionDeclaration.parameters, checker))
+ return false;
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return !!functionDeclaration.name
+ && !!functionDeclaration.body
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ case 157 /* Constructor */:
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ return !!functionDeclaration.body
+ && !!functionDeclaration.parent.name
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ else {
+ return isValidVariableDeclaration(functionDeclaration.parent.parent)
+ && !!functionDeclaration.body
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ case 196 /* FunctionExpression */:
+ case 197 /* ArrowFunction */:
+ return isValidVariableDeclaration(functionDeclaration.parent);
+ }
+ return false;
+ }
+ function isValidParameterNodeArray(parameters, checker) {
+ return getRefactorableParametersLength(parameters) >= minimumParameterLength
+ && ts.every(parameters, /*callback*/ function (/*callback*/ paramDecl) { return isValidParameterDeclaration(paramDecl, checker); });
+ }
+ function isValidParameterDeclaration(parameterDeclaration, checker) {
+ if (ts.isRestParameter(parameterDeclaration)) {
+ var type = checker.getTypeAtLocation(parameterDeclaration);
+ if (!checker.isArrayType(type) && !checker.isTupleType(type))
+ return false;
+ }
+ return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name);
+ }
+ function isValidVariableDeclaration(node) {
+ return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113
+ }
+ function hasThisParameter(parameters) {
+ return parameters.length > 0 && ts.isThis(parameters[0].name);
+ }
+ function getRefactorableParametersLength(parameters) {
+ if (hasThisParameter(parameters)) {
+ return parameters.length - 1;
+ }
+ return parameters.length;
+ }
+ function getRefactorableParameters(parameters) {
+ if (hasThisParameter(parameters)) {
+ parameters = ts.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
+ }
+ return parameters;
+ }
+ function createPropertyOrShorthandAssignment(name, initializer) {
+ if (ts.isIdentifier(initializer) && ts.getTextOfIdentifierOrLiteral(initializer) === name) {
+ return ts.createShorthandPropertyAssignment(name);
+ }
+ return ts.createPropertyAssignment(name, initializer);
+ }
+ function createNewArgument(functionDeclaration, functionArguments) {
+ var parameters = getRefactorableParameters(functionDeclaration.parameters);
+ var hasRestParameter = ts.isRestParameter(ts.last(parameters));
+ var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
+ var properties = ts.map(nonRestArguments, function (arg, i) {
+ var parameterName = getParameterName(parameters[i]);
+ var property = createPropertyOrShorthandAssignment(parameterName, arg);
+ ts.suppressLeadingAndTrailingTrivia(property.name);
+ if (ts.isPropertyAssignment(property))
+ ts.suppressLeadingAndTrailingTrivia(property.initializer);
+ copyComments(arg, property);
+ return property;
+ });
+ if (hasRestParameter && functionArguments.length >= parameters.length) {
+ var restArguments = functionArguments.slice(parameters.length - 1);
+ var restProperty = ts.createPropertyAssignment(getParameterName(ts.last(parameters)), ts.createArrayLiteral(restArguments));
+ properties.push(restProperty);
+ }
+ var objectLiteral = ts.createObjectLiteral(properties, /*multiLine*/ false);
+ return objectLiteral;
+ }
+ function createNewParameters(functionDeclaration, program, host) {
+ var checker = program.getTypeChecker();
+ var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
+ var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration);
+ var objectParameterName = ts.createObjectBindingPattern(bindingElements);
+ var objectParameterType = createParameterTypeNode(refactorableParameters);
+ var objectInitializer;
+ // If every parameter in the original function was optional, add an empty object initializer to the new object parameter
+ if (ts.every(refactorableParameters, isOptionalParameter)) {
+ objectInitializer = ts.createObjectLiteral();
+ }
+ var objectParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, objectParameterName,
+ /*questionToken*/ undefined, objectParameterType, objectInitializer);
+ if (hasThisParameter(functionDeclaration.parameters)) {
+ var thisParameter = functionDeclaration.parameters[0];
+ var newThisParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, thisParameter.name,
+ /*questionToken*/ undefined, thisParameter.type);
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.name);
+ copyComments(thisParameter.name, newThisParameter.name);
+ if (thisParameter.type) {
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.type);
+ copyComments(thisParameter.type, newThisParameter.type);
+ }
+ return ts.createNodeArray([newThisParameter, objectParameter]);
+ }
+ return ts.createNodeArray([objectParameter]);
+ function createBindingElementFromParameterDeclaration(parameterDeclaration) {
+ var element = ts.createBindingElement(
+ /*dotDotDotToken*/ undefined,
+ /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer);
+ ts.suppressLeadingAndTrailingTrivia(element);
+ if (parameterDeclaration.initializer && element.initializer) {
+ copyComments(parameterDeclaration.initializer, element.initializer);
+ }
+ return element;
+ }
+ function createParameterTypeNode(parameters) {
+ var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration);
+ var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */);
+ return typeNode;
+ }
+ function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
+ var parameterType = parameterDeclaration.type;
+ if (!parameterType && (parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration))) {
+ parameterType = getTypeNode(parameterDeclaration);
+ }
+ var propertySignature = ts.createPropertySignature(
+ /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType,
+ /*initializer*/ undefined);
+ ts.suppressLeadingAndTrailingTrivia(propertySignature);
+ copyComments(parameterDeclaration.name, propertySignature.name);
+ if (parameterDeclaration.type && propertySignature.type) {
+ copyComments(parameterDeclaration.type, propertySignature.type);
+ }
+ return propertySignature;
+ }
+ function getTypeNode(node) {
+ var type = checker.getTypeAtLocation(node);
+ return ts.getTypeNodeIfAccessible(type, node, program, host);
+ }
+ function isOptionalParameter(parameterDeclaration) {
+ if (ts.isRestParameter(parameterDeclaration)) {
+ var type = checker.getTypeAtLocation(parameterDeclaration);
+ return !checker.isTupleType(type);
+ }
+ return checker.isOptionalParameter(parameterDeclaration);
+ }
+ }
+ function copyComments(sourceNode, targetNode) {
+ var sourceFile = sourceNode.getSourceFile();
+ var text = sourceFile.text;
+ if (hasLeadingLineBreak(sourceNode, text)) {
+ ts.copyLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ else {
+ ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ ts.copyTrailingComments(sourceNode, targetNode, sourceFile);
+ }
+ function hasLeadingLineBreak(node, text) {
+ var start = node.getFullStart();
+ var end = node.getStart();
+ for (var i = start; i < end; i++) {
+ if (text.charCodeAt(i) === 10 /* lineFeed */)
+ return true;
+ }
+ return false;
+ }
+ function getParameterName(paramDeclaration) {
+ return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name);
+ }
+ function getClassNames(constructorDeclaration) {
+ switch (constructorDeclaration.parent.kind) {
+ case 240 /* ClassDeclaration */:
+ var classDeclaration = constructorDeclaration.parent;
+ return [classDeclaration.name];
+ case 209 /* ClassExpression */:
+ var classExpression = constructorDeclaration.parent;
+ var variableDeclaration = constructorDeclaration.parent.parent;
+ var className = classExpression.name;
+ if (className)
+ return [className, variableDeclaration.name];
+ return [variableDeclaration.name];
+ }
+ }
+ function getFunctionNames(functionDeclaration) {
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return [functionDeclaration.name];
+ case 157 /* Constructor */:
+ var ctrKeyword = ts.findChildOfKind(functionDeclaration, 124 /* ConstructorKeyword */, functionDeclaration.getSourceFile());
+ if (functionDeclaration.parent.kind === 209 /* ClassExpression */) {
+ var variableDeclaration = functionDeclaration.parent.parent;
+ return [variableDeclaration.name, ctrKeyword];
+ }
+ return [ctrKeyword];
+ case 197 /* ArrowFunction */:
+ return [functionDeclaration.parent.name];
+ case 196 /* FunctionExpression */:
+ if (functionDeclaration.name)
+ return [functionDeclaration.name, functionDeclaration.parent.name];
+ return [functionDeclaration.parent.name];
+ default:
+ return ts.Debug.assertNever(functionDeclaration);
+ }
+ }
+ })(convertParamsToDestructuredObject = refactor.convertParamsToDestructuredObject || (refactor.convertParamsToDestructuredObject = {}));
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
var ts;
(function (ts) {
/** The version of the language service API */
@@ -117395,7 +119819,8 @@
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
- this.transformFlags = undefined; // TODO: GH#18217
+ this.modifierFlagsCache = 0 /* None */;
+ this.transformFlags = 0 /* None */;
this.parent = undefined;
this.kind = kind;
}
@@ -117457,7 +119882,7 @@
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 288 /* FirstJSDocNode */ || kid.kind > 310 /* LastJSDocNode */; });
return child.kind < 148 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -117527,7 +119952,7 @@
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(311 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
@@ -117545,6 +119970,8 @@
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
+ this.modifierFlagsCache = 0 /* None */;
+ this.transformFlags = 0 /* None */;
this.parent = undefined;
}
TokenOrIdentifierObject.prototype.getSourceFile = function () {
@@ -118120,7 +120547,7 @@
var sourceFile;
if (this.currentFileName !== fileName) {
// This is a new file, just parse it
- sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
+ sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 7 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
}
else if (this.currentFileVersion !== version) {
// This is the same file, just a newer version. Incrementally parse the file.
@@ -118244,9 +120671,9 @@
}());
ts.ThrottledCancellationToken = ThrottledCancellationToken;
function createLanguageService(host, documentRegistry, syntaxOnly) {
+ var _a;
if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
if (syntaxOnly === void 0) { syntaxOnly = false; }
- var _a;
var syntaxTreeCache = new SyntaxTreeCache(host);
var program;
var lastProjectVersion;
@@ -118277,7 +120704,7 @@
function getValidSourceFile(fileName) {
var sourceFile = program.getSourceFile(fileName);
if (!sourceFile) {
- throw new Error("Could not find file: '" + fileName + "'.");
+ throw new Error("Could not find sourceFile: '" + fileName + "' in " + (program && JSON.stringify(program.getSourceFiles().map(function (f) { return f.fileName; }))) + ".");
}
return sourceFile;
}
@@ -120644,8 +123071,6 @@
// TODO: it should be moved into a namespace though.
/* @internal */
var toolsVersion = ts.versionMajorMinor;
-//# sourceMappingURL=services.js.map
-"use strict";
/* @internal */
var ts;
(function (ts) {
@@ -120986,41 +123411,6 @@
JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
})(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
})(ts || (ts = {}));
-//# sourceMappingURL=jsTyping.js.map
-"use strict";
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-var __extends = (this && this.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
-})();
-var __rest = (this && this.__rest) || function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
- t[p[i]] = s[p[i]];
- return t;
-};
var ts;
(function (ts) {
var server;
@@ -121033,6 +123423,7 @@
LogLevel[LogLevel["verbose"] = 3] = "verbose";
})(LogLevel = server.LogLevel || (server.LogLevel = {}));
server.emptyArray = createSortedArray();
+ // TODO: Use a const enum (https://github.com/Microsoft/TypeScript/issues/16804)
var Msg;
(function (Msg) {
Msg["Err"] = "Err";
@@ -121042,7 +123433,7 @@
function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) {
return {
projectName: project.getProjectName(),
- fileNames: project.getFileNames(true, true).concat(project.getExcludedFiles()),
+ fileNames: project.getFileNames(/*excludeFilesFromExternalLibraries*/ true, /*excludeConfigFiles*/ true).concat(project.getExcludedFiles()),
compilerOptions: project.getCompilationSettings(),
typeAcquisition: typeAcquisition,
unresolvedImports: unresolvedImports,
@@ -121099,6 +123490,7 @@
}
server.createNormalizedPathMap = createNormalizedPathMap;
function isInferredProjectName(name) {
+ // POSIX defines /dev/null as a device - there should be no file with this prefix
return /dev\/null\/inferredProject\d+\*/.test(name);
}
server.isInferredProjectName = isInferredProjectName;
@@ -121107,25 +123499,34 @@
}
server.makeInferredProjectName = makeInferredProjectName;
function createSortedArray() {
- return [];
+ return []; // TODO: GH#19873
}
server.createSortedArray = createSortedArray;
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
+/* @internal */
(function (ts) {
var server;
(function (server) {
- var ThrottledOperations = (function () {
+ var ThrottledOperations = /** @class */ (function () {
function ThrottledOperations(host, logger) {
this.host = host;
this.pendingTimeouts = ts.createMap();
this.logger = logger.hasLevel(server.LogLevel.verbose) ? logger : undefined;
}
+ /**
+ * Wait `number` milliseconds and then invoke `cb`. If, while waiting, schedule
+ * is called again with the same `operationId`, cancel this operation in favor
+ * of the new one. (Note that the amount of time the canceled operation had been
+ * waiting does not affect the amount of time that the new operation waits.)
+ */
ThrottledOperations.prototype.schedule = function (operationId, delay, cb) {
var pendingTimeout = this.pendingTimeouts.get(operationId);
if (pendingTimeout) {
+ // another operation was already scheduled for this id - cancel it
this.host.clearTimeout(pendingTimeout);
}
+ // schedule new operation, pass arguments
this.pendingTimeouts.set(operationId, this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb));
if (this.logger) {
this.logger.info("Scheduled: " + operationId + (pendingTimeout ? ", Cancelled earlier one" : ""));
@@ -121141,7 +123542,7 @@
return ThrottledOperations;
}());
server.ThrottledOperations = ThrottledOperations;
- var GcTimer = (function () {
+ var GcTimer = /** @class */ (function () {
function GcTimer(host, delay, logger) {
this.host = host;
this.delay = delay;
@@ -121149,6 +123550,7 @@
}
GcTimer.prototype.scheduleCollect = function () {
if (!this.host.gc || this.timerId !== undefined) {
+ // no global.gc or collection was already scheduled - skip this request
return;
}
this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this);
@@ -121156,10 +123558,10 @@
GcTimer.run = function (self) {
self.timerId = undefined;
var log = self.logger.hasLevel(server.LogLevel.requestTime);
- var before = log && self.host.getMemoryUsage();
- self.host.gc();
+ var before = log && self.host.getMemoryUsage(); // TODO: GH#18217
+ self.host.gc(); // TODO: GH#18217
if (log) {
- var after = self.host.getMemoryUsage();
+ var after = self.host.getMemoryUsage(); // TODO: GH#18217
self.logger.perftrc("GC::before " + before + ", after " + after);
}
};
@@ -121190,13 +123592,16 @@
return indentStr + str.replace(/\n/g, indentStr);
}
server.indent = indent;
+ /** Put stringified JSON on the next line, indented. */
function stringifyIndented(json) {
return indentStr + JSON.stringify(json);
}
server.stringifyIndented = stringifyIndented;
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
+/* @internal */
(function (ts) {
+ // Additional tsserver specific watch information
var WatchType;
(function (WatchType) {
WatchType["ClosedScriptInfo"] = "Closed Script info";
@@ -121205,41 +123610,57 @@
WatchType["MissingSourceMapFile"] = "Missing source map file";
})(WatchType = ts.WatchType || (ts.WatchType = {}));
})(ts || (ts = {}));
+// tslint:disable no-unnecessary-qualifier
+/**
+ * Declaration module describing the TypeScript Server protocol
+ */
var ts;
(function (ts) {
var server;
(function (server) {
var protocol;
(function (protocol) {
+ // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`.
var CommandTypes;
(function (CommandTypes) {
CommandTypes["JsxClosingTag"] = "jsxClosingTag";
CommandTypes["Brace"] = "brace";
+ /* @internal */
CommandTypes["BraceFull"] = "brace-full";
CommandTypes["BraceCompletion"] = "braceCompletion";
CommandTypes["GetSpanOfEnclosingComment"] = "getSpanOfEnclosingComment";
CommandTypes["Change"] = "change";
CommandTypes["Close"] = "close";
+ /** @deprecated Prefer CompletionInfo -- see comment on CompletionsResponse */
CommandTypes["Completions"] = "completions";
CommandTypes["CompletionInfo"] = "completionInfo";
+ /* @internal */
CommandTypes["CompletionsFull"] = "completions-full";
CommandTypes["CompletionDetails"] = "completionEntryDetails";
+ /* @internal */
CommandTypes["CompletionDetailsFull"] = "completionEntryDetails-full";
CommandTypes["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList";
CommandTypes["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile";
CommandTypes["Configure"] = "configure";
CommandTypes["Definition"] = "definition";
+ /* @internal */
CommandTypes["DefinitionFull"] = "definition-full";
CommandTypes["DefinitionAndBoundSpan"] = "definitionAndBoundSpan";
+ /* @internal */
CommandTypes["DefinitionAndBoundSpanFull"] = "definitionAndBoundSpan-full";
CommandTypes["Implementation"] = "implementation";
+ /* @internal */
CommandTypes["ImplementationFull"] = "implementation-full";
+ /* @internal */
CommandTypes["EmitOutput"] = "emit-output";
CommandTypes["Exit"] = "exit";
CommandTypes["Format"] = "format";
CommandTypes["Formatonkey"] = "formatonkey";
+ /* @internal */
CommandTypes["FormatFull"] = "format-full";
+ /* @internal */
CommandTypes["FormatonkeyFull"] = "formatonkey-full";
+ /* @internal */
CommandTypes["FormatRangeFull"] = "formatRange-full";
CommandTypes["Geterr"] = "geterr";
CommandTypes["GeterrForProject"] = "geterrForProject";
@@ -121247,25 +123668,34 @@
CommandTypes["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync";
CommandTypes["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync";
CommandTypes["NavBar"] = "navbar";
+ /* @internal */
CommandTypes["NavBarFull"] = "navbar-full";
CommandTypes["Navto"] = "navto";
+ /* @internal */
CommandTypes["NavtoFull"] = "navto-full";
CommandTypes["NavTree"] = "navtree";
CommandTypes["NavTreeFull"] = "navtree-full";
+ /** @deprecated */
CommandTypes["Occurrences"] = "occurrences";
CommandTypes["DocumentHighlights"] = "documentHighlights";
+ /* @internal */
CommandTypes["DocumentHighlightsFull"] = "documentHighlights-full";
CommandTypes["Open"] = "open";
CommandTypes["Quickinfo"] = "quickinfo";
+ /* @internal */
CommandTypes["QuickinfoFull"] = "quickinfo-full";
CommandTypes["References"] = "references";
+ /* @internal */
CommandTypes["ReferencesFull"] = "references-full";
CommandTypes["Reload"] = "reload";
CommandTypes["Rename"] = "rename";
+ /* @internal */
CommandTypes["RenameInfoFull"] = "rename-full";
+ /* @internal */
CommandTypes["RenameLocationsFull"] = "renameLocations-full";
CommandTypes["Saveto"] = "saveto";
CommandTypes["SignatureHelp"] = "signatureHelp";
+ /* @internal */
CommandTypes["SignatureHelpFull"] = "signatureHelp-full";
CommandTypes["Status"] = "status";
CommandTypes["TypeDefinition"] = "typeDefinition";
@@ -121275,33 +123705,48 @@
CommandTypes["OpenExternalProject"] = "openExternalProject";
CommandTypes["OpenExternalProjects"] = "openExternalProjects";
CommandTypes["CloseExternalProject"] = "closeExternalProject";
+ /* @internal */
CommandTypes["SynchronizeProjectList"] = "synchronizeProjectList";
+ /* @internal */
CommandTypes["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles";
+ CommandTypes["UpdateOpen"] = "updateOpen";
+ /* @internal */
CommandTypes["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full";
+ /* @internal */
CommandTypes["Cleanup"] = "cleanup";
CommandTypes["GetOutliningSpans"] = "getOutliningSpans";
+ /* @internal */
CommandTypes["GetOutliningSpansFull"] = "outliningSpans";
CommandTypes["TodoComments"] = "todoComments";
CommandTypes["Indentation"] = "indentation";
CommandTypes["DocCommentTemplate"] = "docCommentTemplate";
+ /* @internal */
CommandTypes["CompilerOptionsDiagnosticsFull"] = "compilerOptionsDiagnostics-full";
+ /* @internal */
CommandTypes["NameOrDottedNameSpan"] = "nameOrDottedNameSpan";
+ /* @internal */
CommandTypes["BreakpointStatement"] = "breakpointStatement";
CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects";
CommandTypes["GetCodeFixes"] = "getCodeFixes";
+ /* @internal */
CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full";
CommandTypes["GetCombinedCodeFix"] = "getCombinedCodeFix";
+ /* @internal */
CommandTypes["GetCombinedCodeFixFull"] = "getCombinedCodeFix-full";
CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand";
CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes";
CommandTypes["GetApplicableRefactors"] = "getApplicableRefactors";
CommandTypes["GetEditsForRefactor"] = "getEditsForRefactor";
+ /* @internal */
CommandTypes["GetEditsForRefactorFull"] = "getEditsForRefactor-full";
CommandTypes["OrganizeImports"] = "organizeImports";
+ /* @internal */
CommandTypes["OrganizeImportsFull"] = "organizeImports-full";
CommandTypes["GetEditsForFileRename"] = "getEditsForFileRename";
+ /* @internal */
CommandTypes["GetEditsForFileRenameFull"] = "getEditsForFileRename-full";
CommandTypes["ConfigurePlugin"] = "configurePlugin";
+ // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`.
})(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {}));
var IndentStyle;
(function (IndentStyle) {
@@ -121354,13 +123799,23 @@
(function (ts) {
var server;
(function (server) {
- var TextStorage = (function () {
+ /* @internal */
+ var TextStorage = /** @class */ (function () {
function TextStorage(host, fileName, initialVersion, info) {
this.host = host;
this.fileName = fileName;
this.info = info;
+ /**
+ * True if the text is for the file thats open in the editor
+ */
this.isOpen = false;
+ /**
+ * True if the text present is the text from the file on the disk
+ */
this.ownFileText = false;
+ /**
+ * True when reloading contents of file from the disk is pending
+ */
this.pendingReloadFromDisk = false;
this.version = initialVersion || { svc: 0, text: 0 };
}
@@ -121383,6 +123838,7 @@
this.info.sourceInfos = undefined;
this.info.documentPositionMapper = undefined;
};
+ /** Public for testing */
TextStorage.prototype.useText = function (newText) {
this.svc = undefined;
this.text = newText;
@@ -121399,23 +123855,42 @@
this.fileSize = undefined;
this.resetSourceMapInfo();
};
+ /**
+ * Set the contents as newText
+ * returns true if text changed
+ */
TextStorage.prototype.reload = function (newText) {
ts.Debug.assert(newText !== undefined);
+ // Reload always has fresh content
this.pendingReloadFromDisk = false;
+ // If text changed set the text
+ // This also ensures that if we had switched to version cache,
+ // we are switching back to text.
+ // The change to version cache will happen when needed
+ // Thus avoiding the computation if there are no changes
if (this.text !== newText) {
this.useText(newText);
+ // We cant guarantee new text is own file text
this.ownFileText = false;
return true;
}
return false;
};
+ /**
+ * Reads the contents from tempFile(if supplied) or own file and sets it as contents
+ * returns true if text changed
+ */
TextStorage.prototype.reloadWithFileText = function (tempFileName) {
var _a = this.getFileTextAndSize(tempFileName), newText = _a.text, fileSize = _a.fileSize;
var reloaded = this.reload(newText);
- this.fileSize = fileSize;
+ this.fileSize = fileSize; // NB: after reload since reload clears it
this.ownFileText = !tempFileName || tempFileName === this.fileName;
return reloaded;
};
+ /**
+ * Reloads the contents from the file if there is no pending reload from disk or the contents of file are same as file text
+ * returns true if text changed
+ */
TextStorage.prototype.reloadFromDisk = function () {
if (!this.pendingReloadFromDisk && !this.ownFileText) {
return this.reloadWithFileText();
@@ -121425,14 +123900,21 @@
TextStorage.prototype.delayReloadFromFileIntoText = function () {
this.pendingReloadFromDisk = true;
};
+ /**
+ * For telemetry purposes, we would like to be able to report the size of the file.
+ * However, we do not want telemetry to require extra file I/O so we report a size
+ * that may be stale (e.g. may not reflect change made on disk since the last reload).
+ * NB: Will read from disk if the file contents have never been loaded because
+ * telemetry falsely indicating size 0 would be counter-productive.
+ */
TextStorage.prototype.getTelemetryFileSize = function () {
return !!this.fileSize
? this.fileSize
- : !!this.text
- ? this.text.length
+ : !!this.text // Check text before svc because its length is cheaper
+ ? this.text.length // Could be wrong if this.pendingReloadFromDisk
: !!this.svc
- ? this.svc.getSnapshot().getLength()
- : this.getSnapshot().getLength();
+ ? this.svc.getSnapshot().getLength() // Could be wrong if this.pendingReloadFromDisk
+ : this.getSnapshot().getLength(); // Should be strictly correct
};
TextStorage.prototype.getSnapshot = function () {
return this.useScriptVersionCacheIfValidOrOpen()
@@ -121442,19 +123924,27 @@
TextStorage.prototype.getAbsolutePositionAndLineText = function (line) {
return this.switchToScriptVersionCache().getAbsolutePositionAndLineText(line);
};
+ /**
+ * @param line 0 based index
+ */
TextStorage.prototype.lineToTextSpan = function (line) {
if (!this.useScriptVersionCacheIfValidOrOpen()) {
var lineMap = this.getLineMap();
- var start = lineMap[line];
+ var start = lineMap[line]; // -1 since line is 1-based
var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length;
return ts.createTextSpanFromBounds(start, end);
}
return this.svc.lineToTextSpan(line);
};
+ /**
+ * @param line 1 based index
+ * @param offset 1 based index
+ */
TextStorage.prototype.lineOffsetToPosition = function (line, offset, allowEdits) {
if (!this.useScriptVersionCacheIfValidOrOpen()) {
return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text, allowEdits);
}
+ // TODO: assert this offset is actually on the line
return this.svc.lineOffsetToPosition(line, offset);
};
TextStorage.prototype.positionToLineOffset = function (position) {
@@ -121469,6 +123959,7 @@
var text;
var fileName = tempFileName || this.fileName;
var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; };
+ // Only non typescript files have size limitation
if (!ts.hasTSFileExtension(this.fileName)) {
var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length;
if (fileSize > server.maxFileSize) {
@@ -121489,12 +123980,15 @@
return this.svc;
};
TextStorage.prototype.useScriptVersionCacheIfValidOrOpen = function () {
+ // If this is open script, use the cache
if (this.isOpen) {
return this.switchToScriptVersionCache();
}
+ // If there is pending reload from the disk then, reload the text
if (this.pendingReloadFromDisk) {
this.reloadWithFileText();
}
+ // At this point if svc is present its valid
return this.svc;
};
TextStorage.prototype.getOrLoadText = function () {
@@ -121522,17 +124016,21 @@
return TextStorage;
}());
server.TextStorage = TextStorage;
+ /*@internal*/
function isDynamicFileName(fileName) {
return fileName[0] === "^" || ts.getBaseFileName(fileName)[0] === "^";
}
server.isDynamicFileName = isDynamicFileName;
- var ScriptInfo = (function () {
+ var ScriptInfo = /** @class */ (function () {
function ScriptInfo(host, fileName, scriptKind, hasMixedContent, path, initialVersion) {
this.host = host;
this.fileName = fileName;
this.scriptKind = scriptKind;
this.hasMixedContent = hasMixedContent;
this.path = path;
+ /**
+ * All projects that include this file
+ */
this.containingProjects = [];
this.isDynamic = isDynamicFileName(fileName);
this.textStorage = new TextStorage(host, fileName, initialVersion, this);
@@ -121544,12 +124042,15 @@
? scriptKind
: ts.getScriptKindFromFileName(fileName);
}
+ /*@internal*/
ScriptInfo.prototype.getVersion = function () {
return this.textStorage.version;
};
+ /*@internal*/
ScriptInfo.prototype.getTelemetryFileSize = function () {
return this.textStorage.getTelemetryFileSize();
};
+ /*@internal*/
ScriptInfo.prototype.isDynamicOrHasMixedContent = function () {
return this.hasMixedContent || this.isDynamic;
};
@@ -121560,6 +124061,7 @@
this.textStorage.isOpen = true;
if (newText !== undefined &&
this.textStorage.reload(newText)) {
+ // reload new contents only if the existing contents changed
this.markContainingProjectsAsDirty();
}
};
@@ -121580,6 +124082,7 @@
};
ScriptInfo.prototype.ensureRealPath = function () {
if (this.realpath === undefined) {
+ // Default is just the path
this.realpath = this.path;
if (this.host.realpath) {
ts.Debug.assert(!!this.containingProjects.length);
@@ -121587,13 +124090,15 @@
var realpath = this.host.realpath(this.path);
if (realpath) {
this.realpath = project.toPath(realpath);
+ // If it is different from this.path, add to the map
if (this.realpath !== this.path) {
- project.projectService.realpathToScriptInfos.add(this.realpath, this);
+ project.projectService.realpathToScriptInfos.add(this.realpath, this); // TODO: GH#18217
}
}
}
}
};
+ /*@internal*/
ScriptInfo.prototype.getRealpathIfDifferent = function () {
return this.realpath && this.realpath !== this.path ? this.realpath : undefined;
};
@@ -121611,6 +124116,7 @@
return isNew;
};
ScriptInfo.prototype.isAttached = function (project) {
+ // unrolled for common cases
switch (this.containingProjects.length) {
case 0: return false;
case 1: return this.containingProjects[0] === project;
@@ -121619,6 +124125,7 @@
}
};
ScriptInfo.prototype.detachFromProject = function (project) {
+ // unrolled for common cases
switch (this.containingProjects.length) {
case 0:
return;
@@ -121652,7 +124159,10 @@
p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted);
}
var isInfoRoot = p.isRoot(this);
- p.removeFile(this, false, false);
+ // detach is unnecessary since we'll clean the list of containing projects anyways
+ p.removeFile(this, /*fileExists*/ false, /*detachFromProjects*/ false);
+ // If the info was for the external or configured project's root,
+ // add missing file as the root
if (isInfoRoot && p.projectKind !== server.ProjectKind.Inferred) {
p.addMissingFileRoot(this.fileName);
}
@@ -121666,6 +124176,9 @@
case 1:
return this.containingProjects[0];
default:
+ // if this file belongs to multiple projects, the first configured project should be
+ // the default project; if no configured projects, the first external project should
+ // be the default project; otherwise the first inferred project should be the default.
var firstExternalProject = void 0;
for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) {
var project = _a[_i];
@@ -121708,6 +124221,7 @@
ScriptInfo.prototype.saveTo = function (fileName) {
this.host.writeFile(fileName, ts.getSnapshotText(this.textStorage.getSnapshot()));
};
+ /*@internal*/
ScriptInfo.prototype.delayReloadNonMixedContentFile = function () {
ts.Debug.assert(!this.isDynamicOrHasMixedContent());
this.textStorage.delayReloadFromFileIntoText();
@@ -121727,6 +124241,7 @@
}
return false;
};
+ /*@internal*/
ScriptInfo.prototype.getAbsolutePositionAndLineText = function (line) {
return this.textStorage.getAbsolutePositionAndLineText(line);
};
@@ -121743,6 +124258,9 @@
ScriptInfo.prototype.isOrphan = function () {
return !ts.forEach(this.containingProjects, function (p) { return !p.isOrphan(); });
};
+ /**
+ * @param line 1 based index
+ */
ScriptInfo.prototype.lineToTextSpan = function (line) {
return this.textStorage.lineToTextSpan(line);
};
@@ -121753,11 +124271,13 @@
return this.textStorage.positionToLineOffset(position);
};
ScriptInfo.prototype.isJavaScript = function () {
- return this.scriptKind === 1 || this.scriptKind === 2;
+ return this.scriptKind === 1 /* JS */ || this.scriptKind === 2 /* JSX */;
};
+ /*@internal*/
ScriptInfo.prototype.getLineInfo = function () {
return this.textStorage.getLineInfo();
};
+ /*@internal*/
ScriptInfo.prototype.closeSourceMapFileWatcher = function () {
if (this.sourceMapFilePath && !ts.isString(this.sourceMapFilePath)) {
ts.closeFileWatcherOf(this.sourceMapFilePath);
@@ -121775,12 +124295,13 @@
(function (server) {
server.nullTypingsInstaller = {
isKnownTypesPackageName: ts.returnFalse,
+ // Should never be called because we never provide a types registry.
installPackage: ts.notImplemented,
inspectValue: ts.notImplemented,
enqueueInstallTypingsRequest: ts.noop,
attach: ts.noop,
onProjectClosed: ts.noop,
- globalTypingsCacheLocation: undefined
+ globalTypingsCacheLocation: undefined // TODO: GH#18217
};
function setIsEqualTo(arr1, arr2) {
if (arr1 === arr2) {
@@ -121817,6 +124338,7 @@
!setIsEqualTo(opt1.exclude, opt2.exclude);
}
function compilerOptionsChanged(opt1, opt2) {
+ // TODO: add more relevant properties
return opt1.allowJs !== opt2.allowJs;
}
function unresolvedImportsChanged(imports1, imports2) {
@@ -121825,7 +124347,8 @@
}
return !ts.arrayIsEqualTo(imports1, imports2);
}
- var TypingsCache = (function () {
+ /*@internal*/
+ var TypingsCache = /** @class */ (function () {
function TypingsCache(installer) {
this.installer = installer;
this.perProjectCache = ts.createMap();
@@ -121850,6 +124373,8 @@
typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) ||
compilerOptionsChanged(project.getCompilationSettings(), entry.compilerOptions) ||
unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) {
+ // Note: entry is now poisoned since it does not really contain typings for a given combination of compiler options\typings options.
+ // instead it acts as a placeholder to prevent issuing multiple requests
this.perProjectCache.set(project.getProjectName(), {
compilerOptions: project.getCompilationSettings(),
typeAcquisition: typeAcquisition,
@@ -121857,6 +124382,7 @@
unresolvedImports: unresolvedImports,
poisoned: true
});
+ // something has been changed, issue a request to update typings
this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
}
};
@@ -121890,6 +124416,7 @@
ProjectKind[ProjectKind["Configured"] = 1] = "Configured";
ProjectKind[ProjectKind["External"] = 2] = "External";
})(ProjectKind = server.ProjectKind || (server.ProjectKind = {}));
+ /* @internal */
function countEachFileTypes(infos, includeSizes) {
if (includeSizes === void 0) { includeSizes = false; }
var result = {
@@ -121904,16 +124431,16 @@
var info = infos_1[_i];
var fileSize = includeSizes ? info.getTelemetryFileSize() : 0;
switch (info.scriptKind) {
- case 1:
+ case 1 /* JS */:
result.js += 1;
result.jsSize += fileSize;
break;
- case 2:
+ case 2 /* JSX */:
result.jsx += 1;
result.jsxSize += fileSize;
break;
- case 3:
- if (ts.fileExtensionIs(info.fileName, ".d.ts")) {
+ case 3 /* TS */:
+ if (ts.fileExtensionIs(info.fileName, ".d.ts" /* Dts */)) {
result.dts += 1;
result.dtsSize += fileSize;
}
@@ -121922,11 +124449,11 @@
result.tsSize += fileSize;
}
break;
- case 4:
+ case 4 /* TSX */:
result.tsx += 1;
result.tsxSize += fileSize;
break;
- case 7:
+ case 7 /* Deferred */:
result.deferred += 1;
result.deferredSize += fileSize;
break;
@@ -121949,16 +124476,20 @@
return counts.ts === 0 && counts.tsx === 0;
}
server.allFilesAreJsOrDts = allFilesAreJsOrDts;
+ /* @internal */
function hasNoTypeScriptSource(fileNames) {
- return !fileNames.some(function (fileName) { return (ts.fileExtensionIs(fileName, ".ts") && !ts.fileExtensionIs(fileName, ".d.ts")) || ts.fileExtensionIs(fileName, ".tsx"); });
+ return !fileNames.some(function (fileName) { return (ts.fileExtensionIs(fileName, ".ts" /* Ts */) && !ts.fileExtensionIs(fileName, ".d.ts" /* Dts */)) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */); });
}
server.hasNoTypeScriptSource = hasNoTypeScriptSource;
+ /* @internal */
function isScriptInfo(value) {
return value instanceof server.ScriptInfo;
}
server.isScriptInfo = isScriptInfo;
- var Project = (function () {
- function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) {
+ var Project = /** @class */ (function () {
+ /*@internal*/
+ function Project(
+ /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) {
var _this = this;
this.projectName = projectName;
this.projectKind = projectKind;
@@ -121969,14 +124500,37 @@
this.rootFiles = [];
this.rootFilesMap = ts.createMap();
this.plugins = [];
+ /*@internal*/
+ /**
+ * This is map from files to unresolved imports in it
+ * Maop does not contain entries for files that do not have unresolved imports
+ * This helps in containing the set of files to invalidate
+ */
this.cachedUnresolvedImportsPerFile = ts.createMap();
+ /*@internal*/
this.hasAddedorRemovedFiles = false;
+ /**
+ * Last version that was reported.
+ */
this.lastReportedVersion = 0;
+ /**
+ * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one)
+ * This property is changed in 'updateGraph' based on the set of files in program
+ */
this.projectProgramVersion = 0;
+ /**
+ * Current version of the project state. It is changed when:
+ * - new root file was added/removed
+ * - edit happen in some file that is currently included in the project.
+ * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project
+ */
this.projectStateVersion = 0;
this.isInitialLoadPending = ts.returnFalse;
+ /*@internal*/
this.dirty = false;
+ /*@internal*/
this.hasChangedAutomaticTypeDirectiveNames = false;
+ /*@internal*/
this.typingFiles = server.emptyArray;
this.directoryStructureHost = directoryStructureHost;
this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || "");
@@ -121988,6 +124542,7 @@
this.compilerOptions.allowJs = true;
}
else if (hasExplicitListOfFiles || this.compilerOptions.allowJs || this.projectService.hasDeferredExtension()) {
+ // If files are listed explicitly or allowJs is specified, allow all extensions
this.compilerOptions.allowNonTsExtensions = true;
}
this.languageServiceEnabled = !projectService.syntaxOnly;
@@ -122002,7 +124557,8 @@
if (host.realpath) {
this.realpath = function (path) { return host.realpath(path); };
}
- this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, true);
+ // Use the current directory as resolution root only if the project created using current directory string
+ this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, /*logChangesWhenResolvingModule*/ true);
this.languageService = ts.createLanguageService(this, this.documentRegistry, projectService.syntaxOnly);
if (lastFileExceededProgramSize) {
this.disableLanguageService(lastFileExceededProgramSize);
@@ -122021,7 +124577,7 @@
Project.resolveModule = function (moduleName, initialDir, host, log) {
var resolvedPath = ts.normalizeSlashes(host.resolvePath(ts.combinePaths(initialDir, "node_modules")));
log("Loading " + moduleName + " from " + initialDir + " (resolved to " + resolvedPath + ")");
- var result = host.require(resolvedPath, moduleName);
+ var result = host.require(resolvedPath, moduleName); // TODO: GH#18217
if (result.error) {
var err = result.error.stack || result.error.message || JSON.stringify(result.error);
log("Failed to load module '" + moduleName + "': " + err);
@@ -122035,6 +124591,7 @@
Project.prototype.installPackage = function (options) {
return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) }));
};
+ /* @internal */
Project.prototype.inspectValue = function (options) {
return this.typingsCache.inspectValue(options);
};
@@ -122045,9 +124602,11 @@
enumerable: true,
configurable: true
});
+ // Method of LanguageServiceHost
Project.prototype.getCompilationSettings = function () {
return this.compilerOptions;
};
+ // Method to support public API
Project.prototype.getCompilerOptions = function () {
return this.getCompilationSettings();
};
@@ -122068,6 +124627,7 @@
var result;
this.rootFilesMap.forEach(function (value) {
if (_this.languageServiceEnabled || (isScriptInfo(value) && value.isScriptOpen())) {
+ // if language service is disabled - process only files that are open
(result || (result = [])).push(isScriptInfo(value) ? value.fileName : value);
}
});
@@ -122078,6 +124638,7 @@
if (scriptInfo) {
var existingValue = this.rootFilesMap.get(scriptInfo.path);
if (existingValue !== scriptInfo && existingValue !== undefined) {
+ // This was missing path earlier but now the file exists. Update the root
this.rootFiles.push(scriptInfo);
this.rootFilesMap.set(scriptInfo.path, scriptInfo);
}
@@ -122087,11 +124648,11 @@
};
Project.prototype.getScriptKind = function (fileName) {
var info = this.getOrCreateScriptInfoAndAttachToProject(fileName);
- return (info && info.scriptKind);
+ return (info && info.scriptKind); // TODO: GH#18217
};
Project.prototype.getScriptVersion = function (filename) {
var info = this.getOrCreateScriptInfoAndAttachToProject(filename);
- return (info && info.getLatestVersion());
+ return (info && info.getLatestVersion()); // TODO: GH#18217
};
Project.prototype.getScriptSnapshot = function (filename) {
var scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename);
@@ -122122,6 +124683,8 @@
return this.projectService.host.writeFile(fileName, content);
};
Project.prototype.fileExists = function (file) {
+ // As an optimization, don't hit the disks for files we already know don't exist
+ // (because we're watching for their creation).
var path = this.toPath(file);
return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file);
};
@@ -122135,33 +124698,41 @@
return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference);
};
Project.prototype.directoryExists = function (path) {
- return this.directoryStructureHost.directoryExists(path);
+ return this.directoryStructureHost.directoryExists(path); // TODO: GH#18217
};
Project.prototype.getDirectories = function (path) {
- return this.directoryStructureHost.getDirectories(path);
+ return this.directoryStructureHost.getDirectories(path); // TODO: GH#18217
};
+ /*@internal*/
Project.prototype.getCachedDirectoryStructureHost = function () {
- return undefined;
+ return undefined; // TODO: GH#18217
};
+ /*@internal*/
Project.prototype.toPath = function (fileName) {
return ts.toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName);
};
+ /*@internal*/
Project.prototype.watchDirectoryOfFailedLookupLocation = function (directory, cb, flags) {
- return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Failed Lookup Locations", this);
+ return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Failed Lookup Locations" /* FailedLookupLocations */, this);
};
+ /*@internal*/
Project.prototype.onInvalidatedResolution = function () {
this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
};
+ /*@internal*/
Project.prototype.watchTypeRootsDirectory = function (directory, cb, flags) {
- return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type roots", this);
+ return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type roots" /* TypeRoots */, this);
};
+ /*@internal*/
Project.prototype.onChangedAutomaticTypeDirectiveNames = function () {
this.hasChangedAutomaticTypeDirectiveNames = true;
this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
};
+ /*@internal*/
Project.prototype.getGlobalCache = function () {
return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : undefined;
};
+ /*@internal*/
Project.prototype.writeLog = function (s) {
this.projectService.logger.info(s);
};
@@ -122176,6 +124747,9 @@
this.compilerOptions.noEmitForJsFiles = true;
}
};
+ /**
+ * Get the errors that dont have any file name associated
+ */
Project.prototype.getGlobalProjectErrors = function () {
return server.emptyArray;
};
@@ -122189,12 +124763,15 @@
}
return this.languageService;
};
+ /** @internal */
Project.prototype.getSourceMapper = function () {
return this.getLanguageService().getSourceMapper();
};
+ /*@internal*/
Project.prototype.getDocumentPositionMapper = function (generatedFileName, sourceFileName) {
return this.projectService.getDocumentPositionMapper(this, generatedFileName, sourceFileName);
};
+ /*@internal*/
Project.prototype.getSourceFileLike = function (fileName) {
return this.projectService.getSourceFileLike(fileName, this);
};
@@ -122208,13 +124785,18 @@
}
server.updateProjectIfDirty(this);
this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState);
- return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; });
+ return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), // TODO: GH#18217
+ function (// TODO: GH#18217
+ sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; });
};
+ /**
+ * Returns true if emit was conducted
+ */
Project.prototype.emitFile = function (scriptInfo, writeFile) {
if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) {
return false;
}
- var _a = this.getLanguageService(false).getEmitOutput(scriptInfo.fileName), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles;
+ var _a = this.getLanguageService(/*ensureSynchronized*/ false).getEmitOutput(scriptInfo.fileName), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles;
if (!emitSkipped) {
for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) {
var outputFile = outputFiles_1[_i];
@@ -122230,7 +124812,7 @@
}
this.languageServiceEnabled = true;
this.lastFileExceededProgramSize = undefined;
- this.projectService.onUpdateLanguageServiceStateForProject(this, true);
+ this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ true);
};
Project.prototype.disableLanguageService = function (lastFileExceededProgramSize) {
if (!this.languageServiceEnabled) {
@@ -122242,13 +124824,14 @@
this.lastFileExceededProgramSize = lastFileExceededProgramSize;
this.builderState = undefined;
this.resolutionCache.closeTypeRootsWatch();
- this.projectService.onUpdateLanguageServiceStateForProject(this, false);
+ this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ false);
};
Project.prototype.getProjectName = function () {
return this.projectName;
};
Project.prototype.removeLocalTypingsFromTypeAcquisition = function (newTypeAcquisition) {
if (!newTypeAcquisition || !newTypeAcquisition.include) {
+ // Nothing to filter out, so just return as-is
return newTypeAcquisition;
}
return __assign({}, newTypeAcquisition, { include: this.removeExistingTypings(newTypeAcquisition.include) });
@@ -122275,6 +124858,7 @@
}
return this.program.getSourceFileByPath(path);
};
+ /* @internal */
Project.prototype.getSourceFileOrConfigFile = function (path) {
var options = this.program.getCompilerOptions();
return path === options.configFilePath ? options.configFile : this.getSourceFile(path);
@@ -122282,6 +124866,9 @@
Project.prototype.close = function () {
var _this = this;
if (this.program) {
+ // if we have a program - release all files that are enlisted in program but arent root
+ // The releasing of the roots happens later
+ // The project could have pending update remaining and hence the info could be in the files but not in program graph
for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) {
var f = _a[_i];
this.detachScriptInfoIfNotRoot(f.fileName);
@@ -122292,7 +124879,9 @@
}
});
}
+ // Release external files
ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); });
+ // Always remove root files from the project
for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) {
var root = _c[_b];
root.detachFromProject(this);
@@ -122307,15 +124896,19 @@
this.resolutionCache = undefined;
this.cachedUnresolvedImportsPerFile = undefined;
this.directoryStructureHost = undefined;
+ // Clean up file watchers waiting for missing files
if (this.missingFilesMap) {
ts.clearMap(this.missingFilesMap, ts.closeFileWatcher);
this.missingFilesMap = undefined;
}
+ // signal language service to release source files acquired from document registry
this.languageService.dispose();
this.languageService = undefined;
};
Project.prototype.detachScriptInfoIfNotRoot = function (uncheckedFilename) {
var info = this.projectService.getScriptInfo(uncheckedFilename);
+ // We might not find the script info in case its not associated with the project any more
+ // and project graph was not updated (eg delayed update graph in case of files changed/deleted on the disk)
if (info && !this.isRoot(info)) {
info.detachFromProject(this);
}
@@ -122326,12 +124919,14 @@
Project.prototype.hasRoots = function () {
return this.rootFiles && this.rootFiles.length > 0;
};
+ /*@internal*/
Project.prototype.isOrphan = function () {
return false;
};
Project.prototype.getRootFiles = function () {
return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; });
};
+ /*@internal*/
Project.prototype.getRootFilesMap = function () {
return this.rootFilesMap;
};
@@ -122341,6 +124936,7 @@
Project.prototype.getScriptInfos = function () {
var _this = this;
if (!this.languageServiceEnabled) {
+ // if language service is not enabled - return just root files
return this.rootFiles;
}
return ts.map(this.program.getSourceFiles(), function (sourceFile) {
@@ -122357,6 +124953,7 @@
return [];
}
if (!this.languageServiceEnabled) {
+ // if language service is disabled assume that all files in program are root files + default library
var rootFiles = this.getRootFiles();
if (this.compilerOptions) {
var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions);
@@ -122425,6 +125022,7 @@
Project.prototype.isRoot = function (info) {
return this.rootFilesMap && this.rootFilesMap.get(info.path) === info;
};
+ // add a root file to project
Project.prototype.addRoot = function (info) {
ts.Debug.assert(!this.isRoot(info));
this.rootFiles.push(info);
@@ -122432,6 +125030,7 @@
info.attachToProject(this);
this.markAsDirty();
};
+ // add a root file that doesnt exist on host
Project.prototype.addMissingFileRoot = function (fileName) {
var path = this.projectService.toPath(fileName);
this.rootFilesMap.set(path, fileName);
@@ -122442,6 +125041,7 @@
this.removeRoot(info);
}
if (fileExists) {
+ // If file is present, just remove the resolutions for the file
this.resolutionCache.removeResolutionsOfFile(info.path);
}
else {
@@ -122462,9 +125062,14 @@
this.dirty = true;
}
};
+ /* @internal */
Project.prototype.onFileAddedOrRemoved = function () {
this.hasAddedorRemovedFiles = true;
};
+ /**
+ * Updates set of files that contribute to this project
+ * @returns: true if set of files in the project stays the same and false - otherwise.
+ */
Project.prototype.updateGraph = function () {
this.resolutionCache.startRecordingFilesWithChangedResolutions();
var hasNewProgram = this.updateGraphWorker();
@@ -122473,9 +125078,18 @@
var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray;
for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) {
var file = changedFiles_1[_i];
+ // delete cached information for changed files
this.cachedUnresolvedImportsPerFile.delete(file);
}
+ // update builder only if language service is enabled
+ // otherwise tell it to drop its internal state
if (this.languageServiceEnabled) {
+ // 1. no changes in structure, no changes in unresolved imports - do nothing
+ // 2. no changes in structure, unresolved imports were changed - collect unresolved imports for all files
+ // (can reuse cached imports for files that were not changed)
+ // 3. new files were added/removed, but compilation settings stays the same - collect unresolved imports for all new/modified files
+ // (can reuse cached imports for files that were not changed)
+ // 4. compilation settings were changed in the way that might affect module resolution - drop all caches and collect all data from the scratch
if (hasNewProgram || changedFiles.length) {
this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile);
}
@@ -122489,12 +125103,16 @@
}
return !hasNewProgram;
};
+ /*@internal*/
Project.prototype.updateTypingFiles = function (typingFiles) {
var _this = this;
- ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); });
+ ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()),
+ /*inserted*/ ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); });
this.typingFiles = typingFiles;
+ // Invalidate files with unresolved imports
this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile);
};
+ /* @internal */
Project.prototype.getCurrentProgram = function () {
return this.program;
};
@@ -122510,11 +125128,14 @@
var start = ts.timestamp();
this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution();
this.resolutionCache.startCachingPerDirectoryResolution();
- this.program = this.languageService.getProgram();
+ this.program = this.languageService.getProgram(); // TODO: GH#18217
this.dirty = false;
this.resolutionCache.finishCachingPerDirectoryResolution();
ts.Debug.assert(oldProgram === undefined || this.program !== undefined);
- var hasNewProgram = this.program && (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2)));
+ // bump up the version if
+ // - oldProgram is not set - this is a first time updateGraph is called
+ // - newProgram is different from the old program and structure of the old program was not reused.
+ var hasNewProgram = this.program && (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2 /* Completely */)));
this.hasChangedAutomaticTypeDirectiveNames = false;
if (hasNewProgram) {
if (oldProgram) {
@@ -122522,6 +125143,8 @@
var f = _a[_i];
var newFile = this.program.getSourceFileByPath(f.resolvedPath);
if (!newFile || (f.resolvedPath === f.path && newFile.resolvedPath !== f.path)) {
+ // new program does not contain this file - detach it from the project
+ // - remove resolutions only if the new program doesnt contain source file by the path (not resolvedPath since path is used for resolution)
this.detachScriptInfoFromProject(f.fileName, !!this.program.getSourceFileByPath(f.path));
}
}
@@ -122531,14 +125154,22 @@
}
});
}
- ts.updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = ts.createMap()), function (missingFilePath) { return _this.addMissingFileWatcher(missingFilePath); });
+ // Update the missing file paths watcher
+ ts.updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = ts.createMap()),
+ // Watch the missing files
+ function (missingFilePath) { return _this.addMissingFileWatcher(missingFilePath); });
+ // Watch the type locations that would be added to program as part of automatic type resolutions
if (this.languageServiceEnabled) {
this.resolutionCache.updateTypeRootsWatch();
}
}
var oldExternalFiles = this.externalFiles || server.emptyArray;
this.externalFiles = this.getExternalFiles();
- ts.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), function (inserted) {
+ ts.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()),
+ // Ensure a ScriptInfo is created for new external files. This is performed indirectly
+ // by the LSHost for files in the program when the program is retrieved above but
+ // the program doesn't contain external files so this must be done explicitly.
+ function (inserted) {
var scriptInfo = _this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, _this.currentDirectory, _this.directoryStructureHost);
scriptInfo.attachToProject(_this);
}, function (removed) { return _this.detachScriptInfoFromProject(removed); });
@@ -122564,9 +125195,10 @@
if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) {
_this.missingFilesMap.delete(missingFilePath);
fileWatcher.close();
+ // When a missing file is created, we should update the graph.
_this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(_this);
}
- }, ts.PollingInterval.Medium, "Missing file", this);
+ }, ts.PollingInterval.Medium, "Missing file" /* MissingFile */, this);
return fileWatcher;
};
Project.prototype.isWatchedMissingFile = function (path) {
@@ -122596,6 +125228,7 @@
}
return strBuilder;
};
+ /*@internal*/
Project.prototype.print = function (counter) {
this.writeLog("Project '" + this.projectName + "' (" + ProjectKind[this.projectKind] + ") " + (counter === undefined ? "" : counter));
this.writeLog(this.filesToString(this.projectService.logger.hasLevel(server.LogLevel.verbose)));
@@ -122608,6 +125241,7 @@
this.compilerOptions = compilerOptions;
this.setInternalCompilerOptionsForEmittingJsFiles();
if (ts.changesAffectModuleResolution(oldOptions, compilerOptions)) {
+ // reset cached unresolved imports if changes in compiler options affected module resolution
this.cachedUnresolvedImportsPerFile.clear();
this.lastCachedUnresolvedImportsList = undefined;
this.resolutionCache.clear();
@@ -122615,7 +125249,9 @@
this.markAsDirty();
}
};
+ /* @internal */
Project.prototype.getChangesSinceVersion = function (lastKnownVersion) {
+ // Update the graph only if initial configured project load is not pending
if (!this.isInitialLoadPending()) {
server.updateProjectIfDirty(this);
}
@@ -122629,10 +125265,13 @@
};
var updatedFileNames = this.updatedFileNames;
this.updatedFileNames = undefined;
+ // check if requested version is the same that we have reported last time
if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
+ // if current structure version is the same - return info without any changes
if (this.projectProgramVersion === this.lastReportedVersion && !updatedFileNames) {
return { info: info, projectErrors: this.getGlobalProjectErrors() };
}
+ // compute and return the difference
var lastReportedFileNames_1 = this.lastReportedFileNames;
var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); });
var currentFiles_1 = ts.arrayToSet(this.getFileNames().concat(externalFiles));
@@ -122654,6 +125293,7 @@
return { info: info, changes: { added: added_1, removed: removed_1, updated: updated }, projectErrors: this.getGlobalProjectErrors() };
}
else {
+ // unknown version - return everything
var projectFileNames = this.getFileNames();
var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); });
var allFiles = projectFileNames.concat(externalFiles);
@@ -122662,6 +125302,7 @@
return { info: info, files: allFiles, projectErrors: this.getGlobalProjectErrors() };
}
};
+ // remove a root file from project
Project.prototype.removeRoot = function (info) {
ts.orderedRemoveItem(this.rootFiles, info);
this.rootFilesMap.delete(info.path);
@@ -122672,17 +125313,23 @@
this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
return;
}
+ // Search our peer node_modules, then any globally-specified probe paths
+ // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/
var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations);
if (this.projectService.globalPlugins) {
var _loop_1 = function (globalPluginName) {
+ // Skip empty names from odd commandline parses
if (!globalPluginName)
return "continue";
+ // Skip already-locally-loaded plugins
if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; }))
return "continue";
+ // Provide global: true so plugins can detect why they can't find their config
this_1.projectService.logger.info("Loading global plugin " + globalPluginName);
this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides);
};
var this_1 = this;
+ // Enable global plugins with synthetic configuration entries
for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) {
var globalPluginName = _a[_i];
_loop_1(globalPluginName);
@@ -122701,6 +125348,7 @@
if (resolvedModule) {
var configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name);
if (configurationOverride) {
+ // Preserve the name property since it's immutable
var pluginName = pluginConfigEntry.name;
pluginConfigEntry = configurationOverride;
pluginConfigEntry.name = pluginName;
@@ -122741,6 +125389,7 @@
this.projectService.logger.info("Plugin activation failed: " + e);
}
};
+ /*@internal*/
Project.prototype.onPluginConfigurationChanged = function (pluginName, configuration) {
this.plugins.filter(function (plugin) { return plugin.name === pluginName; }).forEach(function (plugin) {
if (plugin.module.onConfigurationChanged) {
@@ -122748,6 +125397,7 @@
}
});
};
+ /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */
Project.prototype.refreshDiagnostics = function () {
this.projectService.sendProjectsUpdatedInBackgroundEvent();
};
@@ -122766,6 +125416,7 @@
return server.emptyArray;
var unresolvedImports;
file.resolvedModules.forEach(function (resolvedModule, name) {
+ // pick unresolved non-relative names
if ((!resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) &&
!ts.isExternalModuleNameRelative(name) &&
!ambientModules.some(function (m) { return m === name; })) {
@@ -122775,10 +125426,19 @@
return unresolvedImports || server.emptyArray;
});
}
- var InferredProject = (function (_super) {
+ /**
+ * If a file is opened and no tsconfig (or jsconfig) is found,
+ * the file and its imports/references are put into an InferredProject.
+ */
+ var InferredProject = /** @class */ (function (_super) {
__extends(InferredProject, _super);
+ /*@internal*/
function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory, pluginConfigOverrides) {
- var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, undefined, compilerOptions, false, projectService.host, currentDirectory) || this;
+ var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry,
+ // TODO: GH#18217
+ /*files*/ undefined,
+ /*lastFileExceededProgramSize*/ undefined, compilerOptions,
+ /*compileOnSaveEnabled*/ false, projectService.host, currentDirectory) || this;
_this._isJsInferredProject = false;
_this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath);
if (!projectRootPath && !projectService.useSingleInferredProject) {
@@ -122794,6 +125454,7 @@
}
};
InferredProject.prototype.setCompilerOptions = function (options) {
+ // Avoid manipulating the given options directly
if (!options && !this.getCompilationSettings()) {
return;
}
@@ -122811,7 +125472,7 @@
ts.Debug.assert(info.isScriptOpen());
this.projectService.startWatchingConfigFilesForInferredProjectRoot(info);
if (!this._isJsInferredProject && info.isJavaScript()) {
- this.toggleJsInferredProject(true);
+ this.toggleJsInferredProject(/*isJsInferredProject*/ true);
}
_super.prototype.addRoot.call(this, info);
};
@@ -122820,14 +125481,18 @@
_super.prototype.removeRoot.call(this, info);
if (this._isJsInferredProject && info.isJavaScript()) {
if (ts.every(this.getRootScriptInfos(), function (rootInfo) { return !rootInfo.isJavaScript(); })) {
- this.toggleJsInferredProject(false);
+ this.toggleJsInferredProject(/*isJsInferredProject*/ false);
}
}
};
+ /*@internal*/
InferredProject.prototype.isOrphan = function () {
return !this.hasRoots();
};
InferredProject.prototype.isProjectWithSingleRoot = function () {
+ // - when useSingleInferredProject is not set and projectRootPath is not set,
+ // we can guarantee that this will be the only root
+ // - other wise it has single root if it has single root script info
return (!this.projectRootPath && !this.projectService.useSingleInferredProject) ||
this.getRootScriptInfos().length === 1;
};
@@ -122854,17 +125519,34 @@
return InferredProject;
}(Project));
server.InferredProject = InferredProject;
- var ConfiguredProject = (function (_super) {
+ /**
+ * If a file is opened, the server will look for a tsconfig (or jsconfig)
+ * and if successfull create a ConfiguredProject for it.
+ * Otherwise it will create an InferredProject.
+ */
+ var ConfiguredProject = /** @class */ (function (_super) {
__extends(ConfiguredProject, _super);
+ /*@internal*/
function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) {
- var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, false, undefined, {}, false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this;
+ var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry,
+ /*hasExplicitListOfFiles*/ false,
+ /*lastFileExceededProgramSize*/ undefined,
+ /*compilerOptions*/ {},
+ /*compileOnSaveEnabled*/ false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this;
+ /*@internal*/
_this.canConfigFileJsonReportNoInputFiles = false;
+ /** Ref count to the project when opened from external project */
_this.externalProjectRefCount = 0;
_this.isInitialLoadPending = ts.returnTrue;
+ /*@internal*/
_this.sendLoadingProjectFinish = false;
_this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName));
return _this;
}
+ /**
+ * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph
+ * @returns: true if set of files in the project stays the same and false - otherwise.
+ */
ConfiguredProject.prototype.updateGraph = function () {
this.isInitialLoadPending = ts.returnFalse;
var reloadLevel = this.pendingReload;
@@ -122885,9 +125567,9 @@
}
this.projectService.sendProjectLoadingFinishEvent(this);
this.projectService.sendProjectTelemetry(this);
- this.projectService.sendSurveyReady(this);
return result;
};
+ /*@internal*/
ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () {
return this.directoryStructureHost;
};
@@ -122900,22 +125582,27 @@
ConfiguredProject.prototype.updateReferences = function (refs) {
this.projectReferences = refs;
};
+ /*@internal*/
ConfiguredProject.prototype.forEachResolvedProjectReference = function (cb) {
var program = this.getCurrentProgram();
return program && program.forEachResolvedProjectReference(cb);
};
+ /*@internal*/
ConfiguredProject.prototype.enablePluginsWithOptions = function (options, pluginConfigOverrides) {
var host = this.projectService.host;
if (!host.require) {
this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
return;
}
+ // Search our peer node_modules, then any globally-specified probe paths
+ // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/
var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations);
if (this.projectService.allowLocalPluginLoads) {
var local = ts.getDirectoryPath(this.canonicalConfigFilePath);
this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths");
searchPaths.unshift(local);
}
+ // Enable tsconfig-specified plugins
if (options.plugins) {
for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) {
var pluginConfigEntry = _a[_i];
@@ -122924,9 +125611,15 @@
}
this.enableGlobalPlugins(options, pluginConfigOverrides);
};
+ /**
+ * Get the errors that dont have any file name associated
+ */
ConfiguredProject.prototype.getGlobalProjectErrors = function () {
return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray;
};
+ /**
+ * Get all the project errors
+ */
ConfiguredProject.prototype.getAllProjectErrors = function () {
return this.projectErrors || server.emptyArray;
};
@@ -122939,10 +125632,14 @@
ConfiguredProject.prototype.getTypeAcquisition = function () {
return this.typeAcquisition;
};
+ /*@internal*/
ConfiguredProject.prototype.watchWildcards = function (wildcardDirectories) {
var _this = this;
- ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = ts.createMap()), wildcardDirectories, function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); });
+ ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = ts.createMap()), wildcardDirectories,
+ // Create new directory watcher
+ function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); });
};
+ /*@internal*/
ConfiguredProject.prototype.stopWatchingWildCards = function () {
if (this.directoriesWatchedForWildcards) {
ts.clearMap(this.directoriesWatchedForWildcards, ts.closeFileWatcherOf);
@@ -122959,42 +125656,61 @@
this.configFileSpecs = undefined;
_super.prototype.close.call(this);
};
+ /* @internal */
ConfiguredProject.prototype.addExternalProjectReference = function () {
this.externalProjectRefCount++;
};
+ /* @internal */
ConfiguredProject.prototype.deleteExternalProjectReference = function () {
this.externalProjectRefCount--;
};
+ /** Returns true if the project is needed by any of the open script info/external project */
+ /* @internal */
ConfiguredProject.prototype.hasOpenRef = function () {
var _this = this;
if (!!this.externalProjectRefCount) {
return true;
}
+ // Closed project doesnt have any reference
if (this.isClosed()) {
return false;
}
var configFileExistenceInfo = this.projectService.getConfigFileExistenceInfo(this);
if (this.projectService.hasPendingProjectUpdate(this)) {
+ // If there is pending update for this project,
+ // we dont know if this project would be needed by any of the open files impacted by this config file
+ // In that case keep the project alive if there are open files impacted by this project
return !!configFileExistenceInfo.openFilesImpactedByConfigFile.size;
}
+ // If there is no pending update for this project,
+ // We know exact set of open files that get impacted by this configured project as the files in the project
+ // The project is referenced only if open files impacted by this project are present in this project
return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false;
};
+ /*@internal*/
ConfiguredProject.prototype.hasExternalProjectRef = function () {
return !!this.externalProjectRefCount;
};
ConfiguredProject.prototype.getEffectiveTypeRoots = function () {
return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || [];
};
+ /*@internal*/
ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (fileNameResult) {
ts.updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles);
};
return ConfiguredProject;
}(Project));
server.ConfiguredProject = ConfiguredProject;
- var ExternalProject = (function (_super) {
+ /**
+ * Project whose configuration is handled externally, such as in a '.csproj'.
+ * These are created only if a host explicitly calls `openExternalProject`.
+ */
+ var ExternalProject = /** @class */ (function (_super) {
__extends(ExternalProject, _super);
+ /*@internal*/
function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath) {
- var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, true, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, projectService.host, ts.getDirectoryPath(projectFilePath || ts.normalizeSlashes(externalProjectName))) || this;
+ var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry,
+ /*hasExplicitListOfFiles*/ true, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, projectService.host, ts.getDirectoryPath(projectFilePath || ts.normalizeSlashes(externalProjectName))) || this;
_this.externalProjectName = externalProjectName;
_this.compileOnSaveEnabled = compileOnSaveEnabled;
_this.excludedFiles = [];
@@ -123003,7 +125719,6 @@
ExternalProject.prototype.updateGraph = function () {
var result = _super.prototype.updateGraph.call(this);
this.projectService.sendProjectTelemetry(this);
- this.projectService.sendSurveyReady(this);
return result;
};
ExternalProject.prototype.getExcludedFiles = function () {
@@ -123029,11 +125744,12 @@
var server;
(function (server) {
server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
+ /*@internal*/
server.maxFileSize = 4 * 1024 * 1024;
+ // tslint:disable variable-name
server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground";
server.ProjectLoadingStartEvent = "projectLoadingStart";
server.ProjectLoadingFinishEvent = "projectLoadingFinish";
- server.SurveyReady = "surveyReady";
server.LargeFileReferencedEvent = "largeFileReferenced";
server.ConfigFileDiagEvent = "configFileDiag";
server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
@@ -123045,6 +125761,7 @@
var option = commandLineOptions_1[_i];
if (typeof option.type === "object") {
var optionMap = option.type;
+ // verify that map contains only numbers
optionMap.forEach(function (value) {
ts.Debug.assert(typeof value === "number");
});
@@ -123059,25 +125776,47 @@
block: ts.IndentStyle.Block,
smart: ts.IndentStyle.Smart
});
+ /**
+ * How to understand this block:
+ * * The 'match' property is a regexp that matches a filename.
+ * * If 'match' is successful, then:
+ * * All files from 'exclude' are removed from the project. See below.
+ * * All 'types' are included in ATA
+ * * What the heck is 'exclude' ?
+ * * An array of an array of strings and numbers
+ * * Each array is:
+ * * An array of strings and numbers
+ * * The strings are literals
+ * * The numbers refer to capture group indices from the 'match' regexp
+ * * Remember that '1' is the first group
+ * * These are concatenated together to form a new regexp
+ * * Filenames matching these regexps are excluded from the project
+ * This default value is tested in tsserverProjectSystem.ts; add tests there
+ * if you are changing this so that you can be sure your regexp works!
+ */
var defaultTypeSafeList = {
"jquery": {
+ // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js")
match: /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i,
types: ["jquery"]
},
"WinJS": {
+ // e.g. c:/temp/UWApp1/lib/winjs-4.0.1/js/base.js
match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i,
exclude: [["^", 1, "/.*"]],
- types: ["winjs"]
+ types: ["winjs"] // And fetch the @types package for WinJS
},
"Kendo": {
+ // e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js
match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i,
exclude: [["^", 1, "/.*"]],
types: ["kendo-ui"]
},
"Office Nuget": {
+ // e.g. /scripts/Office/1/excel-15.debug.js
match: /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i,
exclude: [["^", 1, "/.*"]],
- types: ["office"]
+ types: ["office"] // @types package to fetch instead
},
"References": {
match: /^(.*\/_references\.js)$/i,
@@ -123109,18 +125848,19 @@
function convertScriptKindName(scriptKindName) {
switch (scriptKindName) {
case "JS":
- return 1;
+ return 1 /* JS */;
case "JSX":
- return 2;
+ return 2 /* JSX */;
case "TS":
- return 3;
+ return 3 /* TS */;
case "TSX":
- return 4;
+ return 4 /* TSX */;
default:
- return 0;
+ return 0 /* Unknown */;
}
}
server.convertScriptKindName = convertScriptKindName;
+ /*@internal*/
function convertUserPreferences(preferences) {
var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]);
return userPreferences;
@@ -123142,7 +125882,7 @@
});
}
}
- return result;
+ return result; // TODO: GH#18217
},
hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); },
};
@@ -123178,6 +125918,7 @@
function isScriptInfoWatchedFromNodeModules(info) {
return !info.isScriptOpen() && info.mTime !== undefined;
}
+ /*@internal*/
function updateProjectIfDirty(project) {
return project.dirty && project.updateGraph();
}
@@ -123187,28 +125928,67 @@
project.projectOptions = true;
}
}
- var ProjectService = (function () {
+ var ProjectService = /** @class */ (function () {
function ProjectService(opts) {
var _this = this;
+ /**
+ * Container of all known scripts
+ */
+ /*@internal*/
this.filenameToScriptInfo = ts.createMap();
this.scriptInfoInNodeModulesWatchers = ts.createMap();
+ /**
+ * Contains all the deleted script info's version information so that
+ * it does not reset when creating script info again
+ * (and could have potentially collided with version where contents mismatch)
+ */
this.filenameToScriptInfoVersion = ts.createMap();
+ // Set of all '.js' files ever opened.
this.allJsFilesForOpenFileTelemetry = ts.createMap();
+ /**
+ * maps external project file name to list of config files that were the part of this project
+ */
this.externalProjectToConfiguredProjectMap = ts.createMap();
+ /**
+ * external projects (configuration and list of root files is not controlled by tsserver)
+ */
this.externalProjects = [];
+ /**
+ * projects built from openFileRoots
+ */
this.inferredProjects = [];
+ /**
+ * projects specified by a tsconfig.json file
+ */
this.configuredProjects = ts.createMap();
+ /**
+ * Open files: with value being project root path, and key being Path of the file that is open
+ */
this.openFiles = ts.createMap();
+ /**
+ * Map of open files that are opened without complete path but have projectRoot as current directory
+ */
this.openFilesWithNonRootedDiskPath = ts.createMap();
this.compilerOptionsForInferredProjectsPerProjectRoot = ts.createMap();
+ /**
+ * Project size for configured or external projects
+ */
this.projectToSizeMap = ts.createMap();
+ /**
+ * This is a map of config file paths existance that doesnt need query to disk
+ * - The entry can be present because there is inferred project that needs to watch addition of config file to directory
+ * In this case the exists could be true/false based on config file is present or not
+ * - Or it is present if we have configured project open with config file at that location
+ * In this case the exists property is always true
+ */
this.configFileExistenceInfoCache = ts.createMap();
this.safelist = defaultTypeSafeList;
this.legacySafelist = ts.createMap();
this.pendingProjectUpdates = ts.createMap();
+ /* @internal */
this.pendingEnsureProjectForOpenFiles = false;
+ /** Tracks projects that we have already sent telemetry for. */
this.seenProjects = ts.createMap();
- this.seenSurveyProjects = ts.createMap();
this.host = opts.host;
this.logger = opts.logger;
this.cancellationToken = opts.cancellationToken;
@@ -123256,26 +126036,33 @@
ProjectService.prototype.toPath = function (fileName) {
return ts.toPath(fileName, this.currentDirectory, this.toCanonicalFileName);
};
+ /*@internal*/
ProjectService.prototype.getExecutingFilePath = function () {
return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath());
};
+ /*@internal*/
ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) {
return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory());
};
+ /*@internal*/
ProjectService.prototype.setDocument = function (key, path, sourceFile) {
var info = ts.Debug.assertDefined(this.getScriptInfoForPath(path));
info.cacheSourceFile = { key: key, sourceFile: sourceFile };
};
+ /*@internal*/
ProjectService.prototype.getDocument = function (key, path) {
var info = this.getScriptInfoForPath(path);
return info && info.cacheSourceFile && info.cacheSourceFile.key === key ? info.cacheSourceFile.sourceFile : undefined;
};
+ /* @internal */
ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () {
this.ensureProjectStructuresUptoDate();
};
+ /* @internal */
ProjectService.prototype.getCompilerOptionsForInferredProjects = function () {
return this.compilerOptionsForInferredProjects;
};
+ /* @internal */
ProjectService.prototype.onUpdateLanguageServiceStateForProject = function (project, languageServiceEnabled) {
if (!this.eventHandler) {
return;
@@ -123288,16 +126075,18 @@
};
ProjectService.prototype.loadTypesMap = function () {
try {
- var fileContent = this.host.readFile(this.typesMapLocation);
+ var fileContent = this.host.readFile(this.typesMapLocation); // TODO: GH#18217
if (fileContent === undefined) {
this.logger.info("Provided types map file \"" + this.typesMapLocation + "\" doesn't exist");
return;
}
var raw = JSON.parse(fileContent);
+ // Parse the regexps
for (var _i = 0, _a = Object.keys(raw.typesMap); _i < _a.length; _i++) {
var k = _a[_i];
raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i");
}
+ // raw is now fixed and ready
this.safelist = raw.typesMap;
for (var key in raw.simpleMap) {
if (raw.simpleMap.hasOwnProperty(key)) {
@@ -123318,10 +126107,12 @@
}
switch (response.kind) {
case server.ActionSet:
+ // Update the typing files and update the project
project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings));
break;
case server.ActionInvalidate:
- this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, true);
+ // Do not clear resolution cache, there was changes detected in typings, so enque typing request and let it get us correct results
+ this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, /*forceRefresh*/ true);
return;
}
this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project);
@@ -123329,13 +126120,15 @@
ProjectService.prototype.delayEnsureProjectForOpenFiles = function () {
var _this = this;
this.pendingEnsureProjectForOpenFiles = true;
- this.throttledOperations.schedule("*ensureProjectForOpenFiles*", 250, function () {
+ this.throttledOperations.schedule("*ensureProjectForOpenFiles*", /*delay*/ 250, function () {
if (_this.pendingProjectUpdates.size !== 0) {
_this.delayEnsureProjectForOpenFiles();
}
else {
if (_this.pendingEnsureProjectForOpenFiles) {
_this.ensureProjectForOpenFiles();
+ // Send the event to notify that there were background project updates
+ // send current list of open files
_this.sendProjectsUpdatedInBackgroundEvent();
}
}
@@ -123346,15 +126139,17 @@
project.markAsDirty();
var projectName = project.getProjectName();
this.pendingProjectUpdates.set(projectName, project);
- this.throttledOperations.schedule(projectName, 250, function () {
+ this.throttledOperations.schedule(projectName, /*delay*/ 250, function () {
if (_this.pendingProjectUpdates.delete(projectName)) {
updateProjectIfDirty(project);
}
});
};
+ /*@internal*/
ProjectService.prototype.hasPendingProjectUpdate = function (project) {
return this.pendingProjectUpdates.has(project.getProjectName());
};
+ /* @internal */
ProjectService.prototype.sendProjectsUpdatedInBackgroundEvent = function () {
var _this = this;
if (!this.eventHandler) {
@@ -123368,12 +126163,7 @@
};
this.eventHandler(event);
};
- ProjectService.prototype.sendSurveyReadyEvent = function (surveyId) {
- if (!this.eventHandler) {
- return;
- }
- this.eventHandler({ eventName: server.SurveyReady, data: { surveyId: surveyId } });
- };
+ /* @internal */
ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) {
if (!this.eventHandler) {
return;
@@ -123384,6 +126174,7 @@
};
this.eventHandler(event);
};
+ /* @internal */
ProjectService.prototype.sendProjectLoadingStartEvent = function (project, reason) {
if (!this.eventHandler) {
return;
@@ -123395,6 +126186,7 @@
};
this.eventHandler(event);
};
+ /* @internal */
ProjectService.prototype.sendProjectLoadingFinishEvent = function (project) {
if (!this.eventHandler || !project.sendLoadingProjectFinish) {
return;
@@ -123406,6 +126198,7 @@
};
this.eventHandler(event);
};
+ /* @internal */
ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) {
this.delayUpdateProjectGraph(project);
this.delayEnsureProjectForOpenFiles();
@@ -123422,6 +126215,8 @@
ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions, projectRootPath) {
ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled");
var compilerOptions = convertCompilerOptions(projectCompilerOptions);
+ // always set 'allowNonTsExtensions' for inferred projects since user cannot configure it from the outside
+ // previously we did not expose a way for user to change these settings and this option was enabled by default
compilerOptions.allowNonTsExtensions = true;
var canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath);
if (canonicalProjectRootPath) {
@@ -123432,6 +126227,14 @@
}
for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
var project = _a[_i];
+ // Only update compiler options in the following cases:
+ // - Inferred projects without a projectRootPath, if the new options do not apply to
+ // a workspace root
+ // - Inferred projects with a projectRootPath, if the new options do not apply to a
+ // workspace root and there is no more specific set of options for that project's
+ // root path
+ // - Inferred projects with a projectRootPath, if the new options apply to that
+ // project root path.
if (canonicalProjectRootPath ?
project.projectRootPath === canonicalProjectRootPath :
!project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) {
@@ -123452,11 +126255,13 @@
}
return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName));
};
+ /* @internal */
ProjectService.prototype.forEachProject = function (cb) {
this.externalProjects.forEach(cb);
this.configuredProjects.forEach(cb);
this.inferredProjects.forEach(cb);
};
+ /* @internal */
ProjectService.prototype.forEachEnabledProject = function (cb) {
this.forEachProject(function (project) {
if (!project.isOrphan() && project.languageServiceEnabled) {
@@ -123467,10 +126272,12 @@
ProjectService.prototype.getDefaultProjectForFile = function (fileName, ensureProject) {
return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName);
};
+ /* @internal */
ProjectService.prototype.tryGetDefaultProjectForFile = function (fileName) {
var scriptInfo = this.getScriptInfoForNormalizedPath(fileName);
return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : undefined;
};
+ /* @internal */
ProjectService.prototype.ensureDefaultProjectForFile = function (fileName) {
return this.tryGetDefaultProjectForFile(fileName) || this.doEnsureDefaultProjectForFile(fileName);
};
@@ -123483,6 +126290,13 @@
this.ensureProjectStructuresUptoDate();
return this.getScriptInfo(uncheckedFileName);
};
+ /**
+ * Ensures the project structures are upto date
+ * This means,
+ * - we go through all the projects and update them if they are dirty
+ * - if updates reflect some change in structure or there was pending request to ensure projects for open files
+ * ensure that each open script info has project
+ */
ProjectService.prototype.ensureProjectStructuresUptoDate = function () {
var hasChanges = this.pendingEnsureProjectForOpenFiles;
this.pendingProjectUpdates.clear();
@@ -123502,7 +126316,7 @@
};
ProjectService.prototype.getPreferences = function (file) {
var info = this.getScriptInfoForNormalizedPath(file);
- return info && info.getPreferences() || this.hostConfiguration.preferences;
+ return __assign({}, this.hostConfiguration.preferences, info && info.getPreferences());
};
ProjectService.prototype.getHostFormatCodeOptions = function () {
return this.hostConfiguration.formatCodeOptions;
@@ -123520,9 +126334,12 @@
info.containingProjects.forEach(function (project) { return project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(info.path); });
}
if (eventKind === ts.FileWatcherEventKind.Deleted) {
+ // File was deleted
this.handleDeletedFile(info);
}
else if (!info.isScriptOpen()) {
+ // file has been changed which might affect the set of referenced files in projects that include
+ // this file and set of inferred projects
info.delayReloadNonMixedContentFile();
this.delayUpdateProjectGraphs(info.containingProjects);
this.handleSourceMapProjects(info);
@@ -123530,6 +126347,7 @@
}
};
ProjectService.prototype.handleSourceMapProjects = function (info) {
+ // Change in d.ts, update source projects as well
if (info.sourceMapFilePath) {
if (ts.isString(info.sourceMapFilePath)) {
var sourceMapFileInfo = this.getScriptInfoForPath(info.sourceMapFilePath);
@@ -123539,6 +126357,7 @@
this.delayUpdateSourceInfoProjects(info.sourceMapFilePath.sourceInfos);
}
}
+ // Change in mapInfo, update declarationProjects and source projects
this.delayUpdateSourceInfoProjects(info.sourceInfos);
if (info.declarationInfoPath) {
this.delayUpdateProjectsOfScriptInfoPath(info.declarationInfoPath);
@@ -123560,11 +126379,14 @@
this.stopWatchingScriptInfo(info);
if (!info.isScriptOpen()) {
this.deleteScriptInfo(info);
+ // capture list of projects since detachAllProjects will wipe out original list
var containingProjects = info.containingProjects.slice();
info.detachAllProjects();
+ // update projects to make sure that set of referenced files is correct
this.delayUpdateProjectGraphs(containingProjects);
this.handleSourceMapProjects(info);
info.closeSourceMapFileWatcher();
+ // need to recalculate source map from declaration file
if (info.declarationInfoPath) {
var declarationInfo = this.getScriptInfoForPath(info.declarationInfoPath);
if (declarationInfo) {
@@ -123573,58 +126395,85 @@
}
}
};
+ /**
+ * This is to watch whenever files are added or removed to the wildcard directories
+ */
+ /*@internal*/
ProjectService.prototype.watchWildcardDirectory = function (directory, flags, project) {
var _this = this;
return this.watchFactory.watchDirectory(this.host, directory, function (fileOrDirectory) {
var fileOrDirectoryPath = _this.toPath(fileOrDirectory);
project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
var configFilename = project.getConfigFilePath();
+ // If the the added or created file or directory is not supported file name, ignore the file
+ // But when watched directory is added/removed, we need to reload the file list
if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, project.getCompilationSettings(), _this.hostConfiguration.extraFileExtensions)) {
_this.logger.info("Project: " + configFilename + " Detected file add/remove of non supported extension: " + fileOrDirectory);
return;
}
+ // Reload is pending, do the reload
if (project.pendingReload !== ts.ConfigFileProgramReloadLevel.Full) {
project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial;
_this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project);
}
- }, flags, "Wild card directory", project);
+ }, flags, "Wild card directory" /* WildcardDirectory */, project);
};
+ /** Gets the config file existence info for the configured project */
+ /*@internal*/
ProjectService.prototype.getConfigFileExistenceInfo = function (project) {
return this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath);
};
ProjectService.prototype.onConfigChangedForConfiguredProject = function (project, eventKind) {
var configFileExistenceInfo = this.getConfigFileExistenceInfo(project);
if (eventKind === ts.FileWatcherEventKind.Deleted) {
+ // Update the cached status
+ // We arent updating or removing the cached config file presence info as that will be taken care of by
+ // setConfigFilePresenceByClosedConfigFile when the project is closed (depending on tracking open files)
configFileExistenceInfo.exists = false;
this.removeProject(project);
- this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for files");
- this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, false);
+ // Reload the configured projects for the open files in the map as they are affected by this config file
+ // Since the configured project was deleted, we want to reload projects for all the open files including files
+ // that are not root of the inferred project
+ this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */);
+ this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false);
}
else {
- this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files");
+ this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files" /* ReloadingInferredRootFiles */);
project.pendingReload = ts.ConfigFileProgramReloadLevel.Full;
project.pendingReloadReason = "Change in config file detected";
this.delayUpdateProjectGraph(project);
- this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, true);
+ // As we scheduled the update on configured project graph,
+ // we would need to schedule the project reload for only the root of inferred projects
+ this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ true);
}
};
+ /**
+ * This is the callback function for the config file add/remove/change at any location
+ * that matters to open script info but doesnt have configured project open
+ * for the config file
+ */
ProjectService.prototype.onConfigFileChangeForOpenScriptInfo = function (configFileName, eventKind) {
+ // This callback is called only if we dont have config file project for this config file
var canonicalConfigPath = server.normalizedPathToPath(configFileName, this.currentDirectory, this.toCanonicalFileName);
var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigPath);
configFileExistenceInfo.exists = (eventKind !== ts.FileWatcherEventKind.Deleted);
- this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, "Reloading configured projects for files");
- this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, false);
+ this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */);
+ // Because there is no configured project open for the config file, the tracking open files map
+ // will only have open files that need the re-detection of the project and hence
+ // reload projects for all the tracking open files in the map
+ this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false);
};
ProjectService.prototype.removeProject = function (project) {
var _this = this;
this.logger.info("`remove Project::");
project.print();
project.close();
- if (ts.Debug.shouldAssert(1)) {
+ if (ts.Debug.shouldAssert(1 /* Normal */)) {
this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project), "Found script Info still attached to project", function () { return project.projectName + ": ScriptInfos still attached: " + JSON.stringify(ts.mapDefined(ts.arrayFrom(_this.filenameToScriptInfo.values()), function (info) { return info.isAttached(project) ? info : undefined; })); }); });
}
+ // Remove the project from pending project updates
this.pendingProjectUpdates.delete(project.getProjectName());
switch (project.projectKind) {
case server.ProjectKind.External:
@@ -123641,6 +126490,7 @@
break;
}
};
+ /*@internal*/
ProjectService.prototype.assignOrphanScriptInfoToInferredProject = function (info, projectRootPath) {
ts.Debug.assert(info.isOrphan());
var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) ||
@@ -123648,6 +126498,7 @@
this.getOrCreateSingleInferredWithoutProjectRoot(info.isDynamic ? this.currentDirectory : ts.getDirectoryPath(info.path));
project.addRoot(info);
if (info.containingProjects[0] !== project) {
+ // Ensure this is first project, we could be in this scenario because info could be part of orphan project
info.detachFromProject(project);
info.containingProjects.unshift(project);
}
@@ -123657,12 +126508,21 @@
if (inferredProject === project || inferredProject.isOrphan()) {
return "continue";
}
+ // Remove the inferred project if the root of it is now part of newly created inferred project
+ // e.g through references
+ // Which means if any root of inferred project is part of more than 1 project can be removed
+ // This logic is same as iterating over all open files and calling
+ // this.removeRootOfInferredProjectIfNowPartOfOtherProject(f);
+ // Since this is also called from refreshInferredProject and closeOpen file
+ // to update inferred projects of the open file, this iteration might be faster
+ // instead of scanning all open files
var roots = inferredProject.getRootScriptInfos();
ts.Debug.assert(roots.length === 1 || !!inferredProject.projectRootPath);
if (roots.length === 1 && ts.forEach(roots[0].containingProjects, function (p) { return p !== roots[0].containingProjects[0] && !p.isOrphan(); })) {
- inferredProject.removeFile(roots[0], true, true);
+ inferredProject.removeFile(roots[0], /*fileExists*/ true, /*detachFromProject*/ true);
}
};
+ // Note that we need to create a copy of the array since the list of project can change
for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
var inferredProject = _a[_i];
_loop_2(inferredProject);
@@ -123670,8 +126530,25 @@
}
return project;
};
- ProjectService.prototype.closeOpenFile = function (info) {
+ ProjectService.prototype.assignOrphanScriptInfosToInferredProject = function () {
var _this = this;
+ // collect orphaned files and assign them to inferred project just like we treat open of a file
+ this.openFiles.forEach(function (projectRootPath, path) {
+ var info = _this.getScriptInfoForPath(path);
+ // collect all orphaned script infos from open files
+ if (info.isOrphan()) {
+ _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
+ }
+ });
+ };
+ /**
+ * Remove this file from the set of open, non-configured files.
+ * @param info The file that has been closed or newly configured
+ */
+ ProjectService.prototype.closeOpenFile = function (info, skipAssignOrphanScriptInfosToInferredProject) {
+ // Closing file should trigger re-reading the file content from disk. This is
+ // because the user may chose to discard the buffer content before saving
+ // to the disk, and the server's version of the file can be out of sync.
var fileExists = this.host.fileExists(info.fileName);
info.close(fileExists);
this.stopWatchingConfigFilesForClosedScriptInfo(info);
@@ -123679,6 +126556,7 @@
if (this.openFilesWithNonRootedDiskPath.get(canonicalFileName) === info) {
this.openFilesWithNonRootedDiskPath.delete(canonicalFileName);
}
+ // collect all projects that should be removed
var ensureProjectsForOpenFiles = false;
for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) {
var p = _a[_i];
@@ -123686,50 +126564,69 @@
if (info.hasMixedContent) {
info.registerFileUpdate();
}
+ // Do not remove the project so that we can reuse this project
+ // if it would need to be re-created with next file open
}
else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) {
+ // If this was the last open root file of inferred project
if (p.isProjectWithSingleRoot()) {
ensureProjectsForOpenFiles = true;
}
- p.removeFile(info, fileExists, true);
+ p.removeFile(info, fileExists, /*detachFromProject*/ true);
+ // Do not remove the project even if this was last root of the inferred project
+ // so that we can reuse this project, if it would need to be re-created with next file open
}
if (!p.languageServiceEnabled) {
+ // if project language service is disabled then we create a program only for open files.
+ // this means that project should be marked as dirty to force rebuilding of the program
+ // on the next request
p.markAsDirty();
}
}
this.openFiles.delete(info.path);
- if (ensureProjectsForOpenFiles) {
- this.openFiles.forEach(function (projectRootPath, path) {
- var info = _this.getScriptInfoForPath(path);
- if (info.isOrphan()) {
- _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
- }
- });
+ if (!skipAssignOrphanScriptInfosToInferredProject && ensureProjectsForOpenFiles) {
+ this.assignOrphanScriptInfosToInferredProject();
}
+ // Cleanup script infos that arent part of any project (eg. those could be closed script infos not referenced by any project)
+ // is postponed to next file open so that if file from same project is opened,
+ // we wont end up creating same script infos
+ // If the current info is being just closed - add the watcher file to track changes
+ // But if file was deleted, handle that part
if (fileExists) {
this.watchClosedScriptInfo(info);
}
else {
this.handleDeletedFile(info);
}
+ return ensureProjectsForOpenFiles;
};
ProjectService.prototype.deleteScriptInfo = function (info) {
this.filenameToScriptInfo.delete(info.path);
this.filenameToScriptInfoVersion.set(info.path, info.getVersion());
var realpath = info.getRealpathIfDifferent();
if (realpath) {
- this.realpathToScriptInfos.remove(realpath, info);
+ this.realpathToScriptInfos.remove(realpath, info); // TODO: GH#18217
}
};
ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) {
var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
if (configFileExistenceInfo) {
+ // By default the info would get impacted by presence of config file since its in the detection path
+ // Only adding the info as a root to inferred project will need the existence to be watched by file watcher
if (isOpenScriptInfo(info) && !configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) {
configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false);
- this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file");
+ this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */);
}
return configFileExistenceInfo.exists;
}
+ // Theoretically we should be adding watch for the directory here itself.
+ // In practice there will be very few scenarios where the config file gets added
+ // somewhere inside the another config file directory.
+ // And technically we could handle that case in configFile's directory watcher in some cases
+ // But given that its a rare scenario it seems like too much overhead. (we werent watching those directories earlier either)
+ // So what we are now watching is: configFile if the configured project corresponding to it is open
+ // Or the whole chain of config files for the roots of the inferred projects
+ // Cache the host value of file exists and add the info to map of open files impacted by this config file
var exists = this.host.fileExists(configFileName);
var openFilesImpactedByConfigFile = ts.createMap();
if (isOpenScriptInfo(info)) {
@@ -123737,27 +126634,34 @@
}
configFileExistenceInfo = { exists: exists, openFilesImpactedByConfigFile: openFilesImpactedByConfigFile };
this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo);
- this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file");
+ this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */);
return exists;
};
ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) {
var configFileExistenceInfo = this.getConfigFileExistenceInfo(project);
if (configFileExistenceInfo) {
+ // The existance might not be set if the file watcher is not invoked by the time config project is created by external project
configFileExistenceInfo.exists = true;
+ // close existing watcher
if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) {
var configFileName = project.getConfigFilePath();
configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close();
configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined;
- this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback");
+ this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */);
}
}
else {
+ // We could be in this scenario if project is the configured project tracked by external project
+ // Since that route doesnt check if the config file is present or not
this.configFileExistenceInfoCache.set(project.canonicalConfigFilePath, {
exists: true,
openFilesImpactedByConfigFile: ts.createMap()
});
}
};
+ /**
+ * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project
+ */
ProjectService.prototype.configFileExistenceImpactsRootOfInferredProject = function (configFileExistenceInfo) {
return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (isRootOfInferredProject) { return isRootOfInferredProject; });
};
@@ -123766,12 +126670,16 @@
ts.Debug.assert(!!configFileExistenceInfo);
if (configFileExistenceInfo.openFilesImpactedByConfigFile.size) {
var configFileName = closedProject.getConfigFilePath();
+ // If there are open files that are impacted by this config file existence
+ // but none of them are root of inferred project, the config file watcher will be
+ // created when any of the script infos are added as root of inferred project
if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) {
ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject);
this.createConfigFileWatcherOfConfigFileExistence(configFileName, closedProject.canonicalConfigFilePath, configFileExistenceInfo);
}
}
else {
+ // There is not a single file open thats tracking the status of this config file. Remove from cache
this.configFileExistenceInfoCache.delete(closedProject.canonicalConfigFilePath);
}
};
@@ -123788,25 +126696,36 @@
});
var watches = [];
if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) {
- watches.push("Config file for the inferred project root");
+ watches.push("Config file for the inferred project root" /* ConfigFileForInferredRoot */);
}
if (this.configuredProjects.has(canonicalConfigFilePath)) {
- watches.push("Config file");
+ watches.push("Config file" /* ConfigFile */);
}
this.logger.info("ConfigFilePresence:: Current Watches: " + watches + ":: File: " + configFileName + " Currently impacted open files: RootsOfInferredProjects: " + inferredRoots + " OtherOpenFiles: " + otherFiles + " Status: " + status);
};
+ /**
+ * Create the watcher for the configFileExistenceInfo
+ */
ProjectService.prototype.createConfigFileWatcherOfConfigFileExistence = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo) {
var _this = this;
- configFileExistenceInfo.configFileWatcherForRootOfInferredProject = this.watchFactory.watchFile(this.host, configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, ts.PollingInterval.High, "Config file for the inferred project root");
- this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback");
+ configFileExistenceInfo.configFileWatcherForRootOfInferredProject = this.watchFactory.watchFile(this.host, configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, ts.PollingInterval.High, "Config file for the inferred project root" /* ConfigFileForInferredRoot */);
+ this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */);
};
+ /**
+ * Close the config file watcher in the cached ConfigFileExistenceInfo
+ * if there arent any open files that are root of inferred project
+ */
ProjectService.prototype.closeConfigFileWatcherOfConfigFileExistenceInfo = function (configFileExistenceInfo) {
+ // Close the config file watcher if there are no more open files that are root of inferred project
if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject &&
!this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) {
configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close();
configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined;
}
};
+ /**
+ * This is called on file close, so that we stop watching the config file for this script info
+ */
ProjectService.prototype.stopWatchingConfigFilesForClosedScriptInfo = function (info) {
var _this = this;
ts.Debug.assert(!info.isScriptOpen());
@@ -123814,11 +126733,18 @@
var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
if (configFileExistenceInfo) {
var infoIsRootOfInferredProject = configFileExistenceInfo.openFilesImpactedByConfigFile.get(info.path);
+ // Delete the info from map, since this file is no more open
configFileExistenceInfo.openFilesImpactedByConfigFile.delete(info.path);
- _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File removed from open files impacted by this config file");
+ _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File removed from open files impacted by this config file" /* OpenFilesImpactedByConfigFileRemove */);
+ // If the script info was not root of inferred project,
+ // there wont be config file watch open because of this script info
if (infoIsRootOfInferredProject) {
+ // But if it is a root, it could be the last script info that is root of inferred project
+ // and hence we would need to close the config file watcher
_this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo);
}
+ // If there are no open files that are impacted by configFileExistenceInfo after closing this script info
+ // there is no configured project present, remove the cached existence info
if (!configFileExistenceInfo.openFilesImpactedByConfigFile.size &&
!_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) {
ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject);
@@ -123827,38 +126753,59 @@
}
});
};
+ /**
+ * This is called by inferred project whenever script info is added as a root
+ */
+ /* @internal */
ProjectService.prototype.startWatchingConfigFilesForInferredProjectRoot = function (info) {
var _this = this;
ts.Debug.assert(info.isScriptOpen());
this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) {
var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
if (!configFileExistenceInfo) {
+ // Create the cache
configFileExistenceInfo = {
exists: _this.host.fileExists(configFileName),
openFilesImpactedByConfigFile: ts.createMap()
};
_this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo);
}
+ // Set this file as the root of inferred project
configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, true);
- _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as Inferred root");
+ _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as Inferred root" /* RootOfInferredProjectTrue */);
+ // If there is no configured project for this config file, add the file watcher
if (!configFileExistenceInfo.configFileWatcherForRootOfInferredProject &&
!_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) {
_this.createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo);
}
});
};
+ /**
+ * This is called by inferred project whenever root script info is removed from it
+ */
+ /* @internal */
ProjectService.prototype.stopWatchingConfigFilesForInferredProjectRoot = function (info) {
var _this = this;
this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) {
var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
if (configFileExistenceInfo && configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) {
ts.Debug.assert(info.isScriptOpen());
+ // Info is not root of inferred project any more
configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false);
- _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as not inferred root");
+ _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as not inferred root" /* RootOfInferredProjectFalse */);
+ // Close the config file watcher
_this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo);
}
});
};
+ /**
+ * This function tries to search for a tsconfig.json for the given file.
+ * This is different from the method the compiler uses because
+ * the compiler can assume it will always start searching in the
+ * current directory (the directory in which tsc was invoked).
+ * The server must start searching from the directory containing
+ * the newly opened file.
+ */
ProjectService.prototype.forEachConfigFileLocation = function (info, action) {
var _this = this;
if (this.syntaxOnly) {
@@ -123868,6 +126815,7 @@
var projectRootPath = this.openFiles.get(info.path);
var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName));
var isSearchPathInProjectRoot = function () { return ts.containsPath(projectRootPath, searchPath, _this.currentDirectory, !_this.host.useCaseSensitiveFileNames); };
+ // If projectRootPath doesn't contain info.path, then do normal search for config file
var anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot();
do {
var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName);
@@ -123889,6 +126837,16 @@
} while (anySearchPathOk || isSearchPathInProjectRoot());
return undefined;
};
+ /**
+ * This function tries to search for a tsconfig.json for the given file.
+ * This is different from the method the compiler uses because
+ * the compiler can assume it will always start searching in the
+ * current directory (the directory in which tsc was invoked).
+ * The server must start searching from the directory containing
+ * the newly opened file.
+ * If script info is passed in, it is asserted to be open script info
+ * otherwise just file name
+ */
ProjectService.prototype.getConfigFileNameForFile = function (info) {
var _this = this;
if (isOpenScriptInfo(info))
@@ -123926,6 +126884,7 @@
this.logger.endGroup();
};
ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) {
+ // make sure that casing of config file name is consistent
var canonicalConfigFilePath = server.asNormalizedPath(this.toCanonicalFileName(configFileName));
return this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath);
};
@@ -123935,6 +126894,7 @@
ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) {
return findProjectByName(projectFileName, this.externalProjects);
};
+ /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */
ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) {
if (options && options.disableSizeLimit || !this.host.getFileSize) {
return;
@@ -123952,6 +126912,7 @@
totalNonTsFileSize += this.host.getFileSize(fileName);
if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) {
this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize));
+ // Keep the size as zero since it's disabled
return fileName;
}
}
@@ -123965,30 +126926,21 @@
var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host;
return fileNames.map(function (f) { return propertyReader.getFileName(f); })
.filter(function (name) { return hasTSFileExtension(name); })
- .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); })
+ .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) // TODO: GH#18217
.sort(function (a, b) { return b.size - a.size; })
.slice(0, 5);
}
};
ProjectService.prototype.createExternalProject = function (projectFileName, files, options, typeAcquisition, excludedFiles) {
var compilerOptions = convertCompilerOptions(options);
- var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave);
+ var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions,
+ /*lastFileExceededProgramSize*/ this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave);
project.excludedFiles = excludedFiles;
this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition);
this.externalProjects.push(project);
return project;
};
- ProjectService.prototype.sendSurveyReady = function (project) {
- if (this.seenSurveyProjects.has(project.projectName)) {
- return;
- }
- if (project.getCompilerOptions().checkJs !== undefined) {
- var name = "checkJs";
- this.logger.info("Survey " + name + " is ready");
- this.sendSurveyReadyEvent(name);
- this.seenSurveyProjects.set(project.projectName, true);
- }
- };
+ /*@internal*/
ProjectService.prototype.sendProjectTelemetry = function (project) {
if (this.seenProjects.has(project.projectName)) {
setProjectOptionsUsed(project);
@@ -124003,7 +126955,7 @@
setProjectOptionsUsed(project);
var data = {
projectId: this.host.createSHA256Hash(project.projectName),
- fileStats: server.countEachFileTypes(project.getScriptInfos(), true),
+ fileStats: server.countEachFileTypes(project.getScriptInfos(), /*includeSizes*/ true),
compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()),
typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()),
extends: projectOptions && projectOptions.configHasExtendsProperty,
@@ -124038,45 +126990,57 @@
};
ProjectService.prototype.createConfiguredProject = function (configFileName) {
var _this = this;
- var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames);
+ var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); // TODO: GH#18217
this.logger.info("Opened configuration file " + configFileName);
var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost);
- project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file", project);
+ // TODO: We probably should also watch the configFiles that are extended
+ project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file" /* ConfigFile */, project);
this.configuredProjects.set(project.canonicalConfigFilePath, project);
this.setConfigFileExistenceByNewConfiguredProject(project);
return project;
};
+ /* @internal */
ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName, reason) {
var project = this.createConfiguredProject(configFileName);
project.pendingReload = ts.ConfigFileProgramReloadLevel.Full;
project.pendingReloadReason = reason;
return project;
};
+ /* @internal */
ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName, reason) {
var project = this.createConfiguredProject(configFileName);
this.loadConfiguredProject(project, reason);
return project;
};
+ /* @internal */
ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName, reason) {
var project = this.createAndLoadConfiguredProject(configFileName, reason);
project.updateGraph();
return project;
};
+ /**
+ * Read the config file of the project, and update the project root file names.
+ */
+ /* @internal */
ProjectService.prototype.loadConfiguredProject = function (project, reason) {
this.sendProjectLoadingStartEvent(project, reason);
+ // Read updated contents from disk
var configFilename = ts.normalizePath(project.getConfigFilePath());
- var configFileContent = this.host.readFile(configFilename);
+ var configFileContent = this.host.readFile(configFilename); // TODO: GH#18217
var result = ts.parseJsonText(configFilename, configFileContent);
if (!result.endOfFileToken) {
- result.endOfFileToken = { kind: 1 };
+ result.endOfFileToken = { kind: 1 /* EndOfFileToken */ };
}
var configFileErrors = result.parseDiagnostics;
- var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions);
+ var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename),
+ /*existingOptions*/ {}, configFilename,
+ /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions);
if (parsedCommandLine.errors.length) {
configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors);
}
ts.Debug.assert(!!parsedCommandLine.fileNames);
var compilerOptions = parsedCommandLine.options;
+ // Update the project
if (!project.projectOptions) {
project.projectOptions = {
configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined,
@@ -124096,11 +127060,11 @@
}
else {
project.enableLanguageService();
- project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories));
+ project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); // TODO: GH#18217
}
project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides);
var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles());
- this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave);
+ this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave); // TODO: GH#18217
};
ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) {
var projectRootFilesMap = project.getRootFilesMap();
@@ -124112,11 +127076,12 @@
var isDynamic = server.isDynamicFileName(normalizedPath);
var scriptInfo = void 0;
var path = void 0;
+ // Use the project's fileExists so that it can use caching instead of reaching to disk for the query
if (!isDynamic && !project.fileExists(newRootFile)) {
path = server.normalizedPathToPath(normalizedPath, this.currentDirectory, this.toCanonicalFileName);
var existingValue = projectRootFilesMap.get(path);
if (server.isScriptInfo(existingValue)) {
- project.removeFile(existingValue, false, true);
+ project.removeFile(existingValue, /*fileExists*/ false, /*detachFromProject*/ true);
}
projectRootFilesMap.set(path, normalizedPath);
scriptInfo = normalizedPath;
@@ -124124,22 +127089,27 @@
else {
var scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions);
var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
- scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost);
+ scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost); // TODO: GH#18217
path = scriptInfo.path;
+ // If this script info is not already a root add it
if (!project.isRoot(scriptInfo)) {
project.addRoot(scriptInfo);
if (scriptInfo.isScriptOpen()) {
+ // if file is already root in some inferred project
+ // - remove the file from that project and delete the project if necessary
this.removeRootOfInferredProjectIfNowPartOfOtherProject(scriptInfo);
}
}
}
newRootScriptInfoMap.set(path, scriptInfo);
}
+ // project's root file map size is always going to be same or larger than new roots map
+ // as we have already all the new files to the project
if (projectRootFilesMap.size > newRootScriptInfoMap.size) {
projectRootFilesMap.forEach(function (value, path) {
if (!newRootScriptInfoMap.has(path)) {
if (server.isScriptInfo(value)) {
- project.removeFile(value, project.fileExists(path), true);
+ project.removeFile(value, project.fileExists(path), /*detachFromProject*/ true);
}
else {
projectRootFilesMap.delete(path);
@@ -124147,28 +127117,43 @@
}
});
}
+ // Just to ensure that even if root files dont change, the changes to the non root file are picked up,
+ // mark the project as dirty unconditionally
project.markAsDirty();
};
ProjectService.prototype.updateRootAndOptionsOfNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) {
project.setCompilerOptions(newOptions);
+ // VS only set the CompileOnSaveEnabled option in the request if the option was changed recently
+ // therefore if it is undefined, it should not be updated.
if (compileOnSave !== undefined) {
project.compileOnSaveEnabled = compileOnSave;
}
this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition);
};
+ /**
+ * Reload the file names from config file specs and update the project graph
+ */
+ /*@internal*/
ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) {
- var configFileSpecs = project.configFileSpecs;
+ var configFileSpecs = project.configFileSpecs; // TODO: GH#18217
var configFileName = project.getConfigFilePath();
var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions);
project.updateErrorOnNoInputFiles(fileNamesResult);
this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader);
return project.updateGraph();
};
+ /**
+ * Read the config file of the project again by clearing the cache and update the project graph
+ */
+ /* @internal */
ProjectService.prototype.reloadConfiguredProject = function (project, reason) {
+ // At this point, there is no reason to not have configFile in the host
var host = project.getCachedDirectoryStructureHost();
+ // Clear the cache since we are reloading the project from disk
host.clearCache();
var configFileName = project.getConfigFilePath();
this.logger.info("Reloading configured project " + configFileName);
+ // Load project from the disk
this.loadConfiguredProject(project, reason);
project.updateGraph();
this.sendConfigFileDiagEvent(project, configFileName);
@@ -124190,21 +127175,28 @@
}
if (projectRootPath) {
var canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath);
+ // if we have an explicit project root path, find (or create) the matching inferred project.
for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
var project = _a[_i];
if (project.projectRootPath === canonicalProjectRootPath) {
return project;
}
}
- return this.createInferredProject(projectRootPath, false, projectRootPath);
+ return this.createInferredProject(projectRootPath, /*isSingleInferredProject*/ false, projectRootPath);
}
+ // we don't have an explicit root path, so we should try to find an inferred project
+ // that more closely contains the file.
var bestMatch;
for (var _b = 0, _c = this.inferredProjects; _b < _c.length; _b++) {
var project = _c[_b];
+ // ignore single inferred projects (handled elsewhere)
if (!project.projectRootPath)
continue;
+ // ignore inferred projects that don't contain the root's path
if (!ts.containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames))
continue;
+ // ignore inferred projects that are higher up in the project root.
+ // TODO(rbuckton): Should we add the file as a root to these as well?
if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length)
continue;
bestMatch = project;
@@ -124215,14 +127207,24 @@
if (!this.useSingleInferredProject) {
return undefined;
}
+ // If `useInferredProjectPerProjectRoot` is not enabled, then there will only be one
+ // inferred project for all files. If `useInferredProjectPerProjectRoot` is enabled
+ // then we want to put all files that are not opened with a `projectRootPath` into
+ // the same inferred project.
+ //
+ // To avoid the cost of searching through the array and to optimize for the case where
+ // `useInferredProjectPerProjectRoot` is not enabled, we will always put the inferred
+ // project for non-rooted files at the front of the array.
if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === undefined) {
return this.inferredProjects[0];
}
- return this.createInferredProject(undefined, true);
+ // Single inferred project does not have a project root and hence no current directory
+ return this.createInferredProject(/*currentDirectory*/ undefined, /*isSingleInferredProject*/ true);
};
ProjectService.prototype.getOrCreateSingleInferredWithoutProjectRoot = function (currentDirectory) {
ts.Debug.assert(!this.useSingleInferredProject);
var expectedCurrentDirectory = this.toCanonicalFileName(this.getNormalizedAbsolutePath(currentDirectory || ""));
+ // Reuse the project with same current directory but no roots
for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
var inferredProject = _a[_i];
if (!inferredProject.projectRootPath &&
@@ -124234,7 +127236,7 @@
return this.createInferredProject(currentDirectory);
};
ProjectService.prototype.createInferredProject = function (currentDirectory, isSingleInferredProject, projectRootPath) {
- var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects;
+ var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; // TODO: GH#18217
var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory, this.currentPluginConfigOverrides);
if (isSingleInferredProject) {
this.inferredProjects.unshift(project);
@@ -124244,12 +127246,15 @@
}
return project;
};
+ /*@internal*/
ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClient = function (uncheckedFileName, currentDirectory, hostToQueryFileExistsOn) {
- return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(server.toNormalizedPath(uncheckedFileName), currentDirectory, undefined, undefined, hostToQueryFileExistsOn);
+ return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(server.toNormalizedPath(uncheckedFileName), currentDirectory, /*scriptKind*/ undefined,
+ /*hasMixedContent*/ undefined, hostToQueryFileExistsOn);
};
ProjectService.prototype.getScriptInfo = function (uncheckedFileName) {
return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
};
+ /* @internal */
ProjectService.prototype.getScriptInfoOrConfig = function (uncheckedFileName) {
var path = server.toNormalizedPath(uncheckedFileName);
var info = this.getScriptInfoForNormalizedPath(path);
@@ -124258,6 +127263,7 @@
var configProject = this.configuredProjects.get(this.toPath(uncheckedFileName));
return configProject && configProject.getCompilerOptions().configFile;
};
+ /* @internal */
ProjectService.prototype.logErrorForScriptInfoNotFound = function (fileName) {
var names = ts.arrayFrom(this.filenameToScriptInfo.entries()).map(function (_a) {
var path = _a[0], scriptInfo = _a[1];
@@ -124265,6 +127271,11 @@
});
this.logger.msg("Could not find file " + JSON.stringify(fileName) + ".\nAll files are: " + JSON.stringify(names), server.Msg.Err);
};
+ /**
+ * Returns the projects that contain script info through SymLink
+ * Note that this does not return projects in info.containingProjects
+ */
+ /*@internal*/
ProjectService.prototype.getSymlinkedProjects = function (info) {
var projects;
if (this.realpathToScriptInfos) {
@@ -124278,6 +127289,7 @@
function combineProjects(toAddInfo) {
if (toAddInfo !== info) {
var _loop_3 = function (project) {
+ // Add the projects only if they can use symLink targets and not already in the list
if (project.languageServiceEnabled &&
!project.isOrphan() &&
!project.getCompilerOptions().preserveSymlinks &&
@@ -124301,12 +127313,14 @@
ProjectService.prototype.watchClosedScriptInfo = function (info) {
var _this = this;
ts.Debug.assert(!info.fileWatcher);
+ // do not watch files with mixed content - server doesn't know how to interpret it
+ // do not watch files in the global cache location
if (!info.isDynamicOrHasMixedContent() &&
(!this.globalCacheLocationDirectoryPath ||
!ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) {
var indexOfNodeModules = info.path.indexOf("/node_modules/");
if (!this.host.getModifiedTime || indexOfNodeModules === -1) {
- info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info");
+ info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */);
}
else {
info.mTime = this.getModifiedTime(info);
@@ -124316,6 +127330,7 @@
};
ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) {
var _this = this;
+ // Watch only directory
var existing = this.scriptInfoInNodeModulesWatchers.get(dir);
if (existing) {
existing.refCount++;
@@ -124324,8 +127339,9 @@
var watchDir = dir + "/node_modules";
var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) {
var fileOrDirectoryPath = _this.toPath(fileOrDirectory);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
+ // Has extension
ts.Debug.assert(result.refCount > 0);
if (watchDir === fileOrDirectoryPath) {
_this.refreshScriptInfosInDirectory(watchDir);
@@ -124337,11 +127353,12 @@
_this.refreshScriptInfo(info);
}
}
+ // Folder
else if (!ts.hasExtension(fileOrDirectoryPath)) {
_this.refreshScriptInfosInDirectory(fileOrDirectoryPath);
}
}
- }, 1, "node_modules for closed script infos in them");
+ }, 1 /* Recursive */, "node_modules for closed script infos in them" /* NodeModulesForClosedScriptInfo */);
var result = {
close: function () {
if (result.refCount === 1) {
@@ -124385,16 +127402,20 @@
};
ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath = function (fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) {
if (ts.isRootedDiskPath(fileName) || server.isDynamicFileName(fileName)) {
- return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, false, undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn);
+ return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn);
}
+ // This is non rooted path with different current directory than project service current directory
+ // Only paths recognized are open relative file paths
var info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName));
if (info) {
return info;
}
+ // This means triple slash references wont be resolved in dynamic and unsaved files
+ // which is intentional since we dont know what it means to be relative to non disk files
return undefined;
};
ProjectService.prototype.getOrCreateScriptInfoOpenedByClientForNormalizedPath = function (fileName, currentDirectory, fileContent, scriptKind, hasMixedContent) {
- return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, true, fileContent, scriptKind, hasMixedContent);
+ return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ true, fileContent, scriptKind, hasMixedContent);
};
ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) {
return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn);
@@ -124409,20 +127430,24 @@
ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info or in context of host currentDirectory"; });
ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; });
ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always have current directory context since containing external project name will always match the script info name."; });
+ // If the file is not opened by client and the file doesnot exist on the disk, return
if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) {
return;
}
- info = new server.ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path, this.filenameToScriptInfoVersion.get(path));
+ info = new server.ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path, this.filenameToScriptInfoVersion.get(path)); // TODO: GH#18217
this.filenameToScriptInfo.set(info.path, info);
this.filenameToScriptInfoVersion.delete(info.path);
if (!openedByClient) {
this.watchClosedScriptInfo(info);
}
else if (!ts.isRootedDiskPath(fileName) && !isDynamic) {
+ // File that is opened by user but isn't rooted disk path
this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info);
}
}
if (openedByClient && !info.isScriptOpen()) {
+ // Opening closed script info
+ // either it was created just now, or was part of projects but was closed
this.stopWatchingScriptInfo(info);
info.open(fileContent);
if (hasMixedContent) {
@@ -124434,6 +127459,9 @@
}
return info;
};
+ /**
+ * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred
+ */
ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) {
return !ts.isRootedDiskPath(fileName) && this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)) ||
this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName));
@@ -124441,13 +127469,17 @@
ProjectService.prototype.getScriptInfoForPath = function (fileName) {
return this.filenameToScriptInfo.get(fileName);
};
+ /*@internal*/
ProjectService.prototype.getDocumentPositionMapper = function (project, generatedFileName, sourceFileName) {
var _this = this;
+ // Since declaration info and map file watches arent updating project's directory structure host (which can cache file structure) use host
var declarationInfo = this.getOrCreateScriptInfoNotOpenedByClient(generatedFileName, project.currentDirectory, this.host);
if (!declarationInfo)
return undefined;
- declarationInfo.getSnapshot();
+ // Try to get from cache
+ declarationInfo.getSnapshot(); // Ensure synchronized
if (ts.isString(declarationInfo.sourceMapFilePath)) {
+ // Ensure mapper is synchronized
var sourceMapFileInfo_1 = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath);
if (sourceMapFileInfo_1) {
sourceMapFileInfo_1.getSnapshot();
@@ -124463,8 +127495,10 @@
return undefined;
}
else if (declarationInfo.sourceMapFilePath !== undefined) {
+ // Doesnt have sourceMap
return undefined;
}
+ // Create the mapper
var sourceMapFileInfo;
var mapFileNameFromDeclarationInfo;
var readMapFile = function (mapFileName, mapFileNameFromDts) {
@@ -124481,7 +127515,7 @@
};
var projectName = project.projectName;
var documentPositionMapper = ts.getDocumentPositionMapper({ getCanonicalFileName: this.toCanonicalFileName, log: function (s) { return _this.logger.info(s); }, getSourceFileLike: function (f) { return _this.getSourceFileLike(f, projectName, declarationInfo); } }, declarationInfo.fileName, declarationInfo.getLineInfo(), readMapFile);
- readMapFile = undefined;
+ readMapFile = undefined; // Remove ref to project
if (sourceMapFileInfo) {
declarationInfo.sourceMapFilePath = sourceMapFileInfo.path;
sourceMapFileInfo.declarationInfoPath = declarationInfo.path;
@@ -124503,6 +127537,7 @@
};
ProjectService.prototype.addSourceInfoToSourceMap = function (sourceFileName, project, sourceInfos) {
if (sourceFileName) {
+ // Attach as source
var sourceInfo = this.getOrCreateScriptInfoNotOpenedByClient(sourceFileName, project.currentDirectory, project.directoryStructureHost);
(sourceInfos || (sourceInfos = ts.createMap())).set(sourceInfo.path, true);
}
@@ -124513,13 +127548,15 @@
var fileWatcher = this.watchFactory.watchFile(this.host, mapFileName, function () {
var declarationInfo = _this.getScriptInfoForPath(declarationInfoPath);
if (declarationInfo && declarationInfo.sourceMapFilePath && !ts.isString(declarationInfo.sourceMapFilePath)) {
+ // Update declaration and source projects
_this.delayUpdateProjectGraphs(declarationInfo.containingProjects);
_this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos);
declarationInfo.closeSourceMapFileWatcher();
}
- }, ts.PollingInterval.High, "Missing source map file");
+ }, ts.PollingInterval.High, "Missing source map file" /* MissingSourceMapFile */);
return fileWatcher;
};
+ /*@internal*/
ProjectService.prototype.getSourceFileLike = function (fileName, projectNameOrProject, declarationInfo) {
var project = projectNameOrProject.projectName ? projectNameOrProject : this.findProject(projectNameOrProject);
if (project) {
@@ -124528,17 +127565,21 @@
if (sourceFile && sourceFile.resolvedPath === path)
return sourceFile;
}
+ // Need to look for other files.
var info = this.getOrCreateScriptInfoNotOpenedByClient(fileName, (project || this).currentDirectory, project ? project.directoryStructureHost : this.host);
if (!info)
return undefined;
+ // Attach as source
if (declarationInfo && ts.isString(declarationInfo.sourceMapFilePath) && info !== declarationInfo) {
var sourceMapInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath);
if (sourceMapInfo) {
(sourceMapInfo.sourceInfos || (sourceMapInfo.sourceInfos = ts.createMap())).set(info.path, true);
}
}
+ // Key doesnt matter since its only for text and lines
if (info.cacheSourceFile)
return info.cacheSourceFile.sourceFile;
+ // Create sourceFileLike
if (!info.sourceFileLike) {
info.sourceFileLike = {
get text() {
@@ -124576,6 +127617,7 @@
var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject;
this.hostConfiguration.preferences = __assign({}, this.hostConfiguration.preferences, args.preferences);
if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) {
+ // Load configured projects for external projects that are pending reload
this.configuredProjects.forEach(function (project) {
if (project.hasExternalProjectRef() &&
project.pendingReload === ts.ConfigFileProgramReloadLevel.Full &&
@@ -124587,6 +127629,8 @@
}
if (args.extraFileExtensions) {
this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
+ // We need to update the project structures again as it is possible that existing
+ // project structure could have more or less files depending on extensions permitted
this.reloadProjects();
this.logger.info("Host file extension mappings updated");
}
@@ -124595,26 +127639,51 @@
ProjectService.prototype.closeLog = function () {
this.logger.close();
};
+ /**
+ * This function rebuilds the project for every file opened by the client
+ * This does not reload contents of open files from disk. But we could do that if needed
+ */
ProjectService.prototype.reloadProjects = function () {
this.logger.info("reload projects.");
- this.reloadConfiguredProjectForFiles(this.openFiles, false, ts.returnTrue, "User requested reload projects");
+ // If we want this to also reload open files from disk, we could do that,
+ // but then we need to make sure we arent calling this function
+ // (and would separate out below reloading of projects to be called when immediate reload is needed)
+ // as there is no need to load contents of the files from the disk
+ // Reload Projects
+ this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, ts.returnTrue, "User requested reload projects");
this.ensureProjectForOpenFiles();
};
ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) {
- this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, true, ignoreIfNotRootOfInferredProject ?
- function (isRootOfInferredProject) { return isRootOfInferredProject; } :
- ts.returnTrue, "Change in config file detected");
+ // Get open files to reload projects for
+ this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile,
+ /*delayReload*/ true, ignoreIfNotRootOfInferredProject ?
+ function (isRootOfInferredProject) { return isRootOfInferredProject; } : // Reload open files if they are root of inferred project
+ ts.returnTrue, // Reload all the open files impacted by config file
+ "Change in config file detected");
this.delayEnsureProjectForOpenFiles();
};
+ /**
+ * This function goes through all the openFiles and tries to file the config file for them.
+ * If the config file is found and it refers to existing project, it reloads it either immediately
+ * or schedules it for reload depending on delayReload option
+ * If the there is no existing project it just opens the configured project for the config file
+ * reloadForInfo provides a way to filter out files to reload configured project for
+ */
ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor, reason) {
var _this = this;
var updatedProjects = ts.createMap();
+ // try to reload config file for all open files
openFiles.forEach(function (openFileValue, path) {
+ // Filter out the files that need to be ignored
if (!shouldReloadProjectFor(openFileValue)) {
return;
}
- var info = _this.getScriptInfoForPath(path);
+ var info = _this.getScriptInfoForPath(path); // TODO: GH#18217
ts.Debug.assert(info.isScriptOpen());
+ // This tries to search for a tsconfig.json for the given file. If we found it,
+ // we first detect if there is already a configured project created for it: if so,
+ // we re- read the tsconfig file content and update the project only if we havent already done so
+ // otherwise we create a new one.
var configFileName = _this.getConfigFileNameForFile(info);
if (configFileName) {
var project = _this.findConfiguredProjectByProjectName(configFileName) || _this.createConfiguredProject(configFileName);
@@ -124625,6 +127694,7 @@
_this.delayUpdateProjectGraph(project);
}
else {
+ // reload from the disk
_this.reloadConfiguredProject(project, reason);
}
updatedProjects.set(configFileName, true);
@@ -124632,26 +127702,51 @@
}
});
};
+ /**
+ * Remove the root of inferred project if script info is part of another project
+ */
ProjectService.prototype.removeRootOfInferredProjectIfNowPartOfOtherProject = function (info) {
+ // If the script info is root of inferred project, it could only be first containing project
+ // since info is added as root to the inferred project only when there are no other projects containing it
+ // So when it is root of the inferred project and after project structure updates its now part
+ // of multiple project it needs to be removed from that inferred project because:
+ // - references in inferred project supercede the root part
+ // - root / reference in non - inferred project beats root in inferred project
+ // eg. say this is structure /a/b/a.ts /a/b/c.ts where c.ts references a.ts
+ // When a.ts is opened, since there is no configured project/external project a.ts can be part of
+ // a.ts is added as root to inferred project.
+ // Now at time of opening c.ts, c.ts is also not aprt of any existing project,
+ // so it will be added to inferred project as a root. (for sake of this example assume single inferred project is false)
+ // So at this poing a.ts is part of first inferred project and second inferred project (of which c.ts is root)
+ // And hence it needs to be removed from the first inferred project.
ts.Debug.assert(info.containingProjects.length > 0);
var firstProject = info.containingProjects[0];
if (!firstProject.isOrphan() &&
firstProject.projectKind === server.ProjectKind.Inferred &&
firstProject.isRoot(info) &&
ts.forEach(info.containingProjects, function (p) { return p !== firstProject && !p.isOrphan(); })) {
- firstProject.removeFile(info, true, true);
+ firstProject.removeFile(info, /*fileExists*/ true, /*detachFromProject*/ true);
}
};
+ /**
+ * This function is to update the project structure for every inferred project.
+ * It is called on the premise that all the configured projects are
+ * up to date.
+ * This will go through open files and assign them to inferred project if open file is not part of any other project
+ * After that all the inferred project graphs are updated
+ */
ProjectService.prototype.ensureProjectForOpenFiles = function () {
var _this = this;
this.logger.info("Structure before ensureProjectForOpenFiles:");
this.printProjects();
this.openFiles.forEach(function (projectRootPath, path) {
var info = _this.getScriptInfoForPath(path);
+ // collect all orphaned script infos from open files
if (info.isOrphan()) {
_this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
}
else {
+ // Or remove the root of inferred project if is referenced in more than one projects
_this.removeRootOfInferredProjectIfNowPartOfOtherProject(info);
}
});
@@ -124660,9 +127755,15 @@
this.logger.info("Structure after ensureProjectForOpenFiles:");
this.printProjects();
};
+ /**
+ * Open file whose contents is managed by the client
+ * @param filename is absolute pathname
+ * @param fileContent is a known version of the file content that is more up to date than the one on disk
+ */
ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) {
- return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined);
+ return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined);
};
+ /*@internal*/
ProjectService.prototype.getOriginalLocationEnsuringConfiguredProject = function (project, location) {
var originalLocation = project.getSourceMapper().tryGetSourcePosition(location);
if (!originalLocation)
@@ -124677,10 +127778,12 @@
var configuredProject = this.findConfiguredProjectByProjectName(configFileName) ||
this.createAndLoadConfiguredProject(configFileName, "Creating project for original file: " + originalFileInfo.fileName + " for location: " + location.fileName);
updateProjectIfDirty(configuredProject);
+ // Keep this configured project as referenced from project
addOriginalConfiguredProject(configuredProject);
var originalScriptInfo = this.getScriptInfo(fileName);
if (!originalScriptInfo || !originalScriptInfo.containingProjects.length)
return undefined;
+ // Add configured projects as referenced
originalScriptInfo.containingProjects.forEach(function (project) {
if (project.projectKind === server.ProjectKind.Configured) {
addOriginalConfiguredProject(project);
@@ -124694,68 +127797,104 @@
project.originalConfiguredProjects.set(originalProject.canonicalConfigFilePath, true);
}
};
+ /** @internal */
ProjectService.prototype.fileExists = function (fileName) {
return !!this.getScriptInfoForNormalizedPath(fileName) || this.host.fileExists(fileName);
};
ProjectService.prototype.findExternalProjectContainingOpenScriptInfo = function (info) {
return ts.find(this.externalProjects, function (proj) {
+ // Ensure project structure is up-to-date to check if info is present in external project
updateProjectIfDirty(proj);
return proj.containsScriptInfo(info);
});
};
- ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
+ ProjectService.prototype.getOrCreateOpenScriptInfo = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
+ var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); // TODO: GH#18217
+ this.openFiles.set(info.path, projectRootPath);
+ return info;
+ };
+ ProjectService.prototype.assignProjectToOpenedScriptInfo = function (info) {
var configFileName;
var configFileErrors;
- var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent);
- this.openFiles.set(info.path, projectRootPath);
var project = this.findExternalProjectContainingOpenScriptInfo(info);
- if (!project && !this.syntaxOnly) {
+ if (!project && !this.syntaxOnly) { // Checking syntaxOnly is an optimization
configFileName = this.getConfigFileNameForFile(info);
if (configFileName) {
project = this.findConfiguredProjectByProjectName(configFileName);
if (!project) {
- project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + fileName + " to open");
+ project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + info.fileName + " to open");
+ // Send the event only if the project got created as part of this open request and info is part of the project
if (info.isOrphan()) {
+ // Since the file isnt part of configured project, do not send config file info
configFileName = undefined;
}
else {
configFileErrors = project.getAllProjectErrors();
- this.sendConfigFileDiagEvent(project, fileName);
+ this.sendConfigFileDiagEvent(project, info.fileName);
}
}
else {
+ // Ensure project is ready to check if it contains opened script info
updateProjectIfDirty(project);
}
}
}
+ // Project we have at this point is going to be updated since its either found through
+ // - external project search, which updates the project before checking if info is present in it
+ // - configured project - either created or updated to ensure we know correct status of info
+ // At this point we need to ensure that containing projects of the info are uptodate
+ // This will ensure that later question of info.isOrphan() will return correct answer
+ // and we correctly create inferred project for the info
info.containingProjects.forEach(updateProjectIfDirty);
+ // At this point if file is part of any any configured or external project, then it would be present in the containing projects
+ // So if it still doesnt have any containing projects, it needs to be part of inferred project
if (info.isOrphan()) {
- this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
+ ts.Debug.assert(this.openFiles.has(info.path));
+ this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path));
}
ts.Debug.assert(!info.isOrphan());
+ return { configFileName: configFileName, configFileErrors: configFileErrors };
+ };
+ ProjectService.prototype.cleanupAfterOpeningFile = function () {
+ // This was postponed from closeOpenFile to after opening next file,
+ // so that we can reuse the project if we need to right away
this.removeOrphanConfiguredProjects();
+ // Remove orphan inferred projects now that we have reused projects
+ // We need to create a duplicate because we cant guarantee order after removal
for (var _i = 0, _a = this.inferredProjects.slice(); _i < _a.length; _i++) {
var inferredProject = _a[_i];
if (inferredProject.isOrphan()) {
this.removeProject(inferredProject);
}
}
+ // Delete the orphan files here because there might be orphan script infos (which are not part of project)
+ // when some file/s were closed which resulted in project removal.
+ // It was then postponed to cleanup these script infos so that they can be reused if
+ // the file from that old project is reopened because of opening file from here.
this.removeOrphanScriptInfos();
this.printProjects();
+ };
+ ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
+ var info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath);
+ var result = this.assignProjectToOpenedScriptInfo(info);
+ this.cleanupAfterOpeningFile();
this.telemetryOnOpenFile(info);
- return { configFileName: configFileName, configFileErrors: configFileErrors };
+ return result;
};
ProjectService.prototype.removeOrphanConfiguredProjects = function () {
var _this = this;
var toRemoveConfiguredProjects = ts.cloneMap(this.configuredProjects);
+ // Do not remove configured projects that are used as original projects of other
this.inferredProjects.forEach(markOriginalProjectsAsUsed);
this.externalProjects.forEach(markOriginalProjectsAsUsed);
this.configuredProjects.forEach(function (project) {
+ // If project has open ref (there are more than zero references from external project/open file), keep it alive as well as any project it references
if (project.hasOpenRef()) {
toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath);
markOriginalProjectsAsUsed(project);
}
else {
+ // If the configured project for project reference has more than zero references, keep it alive
project.forEachResolvedProjectReference(function (ref) {
if (ref) {
var refProject = _this.configuredProjects.get(ref.sourceFile.path);
@@ -124766,6 +127905,7 @@
});
}
});
+ // Remove all the non marked projects
toRemoveConfiguredProjects.forEach(function (project) { return _this.removeProject(project); });
function markOriginalProjectsAsUsed(project) {
if (!project.isOrphan() && project.originalConfiguredProjects) {
@@ -124777,7 +127917,9 @@
var _this = this;
var toRemoveScriptInfos = ts.cloneMap(this.filenameToScriptInfo);
this.filenameToScriptInfo.forEach(function (info) {
+ // If script info is open or orphan, retain it and its dependencies
if (!info.isScriptOpen() && info.isOrphan()) {
+ // Otherwise if there is any source info that is alive, this alive too
if (!info.sourceMapFilePath)
return;
var sourceInfos = void 0;
@@ -124797,10 +127939,12 @@
return;
}
}
+ // Retain this script info
toRemoveScriptInfos.delete(info.path);
if (info.sourceMapFilePath) {
var sourceInfos = void 0;
if (ts.isString(info.sourceMapFilePath)) {
+ // And map file info and source infos
toRemoveScriptInfos.delete(info.sourceMapFilePath);
var sourceMapInfo = _this.getScriptInfoForPath(info.sourceMapFilePath);
sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos;
@@ -124814,6 +127958,7 @@
}
});
toRemoveScriptInfos.forEach(function (info) {
+ // if there are not projects that include this script info - delete it
_this.stopWatchingScriptInfo(info);
_this.deleteScriptInfo(info);
info.closeSourceMapFileWatcher();
@@ -124830,12 +127975,13 @@
var info = { checkJs: !!project.getSourceFile(scriptInfo.path).checkJsDirective };
this.eventHandler({ eventName: server.OpenFileInfoTelemetryEvent, data: { info: info } });
};
- ProjectService.prototype.closeClientFile = function (uncheckedFileName) {
+ ProjectService.prototype.closeClientFile = function (uncheckedFileName, skipAssignOrphanScriptInfosToInferredProject) {
var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
- if (info) {
- this.closeOpenFile(info);
- }
+ var result = info ? this.closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) : false;
+ if (!skipAssignOrphanScriptInfosToInferredProject) {
this.printProjects();
+ }
+ return result;
};
ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) {
var _loop_4 = function (proj) {
@@ -124847,6 +127993,7 @@
_loop_4(proj);
}
};
+ /* @internal */
ProjectService.prototype.synchronizeProjectList = function (knownProjects) {
var files = [];
this.collectChanges(knownProjects, this.externalProjects, files);
@@ -124854,34 +128001,61 @@
this.collectChanges(knownProjects, this.inferredProjects, files);
return files;
};
+ /* @internal */
ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) {
+ var _this = this;
+ var openScriptInfos;
+ var assignOrphanScriptInfosToInferredProject = false;
if (openFiles) {
- for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) {
- var file = openFiles_1[_i];
+ while (true) {
+ var _a = openFiles.next(), file = _a.value, done = _a.done;
+ if (done)
+ break;
var scriptInfo = this.getScriptInfo(file.fileName);
ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen(), "Script should not exist and not be open already");
- var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName);
- this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent);
+ // Create script infos so we have the new content for all the open files before we do any updates to projects
+ var info = this.getOrCreateOpenScriptInfo(scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName), file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent, file.projectRootPath ? server.toNormalizedPath(file.projectRootPath) : undefined);
+ (openScriptInfos || (openScriptInfos = [])).push(info);
}
}
if (changedFiles) {
- for (var _a = 0, changedFiles_2 = changedFiles; _a < changedFiles_2.length; _a++) {
- var file = changedFiles_2[_a];
+ while (true) {
+ var _b = changedFiles.next(), file = _b.value, done = _b.done;
+ if (done)
+ break;
var scriptInfo = this.getScriptInfo(file.fileName);
ts.Debug.assert(!!scriptInfo);
+ // Make edits to script infos and marks containing project as dirty
this.applyChangesToFile(scriptInfo, file.changes);
}
}
if (closedFiles) {
- for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) {
- var file = closedFiles_1[_b];
- this.closeClientFile(file);
- }
- }
+ for (var _i = 0, closedFiles_1 = closedFiles; _i < closedFiles_1.length; _i++) {
+ var file = closedFiles_1[_i];
+ // Close files, but dont assign projects to orphan open script infos, that part comes later
+ assignOrphanScriptInfosToInferredProject = this.closeClientFile(file, /*skipAssignOrphanScriptInfosToInferredProject*/ true) || assignOrphanScriptInfosToInferredProject;
+ }
+ }
+ // All the script infos now exist, so ok to go update projects for open files
+ if (openScriptInfos) {
+ openScriptInfos.forEach(function (info) { return _this.assignProjectToOpenedScriptInfo(info); });
+ }
+ // While closing files there could be open files that needed assigning new inferred projects, do it now
+ if (assignOrphanScriptInfosToInferredProject) {
+ this.assignOrphanScriptInfosToInferredProject();
+ }
+ // Cleanup projects
+ this.cleanupAfterOpeningFile();
+ // Telemetry
+ ts.forEach(openScriptInfos, function (info) { return _this.telemetryOnOpenFile(info); });
+ this.printProjects();
};
+ /* @internal */
ProjectService.prototype.applyChangesToFile = function (scriptInfo, changes) {
- for (var i = changes.length - 1; i >= 0; i--) {
- var change = changes[i];
+ while (true) {
+ var _a = changes.next(), change = _a.value, done = _a.done;
+ if (done)
+ break;
scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText);
}
};
@@ -124906,6 +128080,7 @@
this.externalProjectToConfiguredProjectMap.delete(fileName);
}
else {
+ // close external project
var externalProject = this.findExternalProjectByProjectName(uncheckedFileName);
if (externalProject) {
this.removeProject(externalProject);
@@ -124914,6 +128089,7 @@
};
ProjectService.prototype.openExternalProjects = function (projects) {
var _this = this;
+ // record project list before the update
var projectsToClose = ts.arrayToMap(this.externalProjects, function (p) { return p.getProjectName(); }, function (_) { return true; });
ts.forEachKey(this.externalProjectToConfiguredProjectMap, function (externalProjectName) {
projectsToClose.set(externalProjectName, true);
@@ -124921,8 +128097,10 @@
for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) {
var externalProject = projects_3[_i];
this.openExternalProject(externalProject);
+ // delete project that is present in input list
projectsToClose.delete(externalProject.projectFileName);
}
+ // close projects that were missing in the input list
ts.forEachKey(projectsToClose, function (externalProjectName) {
_this.closeExternalProject(externalProjectName);
});
@@ -124938,6 +128116,7 @@
var rootFiles = proj.rootFiles;
var typeAcquisition = proj.typeAcquisition;
ts.Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now");
+ // If type acquisition has been explicitly disabled, do not exclude anything from the project
if (typeAcquisition.enable === false) {
return [];
}
@@ -124951,9 +128130,12 @@
var root = normalizedNames_1[_i];
if (rule.match.test(root)) {
this_2.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'");
+ // If the file matches, collect its types packages and exclude rules
if (rule.types) {
for (var _a = 0, _b = rule.types; _a < _b.length; _a++) {
var type = _b[_a];
+ // Best-effort de-duping here - doesn't need to be unduplicated but
+ // we don't want the list to become a 400-element array of just 'kendo'
if (typeAcqInclude.indexOf(type) < 0) {
typeAcqInclude.push(type);
}
@@ -124967,9 +128149,13 @@
groups[_i] = arguments[_i];
}
return exclude.map(function (groupNumberOrString) {
+ // RegExp group numbers are 1-based, but the first element in groups
+ // is actually the original string, so it all works out in the end.
if (typeof groupNumberOrString === "number") {
if (!ts.isString(groups[groupNumberOrString])) {
+ // Specification was wrong - exclude nothing!
_this.logger.info("Incorrect RegExp specification in safelist rule " + name + " - not enough groups");
+ // * can't appear in a filename; escape it because it's feeding into a RegExp
return "\\*";
}
return ProjectService.escapeFilenameForRegex(groups[groupNumberOrString]);
@@ -124987,6 +128173,7 @@
}
}
else {
+ // If not rules listed, add the default rule to exclude the matched file
var escaped = ProjectService.escapeFilenameForRegex(root);
if (excludeRules.indexOf(escaped) < 0) {
excludeRules.push(escaped);
@@ -125017,7 +128204,10 @@
if (typeName !== undefined) {
this_3.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist");
excludedFiles.push(normalizedNames[i]);
+ // *exclude* it from the project...
exclude = true;
+ // ... but *include* it in the list of types to acquire
+ // Same best-effort dedupe as above
if (typeAcqInclude.indexOf(typeName) < 0) {
typeAcqInclude.push(typeName);
}
@@ -125025,6 +128215,7 @@
}
}
if (!exclude) {
+ // Exclude any minified files that get this far
if (/^.+[\.-]min\.js$/.test(normalizedNames[i])) {
excludedFiles.push(normalizedNames[i]);
}
@@ -125042,6 +128233,8 @@
return excludedFiles;
};
ProjectService.prototype.openExternalProject = function (proj) {
+ // typingOptions has been deprecated and is only supported for backward compatibility
+ // purposes. It should be removed in future releases - use typeAcquisition instead.
if (proj.typingOptions && !proj.typeAcquisition) {
var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions);
proj.typeAcquisition = typeAcquisition;
@@ -125067,6 +128260,7 @@
rootFiles.push(file);
}
}
+ // sort config files to simplify comparison later
if (tsConfigFiles) {
tsConfigFiles.sort();
}
@@ -125083,17 +128277,24 @@
else {
externalProject.enableLanguageService();
}
+ // external project already exists and not config files were added - update the project and return;
+ // The graph update here isnt postponed since any file open operation needs all updated external projects
this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave);
externalProject.updateGraph();
return;
}
+ // some config files were added to external project (that previously were not there)
+ // close existing project and later we'll open a set of configured projects for these files
this.closeExternalProject(proj.projectFileName);
}
else if (this.externalProjectToConfiguredProjectMap.get(proj.projectFileName)) {
+ // this project used to include config files
if (!tsConfigFiles) {
+ // config files were removed from the project - close existing external project which in turn will close configured projects
this.closeExternalProject(proj.projectFileName);
}
else {
+ // project previously had some config files - compare them with new set of files and close all configured projects that correspond to unused files
var oldConfigFiles = this.externalProjectToConfiguredProjectMap.get(proj.projectFileName);
var iNew = 0;
var iOld = 0;
@@ -125108,55 +128309,68 @@
iNew++;
}
else {
+ // record existing config files so avoid extra add-refs
(exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig);
iOld++;
iNew++;
}
}
for (var i = iOld; i < oldConfigFiles.length; i++) {
+ // projects for all remaining old config files should be closed
this.closeConfiguredProjectReferencedFromExternalProject(oldConfigFiles[i]);
}
}
}
if (tsConfigFiles) {
+ // store the list of tsconfig files that belong to the external project
this.externalProjectToConfiguredProjectMap.set(proj.projectFileName, tsConfigFiles);
for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) {
var tsconfigFile = tsConfigFiles_1[_b];
var project = this.findConfiguredProjectByProjectName(tsconfigFile);
if (!project) {
+ // errors are stored in the project, do not need to update the graph
project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ?
this.createConfiguredProjectWithDelayLoad(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName) :
this.createLoadAndUpdateConfiguredProject(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName);
}
if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) {
+ // keep project alive even if no documents are opened - its lifetime is bound to the lifetime of containing external project
project.addExternalProjectReference();
}
}
}
else {
+ // no config files - remove the item from the collection
+ // Create external project and update its graph, do not delay update since
+ // any file open operation needs all updated external projects
this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName);
var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles);
project.updateGraph();
}
};
ProjectService.prototype.hasDeferredExtension = function () {
- for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) {
+ for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) { // TODO: GH#18217
var extension = _a[_i];
- if (extension.scriptKind === 7) {
+ if (extension.scriptKind === 7 /* Deferred */) {
return true;
}
}
return false;
};
ProjectService.prototype.configurePlugin = function (args) {
+ // For any projects that already have the plugin loaded, configure the plugin
this.forEachEnabledProject(function (project) { return project.onPluginConfigurationChanged(args.pluginName, args.configuration); });
+ // Also save the current configuration to pass on to any projects that are yet to be loaded.
+ // If a plugin is configured twice, only the latest configuration will be remembered.
this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || ts.createMap();
this.currentPluginConfigOverrides.set(args.pluginName, args.configuration);
};
+ /** Makes a filename safe to insert in a RegExp */
ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g;
return ProjectService;
}());
server.ProjectService = ProjectService;
+ /* @internal */
function isConfigFile(config) {
return config.kind !== undefined;
}
@@ -125186,6 +128400,18 @@
return ((1e9 * seconds) + nanoseconds) / 1000000.0;
}
function isDeclarationFileInJSOnlyNonConfiguredProject(project, file) {
+ // Checking for semantic diagnostics is an expensive process. We want to avoid it if we
+ // know for sure it is not needed.
+ // For instance, .d.ts files injected by ATA automatically do not produce any relevant
+ // errors to a JS- only project.
+ //
+ // Note that configured projects can set skipLibCheck (on by default in jsconfig.json) to
+ // disable checking for declaration files. We only need to verify for inferred projects (e.g.
+ // miscellaneous context in VS) and external projects(e.g.VS.csproj project) with only JS
+ // files.
+ //
+ // We still want to check .js files in a JS-only inferred or external project (e.g. if the
+ // file has '// @ts-check').
if ((project.projectKind === server.ProjectKind.Inferred || project.projectKind === server.ProjectKind.External) &&
project.isJsOnlyProject()) {
var scriptInfo = project.getScriptInfoForNormalizedPath(file);
@@ -125194,7 +128420,7 @@
return false;
}
function formatDiag(fileName, project, diag) {
- var scriptInfo = project.getScriptInfoForNormalizedPath(fileName);
+ var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); // TODO: GH#18217
return {
start: scriptInfo.positionToLineOffset(diag.start),
end: scriptInfo.positionToLineOffset(diag.start + diag.length),
@@ -125229,8 +128455,8 @@
return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 };
}
function formatConfigFileDiag(diag, includeFileName) {
- var start = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start)));
- var end = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length)));
+ var start = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start))); // TODO: GH#18217
+ var end = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length))); // TODO: GH#18217
var text = ts.flattenDiagnosticMessageText(diag.messageText, "\n");
var code = diag.code, source = diag.source;
var category = ts.diagnosticCategoryName(diag);
@@ -125250,7 +128476,7 @@
function allEditsBeforePos(edits, pos) {
return edits.every(function (edit) { return ts.textSpanEnd(edit.span) < pos; });
}
- server.CommandNames = server.protocol.CommandTypes;
+ server.CommandNames = server.protocol.CommandTypes; // tslint:disable-line variable-name
function formatMessage(msg, logger, byteLength, newLine) {
var verboseLogging = logger.hasLevel(server.LogLevel.verbose);
var json = JSON.stringify(msg);
@@ -125261,7 +128487,11 @@
return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine;
}
server.formatMessage = formatMessage;
- var MultistepOperation = (function () {
+ /**
+ * Represents operation that can schedule its next step to be executed later.
+ * Scheduling is done via instance of NextStep. If on current step subsequent step was not scheduled - operation is assumed to be completed.
+ */
+ var MultistepOperation = /** @class */ (function () {
function MultistepOperation(operationHost) {
this.operationHost = operationHost;
}
@@ -125308,6 +128538,7 @@
}
catch (e) {
stop = true;
+ // ignore cancellation request
if (!(e instanceof ts.OperationCanceledException)) {
this.operationHost.logError(e, "delayed processing of request " + this.requestId);
}
@@ -125333,6 +128564,7 @@
};
return MultistepOperation;
}());
+ /** @internal */
function toEvent(eventName, body) {
return {
seq: 0,
@@ -125342,6 +128574,9 @@
};
}
server.toEvent = toEvent;
+ /**
+ * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project.
+ */
function combineProjectOutput(defaultValue, getValue, projects, action) {
var outputs = ts.flatMapToMutable(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); });
if (!ts.isArray(projects) && projects.symLinkedProjects) {
@@ -125362,7 +128597,8 @@
}
function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, action, getLocation, resultsEqual) {
var outputs = [];
- combineProjectOutputWorker(projects, defaultProject, undefined, function (_a, tryAddToTodo) {
+ combineProjectOutputWorker(projects, defaultProject,
+ /*initialLocation*/ undefined, function (_a, tryAddToTodo) {
var project = _a.project;
for (var _i = 0, _b = action(project); _i < _b.length; _i++) {
var output = _b[_i];
@@ -125370,7 +128606,8 @@
outputs.push(output);
}
}
- }, undefined);
+ },
+ /*getDefinition*/ undefined);
return outputs;
}
function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments, hostPreferences) {
@@ -125405,6 +128642,7 @@
}
for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) {
var ref = _a[_i];
+ // If it's in a mapped file, that is added to the todo list by `getMappedLocation`.
if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) {
symbolToAddTo.references.push(ref);
}
@@ -125436,9 +128674,11 @@
var toDo;
var seenProjects = ts.createMap();
forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) {
+ // TLocation shoud be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid.
var location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : undefined);
toDo = callbackProjectAndLocation({ project: project, location: location }, projectService, toDo, seenProjects, cb);
});
+ // After initial references are collected, go over every other project and see if it has a reference for the symbol definition.
if (getDefinition) {
var memGetDefinition_1 = ts.memoize(getDefinition);
projectService.forEachEnabledProject(function (project) {
@@ -125462,7 +128702,7 @@
}
function callbackProjectAndLocation(projectAndLocation, projectService, toDo, seenProjects, cb) {
if (projectAndLocation.project.getCancellationToken().isCancellationRequested())
- return undefined;
+ return undefined; // Skip rest of toDo if cancelled
cb(projectAndLocation, function (project, location) {
seenProjects.set(projectAndLocation.project.projectName, true);
var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location);
@@ -125499,10 +128739,10 @@
var mapsTo = project.getSourceMapper().tryGetSourcePosition(location);
return mapsTo && projectService.fileExists(server.toNormalizedPath(mapsTo.fileName)) ? mapsTo : undefined;
}
- var Session = (function () {
+ var Session = /** @class */ (function () {
function Session(opts) {
- var _a;
var _this = this;
+ var _a;
this.changeSeq = 0;
this.handlers = ts.createMapFromTemplate((_a = {},
_a[server.CommandNames.Status] = function () {
@@ -125511,15 +128751,18 @@
},
_a[server.CommandNames.OpenExternalProject] = function (request) {
_this.projectService.openExternalProject(request.arguments);
- return _this.requiredResponse(true);
+ // TODO: GH#20447 report errors
+ return _this.requiredResponse(/*response*/ true);
},
_a[server.CommandNames.OpenExternalProjects] = function (request) {
_this.projectService.openExternalProjects(request.arguments.projects);
- return _this.requiredResponse(true);
+ // TODO: GH#20447 report errors
+ return _this.requiredResponse(/*response*/ true);
},
_a[server.CommandNames.CloseExternalProject] = function (request) {
_this.projectService.closeExternalProject(request.arguments.projectFileName);
- return _this.requiredResponse(true);
+ // TODO: GH#20447 report errors
+ return _this.requiredResponse(/*response*/ true);
},
_a[server.CommandNames.SynchronizeProjectList] = function (request) {
var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects);
@@ -125534,31 +128777,54 @@
info: p.info,
changes: p.changes,
files: p.files,
- projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined)
+ projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, /*scriptInfo*/ undefined)
};
});
return _this.requiredResponse(converted);
},
+ _a[server.CommandNames.UpdateOpen] = function (request) {
+ _this.changeSeq++;
+ _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles && ts.mapIterator(ts.arrayIterator(request.arguments.openFiles), function (file) { return ({
+ fileName: file.file,
+ content: file.fileContent,
+ scriptKind: file.scriptKindName,
+ projectRootPath: file.projectRootPath
+ }); }), request.arguments.changedFiles && ts.mapIterator(ts.arrayIterator(request.arguments.changedFiles), function (file) { return ({
+ fileName: file.fileName,
+ changes: ts.mapDefinedIterator(ts.arrayReverseIterator(file.textChanges), function (change) {
+ var scriptInfo = ts.Debug.assertDefined(_this.projectService.getScriptInfo(file.fileName));
+ var start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset);
+ var end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset);
+ return start >= 0 ? { span: { start: start, length: end - start }, newText: change.newText } : undefined;
+ })
+ }); }), request.arguments.closedFiles);
+ return _this.requiredResponse(/*response*/ true);
+ },
_a[server.CommandNames.ApplyChangedToOpenFiles] = function (request) {
_this.changeSeq++;
- _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles);
- return _this.requiredResponse(true);
+ _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles && ts.arrayIterator(request.arguments.openFiles), request.arguments.changedFiles && ts.mapIterator(ts.arrayIterator(request.arguments.changedFiles), function (file) { return ({
+ fileName: file.fileName,
+ // apply changes in reverse order
+ changes: ts.arrayReverseIterator(file.changes)
+ }); }), request.arguments.closedFiles);
+ // TODO: report errors
+ return _this.requiredResponse(/*response*/ true);
},
_a[server.CommandNames.Exit] = function () {
_this.exit();
return _this.notRequired();
},
_a[server.CommandNames.Definition] = function (request) {
- return _this.requiredResponse(_this.getDefinition(request.arguments, true));
+ return _this.requiredResponse(_this.getDefinition(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.DefinitionFull] = function (request) {
- return _this.requiredResponse(_this.getDefinition(request.arguments, false));
+ return _this.requiredResponse(_this.getDefinition(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.DefinitionAndBoundSpan] = function (request) {
- return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, true));
+ return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.DefinitionAndBoundSpanFull] = function (request) {
- return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, false));
+ return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.EmitOutput] = function (request) {
return _this.requiredResponse(_this.getEmitOutput(request.arguments));
@@ -125567,41 +128833,42 @@
return _this.requiredResponse(_this.getTypeDefinition(request.arguments));
},
_a[server.CommandNames.Implementation] = function (request) {
- return _this.requiredResponse(_this.getImplementation(request.arguments, true));
+ return _this.requiredResponse(_this.getImplementation(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.ImplementationFull] = function (request) {
- return _this.requiredResponse(_this.getImplementation(request.arguments, false));
+ return _this.requiredResponse(_this.getImplementation(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.References] = function (request) {
- return _this.requiredResponse(_this.getReferences(request.arguments, true));
+ return _this.requiredResponse(_this.getReferences(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.ReferencesFull] = function (request) {
- return _this.requiredResponse(_this.getReferences(request.arguments, false));
+ return _this.requiredResponse(_this.getReferences(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.Rename] = function (request) {
- return _this.requiredResponse(_this.getRenameLocations(request.arguments, true));
+ return _this.requiredResponse(_this.getRenameLocations(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.RenameLocationsFull] = function (request) {
- return _this.requiredResponse(_this.getRenameLocations(request.arguments, false));
+ return _this.requiredResponse(_this.getRenameLocations(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.RenameInfoFull] = function (request) {
return _this.requiredResponse(_this.getRenameInfo(request.arguments));
},
_a[server.CommandNames.Open] = function (request) {
- _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName), request.arguments.projectRootPath ? server.toNormalizedPath(request.arguments.projectRootPath) : undefined);
+ _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName), // TODO: GH#18217
+ request.arguments.projectRootPath ? server.toNormalizedPath(request.arguments.projectRootPath) : undefined);
return _this.notRequired();
},
_a[server.CommandNames.Quickinfo] = function (request) {
- return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true));
+ return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.QuickinfoFull] = function (request) {
- return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false));
+ return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.GetOutliningSpans] = function (request) {
- return _this.requiredResponse(_this.getOutliningSpans(request.arguments, true));
+ return _this.requiredResponse(_this.getOutliningSpans(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.GetOutliningSpansFull] = function (request) {
- return _this.requiredResponse(_this.getOutliningSpans(request.arguments, false));
+ return _this.requiredResponse(_this.getOutliningSpans(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.TodoComments] = function (request) {
return _this.requiredResponse(_this.getTodoComments(request.arguments));
@@ -125649,10 +128916,10 @@
return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionsFull));
},
_a[server.CommandNames.CompletionDetails] = function (request) {
- return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, true));
+ return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.CompletionDetailsFull] = function (request) {
- return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, false));
+ return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.CompileOnSaveAffectedFileList] = function (request) {
return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments));
@@ -125661,10 +128928,10 @@
return _this.requiredResponse(_this.emitFile(request.arguments));
},
_a[server.CommandNames.SignatureHelp] = function (request) {
- return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true));
+ return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.SignatureHelpFull] = function (request) {
- return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false));
+ return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.CompilerOptionsDiagnosticsFull] = function (request) {
return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments));
@@ -125674,7 +128941,7 @@
},
_a[server.CommandNames.Cleanup] = function () {
_this.cleanup();
- return _this.requiredResponse(true);
+ return _this.requiredResponse(/*response*/ true);
},
_a[server.CommandNames.SemanticDiagnosticsSync] = function (request) {
return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments));
@@ -125699,7 +128966,7 @@
},
_a[server.CommandNames.Configure] = function (request) {
_this.projectService.setHostConfiguration(request.arguments);
- _this.doOutput(undefined, server.CommandNames.Configure, request.seq, true);
+ _this.doOutput(/*info*/ undefined, server.CommandNames.Configure, request.seq, /*success*/ true);
return _this.notRequired();
},
_a[server.CommandNames.Reload] = function (request) {
@@ -125717,41 +128984,41 @@
return _this.notRequired();
},
_a[server.CommandNames.Navto] = function (request) {
- return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true));
+ return _this.requiredResponse(_this.getNavigateToItems(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.NavtoFull] = function (request) {
- return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false));
+ return _this.requiredResponse(_this.getNavigateToItems(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.Brace] = function (request) {
- return _this.requiredResponse(_this.getBraceMatching(request.arguments, true));
+ return _this.requiredResponse(_this.getBraceMatching(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.BraceFull] = function (request) {
- return _this.requiredResponse(_this.getBraceMatching(request.arguments, false));
+ return _this.requiredResponse(_this.getBraceMatching(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.NavBar] = function (request) {
- return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true));
+ return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.NavBarFull] = function (request) {
- return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false));
+ return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.NavTree] = function (request) {
- return _this.requiredResponse(_this.getNavigationTree(request.arguments, true));
+ return _this.requiredResponse(_this.getNavigationTree(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.NavTreeFull] = function (request) {
- return _this.requiredResponse(_this.getNavigationTree(request.arguments, false));
+ return _this.requiredResponse(_this.getNavigationTree(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.Occurrences] = function (request) {
return _this.requiredResponse(_this.getOccurrences(request.arguments));
},
_a[server.CommandNames.DocumentHighlights] = function (request) {
- return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true));
+ return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.DocumentHighlightsFull] = function (request) {
- return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false));
+ return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.CompilerOptionsForInferredProjects] = function (request) {
_this.setCompilerOptionsForInferredProjects(request.arguments);
- return _this.requiredResponse(true);
+ return _this.requiredResponse(/*response*/ true);
},
_a[server.CommandNames.ProjectInfo] = function (request) {
return _this.requiredResponse(_this.getProjectInfo(request.arguments));
@@ -125764,16 +129031,16 @@
return _this.requiredResponse(_this.getJsxClosingTag(request.arguments));
},
_a[server.CommandNames.GetCodeFixes] = function (request) {
- return _this.requiredResponse(_this.getCodeFixes(request.arguments, true));
+ return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.GetCodeFixesFull] = function (request) {
- return _this.requiredResponse(_this.getCodeFixes(request.arguments, false));
+ return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.GetCombinedCodeFix] = function (request) {
- return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, true));
+ return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.GetCombinedCodeFixFull] = function (request) {
- return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, false));
+ return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.ApplyCodeActionCommand] = function (request) {
return _this.requiredResponse(_this.applyCodeActionCommand(request.arguments));
@@ -125785,22 +129052,22 @@
return _this.requiredResponse(_this.getApplicableRefactors(request.arguments));
},
_a[server.CommandNames.GetEditsForRefactor] = function (request) {
- return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, true));
+ return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.GetEditsForRefactorFull] = function (request) {
- return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, false));
+ return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.OrganizeImports] = function (request) {
- return _this.requiredResponse(_this.organizeImports(request.arguments, true));
+ return _this.requiredResponse(_this.organizeImports(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.OrganizeImportsFull] = function (request) {
- return _this.requiredResponse(_this.organizeImports(request.arguments, false));
+ return _this.requiredResponse(_this.organizeImports(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.GetEditsForFileRename] = function (request) {
- return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, true));
+ return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.GetEditsForFileRenameFull] = function (request) {
- return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, false));
+ return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.ConfigurePlugin] = function (request) {
_this.configurePlugin(request.arguments);
@@ -125846,7 +129113,7 @@
syntaxOnly: opts.syntaxOnly,
};
this.projectService = new server.ProjectService(settings);
- this.gcTimer = new server.GcTimer(this.host, 7000, this.logger);
+ this.gcTimer = new server.GcTimer(this.host, /*delay*/ 7000, this.logger);
}
Session.prototype.sendRequestCompletedEvent = function (requestId) {
this.event({ request_seq: requestId }, "requestCompleted");
@@ -125871,17 +129138,13 @@
break;
case server.ConfigFileDiagEvent:
var _c = event.data, triggerFile = _c.triggerFile, configFile = _c.configFileName, diagnostics = _c.diagnostics;
- var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); });
+ var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ true); });
this.event({
triggerFile: triggerFile,
configFile: configFile,
diagnostics: bakedDiags
}, server.ConfigFileDiagEvent);
break;
- case server.SurveyReady:
- var surveyId = event.data.surveyId;
- this.event({ surveyId: surveyId }, server.SurveyReady);
- break;
case server.ProjectLanguageServiceStateEvent: {
var eventName = server.ProjectLanguageServiceStateEvent;
this.event({
@@ -125906,8 +129169,10 @@
if (openFiles.length) {
if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) {
var checkList_1 = this.createCheckList(openFiles);
- this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, true); });
+ // For now only queue error checking for open files. We can change this to include non open files as well
+ this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, /*requireOpen*/ true); });
}
+ // Send project changed event
this.event({
openFiles: openFiles
}, server.ProjectsUpdatedInBackgroundEvent);
@@ -125924,7 +129189,8 @@
msg += "\n" + server.indent(err.stack);
}
}
- if (fileRequest && this.logger.hasLevel(server.LogLevel.verbose)) {
+ if (this.logger.hasLevel(server.LogLevel.verbose)) {
+ if (fileRequest) {
try {
var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project;
var scriptInfo = project.getScriptInfoForNormalizedPath(file);
@@ -125933,7 +129199,21 @@
msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n";
}
}
- catch (_b) { }
+ catch (_b) { } // tslint:disable-line no-empty
+ }
+ if (err.message && err.message.indexOf("Could not find sourceFile:") !== -1) {
+ msg += "\n\nProjects::\n";
+ var counter_1 = 0;
+ var addProjectInfo = function (project) {
+ msg += "\nProject '" + project.projectName + "' (" + server.ProjectKind[project.projectKind] + ") " + counter_1 + "\n";
+ msg += project.filesToString(/*writeProjectFileNames*/ true);
+ msg += "\n-----------------------------------------------\n";
+ counter_1++;
+ };
+ this.projectService.externalProjects.forEach(addProjectInfo);
+ this.projectService.configuredProjects.forEach(addProjectInfo);
+ this.projectService.inferredProjects.forEach(addProjectInfo);
+ }
}
this.logger.msg(msg, server.Msg.Err);
};
@@ -125949,8 +129229,10 @@
Session.prototype.event = function (body, eventName) {
this.send(toEvent(eventName, body));
};
+ // For backwards-compatibility only.
+ /** @deprecated */
Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) {
- this.doOutput(info, cmdName, reqSeq, !errorMsg, errorMsg);
+ this.doOutput(info, cmdName, reqSeq, /*success*/ !errorMsg, errorMsg); // TODO: GH#18217
};
Session.prototype.doOutput = function (info, cmdName, reqSeq, success, message) {
var res = {
@@ -126011,10 +129293,11 @@
this.logError(err, kind);
}
};
+ /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */
Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) {
var _this = this;
if (requireOpen === void 0) { requireOpen = true; }
- ts.Debug.assert(!this.suppressDiagnosticEvents);
+ ts.Debug.assert(!this.suppressDiagnosticEvents); // Caller's responsibility
var seq = this.changeSeq;
var followMs = Math.min(ms, 200);
var index = 0;
@@ -126024,6 +129307,7 @@
}
var _a = checkList[index], fileName = _a.fileName, project = _a.project;
index++;
+ // Ensure the project is upto date before checking if this file is present in the project
server.updateProjectIfDirty(project);
if (!project.containsFile(fileName, requireOpen)) {
return;
@@ -126064,7 +129348,7 @@
this.logger.info("cleaning " + caption);
for (var _i = 0, projects_5 = projects; _i < projects_5.length; _i++) {
var p = projects_5[_i];
- p.getLanguageService(false).cleanupSemanticCache();
+ p.getLanguageService(/*ensureSynchronized*/ false).cleanupSemanticCache();
}
};
Session.prototype.cleanup = function () {
@@ -126097,7 +129381,7 @@
var diagnosticsForConfigFile = ts.filter(ts.concatenate(projectErrors, optionsErrors), function (diagnostic) { return !!diagnostic.file && diagnostic.file.fileName === configFile; });
return includeLinePosition ?
this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) :
- ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, false); });
+ ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ false); });
};
Session.prototype.convertToDiagnosticsWithLinePositionFromDiagnosticFile = function (diagnostics) {
var _this = this;
@@ -126114,7 +129398,11 @@
};
Session.prototype.getCompilerOptionsDiagnostics = function (args) {
var project = this.getProject(args.projectFileName);
- return this.convertToDiagnosticsWithLinePosition(ts.filter(project.getLanguageService().getCompilerOptionsDiagnostics(), function (diagnostic) { return !diagnostic.file; }), undefined);
+ // Get diagnostics that dont have associated file with them
+ // The diagnostics which have file would be in config file and
+ // would be reported as part of configFileDiagnostics
+ return this.convertToDiagnosticsWithLinePosition(ts.filter(project.getLanguageService().getCompilerOptionsDiagnostics(), function (diagnostic) { return !diagnostic.file; }),
+ /*scriptInfo*/ undefined);
};
Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) {
var _this = this;
@@ -126175,7 +129463,7 @@
if (!unmappedDefinitionAndBoundSpan || !unmappedDefinitionAndBoundSpan.definitions) {
return {
definitions: server.emptyArray,
- textSpan: undefined
+ textSpan: undefined // TODO: GH#18217
};
}
var definitions = this.mapDefinitionInfoLocations(unmappedDefinitionAndBoundSpan.definitions, project);
@@ -126199,6 +129487,13 @@
var _this = this;
return definitions.map(function (def) { return _this.toFileSpan(def.fileName, def.textSpan, project); });
};
+ /*
+ * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in
+ * the same project which corresponds to the file. VS Code has no problem with this, and luckily we have two protocols.
+ * This retains the existing behavior for the "simplified" (VS Code) protocol but stores the .d.ts location in a
+ * set of additional fields, and does the reverse for VS (store the .d.ts location where
+ * it used to be and stores the .ts location in the additional fields).
+ */
Session.mapToOriginalLocation = function (def) {
if (def.originalFileName) {
ts.Debug.assert(def.originalTextSpan !== undefined, "originalTextSpan should be present if originalFileName is");
@@ -126208,7 +129503,7 @@
};
Session.prototype.toFileSpan = function (fileName, textSpan, project) {
var ls = project.getLanguageService();
- var start = ls.toLineColumnOffset(fileName, textSpan.start);
+ var start = ls.toLineColumnOffset(fileName, textSpan.start); // TODO: GH#18217
var end = ls.toLineColumnOffset(fileName, ts.textSpanEnd(textSpan));
return {
file: fileName,
@@ -126268,6 +129563,7 @@
file: fileName,
isWriteAccess: isWriteAccess,
};
+ // no need to serialize the property if it is not true
if (isInString) {
result.isInString = isInString;
}
@@ -126277,23 +129573,26 @@
Session.prototype.getSyntacticDiagnosticsSync = function (args) {
var configFile = this.getConfigFileAndProject(args).configFile;
if (configFile) {
+ // all the config file errors are reported as part of semantic check so nothing to report here
return server.emptyArray;
}
- return this.getDiagnosticsWorker(args, false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, !!args.includeLinePosition);
+ return this.getDiagnosticsWorker(args, /*isSemantic*/ false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, !!args.includeLinePosition);
};
Session.prototype.getSemanticDiagnosticsSync = function (args) {
var _a = this.getConfigFileAndProject(args), configFile = _a.configFile, project = _a.project;
if (configFile) {
- return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition);
+ return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition); // TODO: GH#18217
}
- return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, !!args.includeLinePosition);
+ return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, !!args.includeLinePosition);
};
Session.prototype.getSuggestionDiagnosticsSync = function (args) {
var configFile = this.getConfigFileAndProject(args).configFile;
if (configFile) {
+ // Currently there are no info diagnostics for config files.
return server.emptyArray;
}
- return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSuggestionDiagnostics(file); }, !!args.includeLinePosition);
+ // isSemantic because we don't want to info diagnostics in declaration files for JS-only users
+ return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSuggestionDiagnostics(file); }, !!args.includeLinePosition);
};
Session.prototype.getJsxClosingTag = function (args) {
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
@@ -126333,7 +129632,7 @@
this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath);
};
Session.prototype.getProjectInfo = function (args) {
- return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, false);
+ return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, /*excludeConfigFiles*/ false);
};
Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) {
var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName).project;
@@ -126341,15 +129640,14 @@
var projectInfo = {
configFileName: project.getProjectName(),
languageServiceDisabled: !project.languageServiceEnabled,
- fileNames: needFileNameList ? project.getFileNames(false, excludeConfigFiles) : undefined
+ fileNames: needFileNameList ? project.getFileNames(/*excludeFilesFromExternalLibraries*/ false, excludeConfigFiles) : undefined
};
return projectInfo;
};
Session.prototype.getRenameInfo = function (args) {
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
var position = this.getPositionInFile(args, file);
- var preferences = this.getHostPreferences();
- return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: preferences.allowRenameOfImportPath });
+ return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath });
};
Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) {
var projects;
@@ -126373,12 +129671,13 @@
projects = scriptInfo.containingProjects;
symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo);
}
+ // filter handles case when 'projects' is undefined
projects = ts.filter(projects, function (p) { return p.languageServiceEnabled && !p.isOrphan(); });
if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) {
this.projectService.logErrorForScriptInfoNotFound(args.file);
return server.Errors.ThrowNoProject();
}
- return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects;
+ return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; // TODO: GH#18217
};
Session.prototype.getDefaultProject = function (args) {
if (args.projectFileName) {
@@ -126394,11 +129693,11 @@
var file = server.toNormalizedPath(args.file);
var position = this.getPositionInFile(args, file);
var projects = this.getProjects(args);
- var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getHostPreferences());
+ var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getPreferences(file));
if (!simplifiedResult)
return locations;
var defaultProject = this.getDefaultProject(args);
- var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getHostPreferences().allowRenameOfImportPath }), ts.Debug.assertDefined(this.projectService.getScriptInfo(file)));
+ var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }), ts.Debug.assertDefined(this.projectService.getScriptInfo(file)));
return { info: renameInfo, locs: this.toSpanGroups(locations) };
};
Session.prototype.mapRenameInfo = function (info, scriptInfo) {
@@ -126454,8 +129753,12 @@
return references;
}
};
+ /**
+ * @param fileName is the name of the file to be opened
+ * @param fileContent is a version of the file content that is known to be more up to date than the one on disk
+ */
Session.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) {
- this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, false, projectRootPath);
+ this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath);
};
Session.prototype.getPosition = function (args, scriptInfo) {
return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset);
@@ -126468,6 +129771,8 @@
return this.getFileAndProjectWorker(args.file, args.projectFileName);
};
Session.prototype.getFileAndLanguageServiceForSyntacticOperation = function (args) {
+ // Since this is syntactic operation, there should always be project for the file
+ // we wouldnt have to ensure project but rather throw if we dont get project
var file = server.toNormalizedPath(args.file);
var project = this.getProject(args.projectFileName) || this.projectService.tryGetDefaultProjectForFile(file);
if (!project) {
@@ -126475,7 +129780,7 @@
}
return {
file: file,
- languageService: project.getLanguageService(false)
+ languageService: project.getLanguageService(/*ensureSynchronized*/ false)
};
};
Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName) {
@@ -126568,6 +129873,7 @@
var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset);
var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
+ // TODO: avoid duplicate code (with formatonkey)
var edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.getFormatOptions(file));
if (!edits) {
return undefined;
@@ -126577,7 +129883,7 @@
Session.prototype.getFormattingEditsForRangeFull = function (args) {
var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file);
- return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options);
+ return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); // TODO: GH#18217
};
Session.prototype.getFormattingEditsForDocumentFull = function (args) {
var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
@@ -126587,7 +129893,7 @@
Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) {
var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file);
- return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options);
+ return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); // TODO: GH#18217
};
Session.prototype.getFormattingEditsAfterKeystroke = function (args) {
var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
@@ -126595,6 +129901,12 @@
var position = scriptInfo.lineOffsetToPosition(args.line, args.offset);
var formatOptions = this.getFormatOptions(file);
var edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions);
+ // Check whether we should auto-indent. This will be when
+ // the position is on a line containing only whitespace.
+ // This should leave the edits returned from
+ // getFormattingEditsAfterKeystroke either empty or pertaining
+ // only to the previous line. If all this is true, then
+ // add edits necessary to properly indent the current line.
if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) {
var _b = scriptInfo.getAbsolutePositionAndLineText(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition;
if (lineText && lineText.search("\\S") < 0) {
@@ -126606,12 +129918,13 @@
hasIndent++;
}
else if (lineText.charAt(i) === "\t") {
- hasIndent += formatOptions.tabSize;
+ hasIndent += formatOptions.tabSize; // TODO: GH#18217
}
else {
break;
}
}
+ // i points to the first non whitespace character
if (preferredIndent !== hasIndent) {
var firstNoWhiteSpacePosition = absolutePosition + i;
edits.push({
@@ -126640,17 +129953,18 @@
var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, server.convertUserPreferences(this.getPreferences(file)), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions }));
if (completions === undefined)
return undefined;
- if (kind === "completions-full")
+ if (kind === "completions-full" /* CompletionsFull */)
return completions;
var prefix = args.prefix || "";
var entries = ts.mapDefined(completions.entries, function (entry) {
if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) {
var name = entry.name, kind_1 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended;
var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined;
+ // Use `hasAction || undefined` to avoid serializing `false`.
return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended };
}
}).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); });
- if (kind === "completions") {
+ if (kind === "completions" /* Completions */) {
if (completions.metadata)
entries.metadata = completions.metadata;
return entries;
@@ -126674,7 +129988,7 @@
};
Session.prototype.getCompileOnSaveAffectedFileList = function (args) {
var _this = this;
- var projects = this.getProjects(args, true, true);
+ var projects = this.getProjects(args, /*getScriptInfoEnsuringProjectsUptoDate*/ true, /*ignoreNoProjectError*/ true);
var info = this.projectService.getScriptInfo(args.file);
if (!info) {
return server.emptyArray;
@@ -126752,10 +130066,10 @@
var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
if (start >= 0) {
this.changeSeq++;
- this.projectService.applyChangesToFile(scriptInfo, [{
+ this.projectService.applyChangesToFile(scriptInfo, ts.singleIterator({
span: { start: start, length: end - start },
- newText: args.insertString
- }]);
+ newText: args.insertString // TODO: GH#18217
+ }));
}
};
Session.prototype.reload = function (args, reqSeq) {
@@ -126764,8 +130078,9 @@
var info = this.projectService.getScriptInfoForNormalizedPath(file);
if (info) {
this.changeSeq++;
+ // make sure no changes happen before this one is finished
if (info.reloadFromFile(tempFileName)) {
- this.doOutput(undefined, server.CommandNames.Reload, reqSeq, true);
+ this.doOutput(/*info*/ undefined, server.CommandNames.Reload, reqSeq, /*success*/ true);
}
}
};
@@ -126863,7 +130178,7 @@
}
else {
return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(args), this.getDefaultProject(args), function (project) {
- return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, undefined, project.isNonTsProject());
+ return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ undefined, /*excludeDts*/ project.isNonTsProject());
}, documentSpanLocation, navigateToItemIsEqualTo);
}
function navigateToItemIsEqualTo(a, b) {
@@ -126975,7 +130290,7 @@
}
};
Session.prototype.applyCodeActionCommand = function (args) {
- var commands = args.command;
+ var commands = args.command; // They should be sending back the command we sent them.
for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) {
var command = _a[_i];
var _b = this.getFileAndProject(command), file = _b.file, project = _b.project;
@@ -126990,6 +130305,7 @@
}
else {
startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset);
+ // save the result so we don't always recompute
args.startPosition = startPosition;
}
if (args.endPosition !== undefined) {
@@ -127016,7 +130332,7 @@
Session.prototype.mapTextChangeToCodeEdit = function (textChanges) {
var scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges.fileName);
if (!!textChanges.isNewFile === !!scriptInfo) {
- if (!scriptInfo) {
+ if (!scriptInfo) { // and !isNewFile
this.projectService.logErrorForScriptInfoNotFound(textChanges.fileName);
}
ts.Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo }));
@@ -127048,14 +130364,16 @@
if (this.suppressDiagnosticEvents) {
return;
}
- var _a = this.getProjectInfoWorker(fileName, undefined, true, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled;
+ var _a = this.getProjectInfoWorker(fileName, /*projectFileName*/ undefined, /*needFileNameList*/ true, /*excludeConfigFiles*/ true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled;
if (languageServiceDisabled) {
return;
}
- var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); });
+ // No need to analyze lib.d.ts
+ var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); }); // TODO: GH#18217
if (fileNamesInProject.length === 0) {
return;
}
+ // Sort the file name list to make the recently touched files come first
var highPriorityFiles = [];
var mediumPriorityFiles = [];
var lowPriorityFiles = [];
@@ -127068,9 +130386,9 @@
highPriorityFiles.push(fileNameInProject);
}
else {
- var info = this.projectService.getScriptInfo(fileNameInProject);
+ var info = this.projectService.getScriptInfo(fileNameInProject); // TODO: GH#18217
if (!info.isScriptOpen()) {
- if (ts.fileExtensionIs(fileNameInProject, ".d.ts")) {
+ if (ts.fileExtensionIs(fileNameInProject, ".d.ts" /* Dts */)) {
veryLowPriorityFiles.push(fileNameInProject);
}
else {
@@ -127084,7 +130402,9 @@
}
var sortedFiles = highPriorityFiles.concat(mediumPriorityFiles, lowPriorityFiles, veryLowPriorityFiles);
var checkList = sortedFiles.map(function (fileName) { return ({ fileName: fileName, project: project }); });
- this.updateErrorCheck(next, checkList, delay, false);
+ // Project level error analysis runs on background files too, therefore
+ // doesn't require the file to be opened
+ this.updateErrorCheck(next, checkList, delay, /*requireOpen*/ false);
};
Session.prototype.configurePlugin = function (args) {
this.projectService.configurePlugin(args);
@@ -127113,7 +130433,7 @@
};
Session.prototype.resetCurrentRequest = function (requestId) {
ts.Debug.assert(this.currentRequestId === requestId);
- this.currentRequestId = undefined;
+ this.currentRequestId = undefined; // TODO: GH#18217
this.cancellationToken.resetRequest(requestId);
};
Session.prototype.executeWithRequestId = function (requestId, f) {
@@ -127132,7 +130452,7 @@
}
else {
this.logger.msg("Unrecognized JSON command:" + server.stringifyIndented(request), server.Msg.Err);
- this.doOutput(undefined, server.CommandNames.Unknown, request.seq, false, "Unrecognized JSON command: " + request.command);
+ this.doOutput(/*info*/ undefined, server.CommandNames.Unknown, request.seq, /*success*/ false, "Unrecognized JSON command: " + request.command);
return { responseRequired: false };
}
};
@@ -127161,19 +130481,22 @@
}
}
if (response) {
- this.doOutput(response, request.command, request.seq, true);
+ this.doOutput(response, request.command, request.seq, /*success*/ true);
}
else if (responseRequired) {
- this.doOutput(undefined, request.command, request.seq, false, "No content available.");
+ this.doOutput(/*info*/ undefined, request.command, request.seq, /*success*/ false, "No content available.");
}
}
catch (err) {
if (err instanceof ts.OperationCanceledException) {
- this.doOutput({ canceled: true }, request.command, request.seq, true);
+ // Handle cancellation exceptions
+ this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true);
return;
}
this.logErrorWorker(err, message, relevantFile);
- this.doOutput(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, false, "Error processing request. " + err.message + "\n" + err.stack);
+ this.doOutput(
+ /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0,
+ /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack);
}
};
Session.prototype.getFormatOptions = function (file) {
@@ -127209,6 +130532,7 @@
ts.Debug.assert(change.span.start === 0 && change.span.length === 0);
return { fileName: textChanges.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] };
}
+ /* @internal */ // Exported only for tests
function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) {
var newText = applyEdits(oldText, renameFilename, edits);
var _a = ts.computeLineAndCharacterOfPosition(ts.computeLineStarts(newText), renameLocation), line = _a.line, character = _a.character;
@@ -127230,6 +130554,7 @@
}
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
+/*@internal*/
var ts;
(function (ts) {
var server;
@@ -127244,12 +130569,12 @@
CharRangeSection[CharRangeSection["End"] = 4] = "End";
CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd";
})(CharRangeSection || (CharRangeSection = {}));
- var EditWalker = (function () {
+ var EditWalker = /** @class */ (function () {
function EditWalker() {
this.goSubtree = true;
this.lineIndex = new LineIndex();
this.endBranch = [];
- this.state = 2;
+ this.state = 2 /* Entire */;
this.initialText = "";
this.trailingText = "";
this.lineIndex.root = new LineNode();
@@ -127295,6 +130620,7 @@
if (lastZeroCount) {
branchParent.remove(lastZeroCount);
}
+ // path at least length two (root and leaf)
var leafNode = this.startPath[this.startPath.length - 1];
if (lines.length > 0) {
leafNode.text = lines[0];
@@ -127329,6 +130655,7 @@
}
else {
var insertionNode = this.startPath[this.startPath.length - 2];
+ // no content for leaf node, so delete it
insertionNode.remove(leafNode);
for (var j = this.startPath.length - 2; j >= 0; j--) {
this.startPath[j].updateCounts();
@@ -127337,15 +130664,20 @@
return this.lineIndex;
};
EditWalker.prototype.post = function (_relativeStart, _relativeLength, lineCollection) {
+ // have visited the path for start of range, now looking for end
+ // if range is on single line, we will never make this state transition
if (lineCollection === this.lineCollectionAtBranch) {
- this.state = 4;
+ this.state = 4 /* End */;
}
+ // always pop stack because post only called when child has been visited
this.stack.pop();
};
EditWalker.prototype.pre = function (_relativeStart, _relativeLength, lineCollection, _parent, nodeType) {
+ // currentNode corresponds to parent, but in the new tree
var currentNode = this.stack[this.stack.length - 1];
- if ((this.state === 2) && (nodeType === 1)) {
- this.state = 1;
+ if ((this.state === 2 /* Entire */) && (nodeType === 1 /* Start */)) {
+ // if range is on single line, we will never make this state transition
+ this.state = 1 /* Start */;
this.branchNode = currentNode;
this.lineCollectionAtBranch = lineCollection;
}
@@ -127358,14 +130690,14 @@
return new LineNode();
}
switch (nodeType) {
- case 0:
+ case 0 /* PreStart */:
this.goSubtree = false;
- if (this.state !== 4) {
+ if (this.state !== 4 /* End */) {
currentNode.add(lineCollection);
}
break;
- case 1:
- if (this.state === 4) {
+ case 1 /* Start */:
+ if (this.state === 4 /* End */) {
this.goSubtree = false;
}
else {
@@ -127374,8 +130706,8 @@
this.startPath.push(child);
}
break;
- case 2:
- if (this.state !== 4) {
+ case 2 /* Entire */:
+ if (this.state !== 4 /* End */) {
child = fresh(lineCollection);
currentNode.add(child);
this.startPath.push(child);
@@ -127388,11 +130720,11 @@
}
}
break;
- case 3:
+ case 3 /* Mid */:
this.goSubtree = false;
break;
- case 4:
- if (this.state !== 4) {
+ case 4 /* End */:
+ if (this.state !== 4 /* End */) {
this.goSubtree = false;
}
else {
@@ -127403,9 +130735,9 @@
}
}
break;
- case 5:
+ case 5 /* PostEnd */:
this.goSubtree = false;
- if (this.state !== 1) {
+ if (this.state !== 1 /* Start */) {
currentNode.add(lineCollection);
}
break;
@@ -127414,21 +130746,24 @@
this.stack.push(child);
}
};
+ // just gather text from the leaves
EditWalker.prototype.leaf = function (relativeStart, relativeLength, ll) {
- if (this.state === 1) {
+ if (this.state === 1 /* Start */) {
this.initialText = ll.text.substring(0, relativeStart);
}
- else if (this.state === 2) {
+ else if (this.state === 2 /* Entire */) {
this.initialText = ll.text.substring(0, relativeStart);
this.trailingText = ll.text.substring(relativeStart + relativeLength);
}
else {
+ // state is CharRangeSection.End
this.trailingText = ll.text.substring(relativeStart + relativeLength);
}
};
return EditWalker;
}());
- var TextChange = (function () {
+ // text change information
+ var TextChange = /** @class */ (function () {
function TextChange(pos, deleteLen, insertedText) {
this.pos = pos;
this.deleteLen = deleteLen;
@@ -127439,11 +130774,11 @@
};
return TextChange;
}());
- var ScriptVersionCache = (function () {
+ var ScriptVersionCache = /** @class */ (function () {
function ScriptVersionCache() {
this.changes = [];
this.versions = new Array(ScriptVersionCache.maxVersions);
- this.minVersion = 0;
+ this.minVersion = 0; // no versions earlier than min version will maintain change history
this.currentVersion = 0;
}
ScriptVersionCache.prototype.versionToIndex = function (version) {
@@ -127455,6 +130790,7 @@
ScriptVersionCache.prototype.currentVersionToIndex = function () {
return this.currentVersion % ScriptVersionCache.maxVersions;
};
+ // REVIEW: can optimize by coalescing simple edits
ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) {
this.changes.push(new TextChange(pos, deleteLen, insertedText));
if (this.changes.length > ScriptVersionCache.changeNumberThreshold ||
@@ -127505,7 +130841,7 @@
if (oldVersion >= this.minVersion) {
var textChangeRanges = [];
for (var i = oldVersion + 1; i <= newVersion; i++) {
- var snap = this.versions[this.versionToIndex(i)];
+ var snap = this.versions[this.versionToIndex(i)]; // TODO: GH#18217
for (var _i = 0, _a = snap.changesSincePreviousVersion; _i < _a.length; _i++) {
var textChange = _a[_i];
textChangeRanges.push(textChange.getTextChangeRange());
@@ -127538,7 +130874,7 @@
return ScriptVersionCache;
}());
server.ScriptVersionCache = ScriptVersionCache;
- var LineIndexSnapshot = (function () {
+ var LineIndexSnapshot = /** @class */ (function () {
function LineIndexSnapshot(version, cache, index, changesSincePreviousVersion) {
if (changesSincePreviousVersion === void 0) { changesSincePreviousVersion = server.emptyArray; }
this.version = version;
@@ -127564,8 +130900,9 @@
};
return LineIndexSnapshot;
}());
- var LineIndex = (function () {
+ var LineIndex = /** @class */ (function () {
function LineIndex() {
+ // set this to true to check each edit for accuracy
this.checkEdits = false;
}
LineIndex.prototype.absolutePositionOfStartOfLine = function (oneBasedLine) {
@@ -127640,12 +130977,12 @@
};
LineIndex.prototype.edit = function (pos, deleteLength, newText) {
if (this.root.charCount() === 0) {
- ts.Debug.assert(deleteLength === 0);
+ ts.Debug.assert(deleteLength === 0); // Can't delete from empty document
if (newText !== undefined) {
this.load(LineIndex.linesFromText(newText).lines);
return this;
}
- return undefined;
+ return undefined; // TODO: GH#18217
}
else {
var checkText = void 0;
@@ -127656,6 +130993,7 @@
var walker = new EditWalker();
var suppressTrailingText = false;
if (pos >= this.root.charCount()) {
+ // insert at end
pos = this.root.charCount() - 1;
var endString = this.getText(pos, 1);
if (newText) {
@@ -127668,10 +131006,13 @@
suppressTrailingText = true;
}
else if (deleteLength > 0) {
+ // check whether last characters deleted are line break
var e = pos + deleteLength;
var _a = this.positionToColumnAndLineText(e), zeroBasedColumn = _a.zeroBasedColumn, lineText = _a.lineText;
if (zeroBasedColumn === 0) {
- deleteLength += lineText.length;
+ // move range end just past line that will merge with previous line
+ deleteLength += lineText.length; // TODO: GH#18217
+ // store text by appending to end of insertedText
newText = newText ? newText + lineText : lineText;
}
}
@@ -127719,7 +131060,7 @@
return LineIndex;
}());
server.LineIndex = LineIndex;
- var LineNode = (function () {
+ var LineNode = /** @class */ (function () {
function LineNode(children) {
if (children === void 0) { children = []; }
this.children = children;
@@ -127762,22 +131103,26 @@
}
};
LineNode.prototype.walk = function (rangeStart, rangeLength, walkFns) {
+ // assume (rangeStart < this.totalChars) && (rangeLength <= this.totalChars)
var childIndex = 0;
var childCharCount = this.children[childIndex].charCount();
+ // find sub-tree containing start
var adjustedStart = rangeStart;
while (adjustedStart >= childCharCount) {
- this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0);
+ this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0 /* PreStart */);
adjustedStart -= childCharCount;
childIndex++;
childCharCount = this.children[childIndex].charCount();
}
+ // Case I: both start and end of range in same subtree
if ((adjustedStart + rangeLength) <= childCharCount) {
- if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2)) {
+ if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2 /* Entire */)) {
return;
}
}
else {
- if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1)) {
+ // Case II: start and end of range in different subtrees (possibly with subtrees in the middle)
+ if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1 /* Start */)) {
return;
}
var adjustedLength = rangeLength - (childCharCount - adjustedStart);
@@ -127785,7 +131130,7 @@
var child = this.children[childIndex];
childCharCount = child.charCount();
while (adjustedLength > childCharCount) {
- if (this.execWalk(0, childCharCount, walkFns, childIndex, 3)) {
+ if (this.execWalk(0, childCharCount, walkFns, childIndex, 3 /* Mid */)) {
return;
}
adjustedLength -= childCharCount;
@@ -127793,22 +131138,26 @@
childCharCount = this.children[childIndex].charCount();
}
if (adjustedLength > 0) {
- if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4)) {
+ if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4 /* End */)) {
return;
}
}
}
+ // Process any subtrees after the one containing range end
if (walkFns.pre) {
var clen = this.children.length;
if (childIndex < (clen - 1)) {
for (var ej = childIndex + 1; ej < clen; ej++) {
- this.skipChild(0, 0, ej, walkFns, 5);
+ this.skipChild(0, 0, ej, walkFns, 5 /* PostEnd */);
}
}
}
};
+ // Input position is relative to the start of this node.
+ // Output line number is absolute.
LineNode.prototype.charOffsetToLineInfo = function (lineNumberAccumulator, relativePosition) {
if (this.children.length === 0) {
+ // Root node might have no children if this is an empty document.
return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: undefined };
}
for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
@@ -127826,9 +131175,15 @@
lineNumberAccumulator += child.lineCount();
}
}
+ // Skipped all children
var leaf = this.lineNumberToInfo(this.lineCount(), 0).leaf;
return { oneBasedLine: this.lineCount(), zeroBasedColumn: leaf ? leaf.charCount() : 0, lineText: undefined };
};
+ /**
+ * Input line number is relative to the start of this node.
+ * Output line number is relative to the child.
+ * positionAccumulator will be an absolute position once relativeLineNumber reaches 0.
+ */
LineNode.prototype.lineNumberToInfo = function (relativeOneBasedLine, positionAccumulator) {
for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
var child = _a[_i];
@@ -127878,6 +131233,7 @@
var childIndex = this.findChildIndex(child);
var clen = this.children.length;
var nodeCount = nodes.length;
+ // if child is last and there is more room and only one node to place, place it
if ((clen < lineCollectionCapacity) && (childIndex === (clen - 1)) && (nodeCount === 1)) {
this.add(nodes[0]);
this.updateCounts();
@@ -127926,6 +131282,7 @@
return splitNodes;
}
};
+ // assume there is room for the item; return true if more room
LineNode.prototype.add = function (collection) {
this.children.push(collection);
ts.Debug.assert(this.children.length <= lineCollectionCapacity);
@@ -127938,7 +131295,7 @@
};
return LineNode;
}());
- var LineLeaf = (function () {
+ var LineLeaf = /** @class */ (function () {
function LineLeaf(text) {
this.text = text;
}
@@ -127958,7 +131315,6 @@
}());
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
-//# sourceMappingURL=server.js.map
// tslint:disable no-unnecessary-type-assertion (TODO: tslint can't find node types)
var ts;
(function (ts) {
@@ -128531,6 +131887,7 @@
// stat due to inconsistencies of fs.watch
// and efficiency of stat on modern filesystems
function startWatchTimer() {
+ // tslint:disable-next-line:ban
setInterval(function () {
var count = 0;
var nextToCheck = nextFileToCheck;